2d2c00a2dc115360db88cccc79ddc7aacab177ea
[nit.git] / src / scope.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2012 Jean Privat <jean@pryen.org>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Identification and scping of local variables and labels.
18 module scope
19
20 import parser
21 import toolcontext
22 import phase
23
24 redef class ToolContext
25 var scope_phase: Phase = new ScopePhase(self, null)
26 end
27
28 private class ScopePhase
29 super Phase
30 redef fun process_npropdef(npropdef) do npropdef.do_scope(toolcontext)
31 end
32
33
34 # A local variable (including parameters, automatic variables and self)
35 class Variable
36 # The name of the variable (as used in the program)
37 var name: String
38
39 # Alias of `name`
40 redef fun to_s do return self.name
41 end
42
43 # Mark where break and continue will branch.
44 # Marks are either associated with a label of with a for_loop structure
45 class EscapeMark
46 # The name of the label (unless the mark is an anonymous loop mark)
47 var name: nullable String
48
49 # Is the mark atached to a loop (loop, while, for)
50 # Such a mark is a candidate to a labelless 'continue' or 'break'
51 var for_loop: Bool
52
53 # Each 'continue' attached to the mark
54 var continues: Array[AContinueExpr] = new Array[AContinueExpr]
55
56 # Each 'break' attached to the mark
57 var breaks: Array[ABreakExpr] = new Array[ABreakExpr]
58 end
59
60 # Visit a npropdef and:
61 # * Identify variables and labels
62 # * Associate each break and continue to its escapemark
63 # * Transform `ACallFormExpr` that access a variable into `AVarFormExpr`
64 # FIXME: Should the class be private?
65 private class ScopeVisitor
66 super Visitor
67
68 # The tool context used to display errors
69 var toolcontext: ToolContext
70
71 var selfvariable: Variable = new Variable("self")
72
73 init(toolcontext: ToolContext)
74 do
75 self.toolcontext = toolcontext
76 scopes.add(new Scope)
77 end
78
79 # All stacked scope. `scopes.first` is the current scope
80 private var scopes: List[Scope] = new List[Scope]
81
82 # Regiter a local variable.
83 # Display an error on toolcontext if a variable with the same name is masked.
84 fun register_variable(node: ANode, variable: Variable): Bool
85 do
86 var name = variable.name
87 var found = search_variable(name)
88 if found != null then
89 self.error(node, "Error: A variable named `{name}' already exists")
90 return false
91 end
92 scopes.first.variables[name] = variable
93 return true
94 end
95
96 # Look for a variable named `name`.
97 # Return null if no such a variable is found.
98 fun search_variable(name: String): nullable Variable
99 do
100 for scope in scopes do
101 var res = scope.get_variable(name)
102 if res != null then
103 return res
104 end
105 end
106 return null
107 end
108
109 redef fun visit(n)
110 do
111 n.accept_scope_visitor(self)
112 end
113
114 # Enter in a statement block `node` as inside a new scope.
115 # The block can be optionally attached to an `escapemark`.
116 private fun enter_visit_block(node: nullable AExpr, escapemark: nullable EscapeMark)
117 do
118 if node == null then return
119 var scope = new Scope
120 scope.escapemark = escapemark
121 scopes.unshift(scope)
122 enter_visit(node)
123 scopes.shift
124 end
125
126 # Look for a label `name`.
127 # Return nulll if no such a label is found.
128 private fun search_label(name: String): nullable EscapeMark
129 do
130 for scope in scopes do
131 var res = scope.escapemark
132 if res != null and res.name == name then
133 return res
134 end
135 end
136 return null
137 end
138
139 # Create a new escape mark (possibly with a label)
140 # Display an error on toolcontext if a label with the same name is masked.
141 private fun make_escape_mark(nlabel: nullable ALabel, for_loop: Bool): EscapeMark
142 do
143 var name: nullable String
144 if nlabel != null then
145 var nid = nlabel.n_id
146 if nid == null then
147 var res = search_label("")
148 if res != null then
149 self.error(nlabel, "Syntax error: anonymous label already defined.")
150 end
151 name = ""
152 else
153 name = nid.text
154 var found = self.search_label(name)
155 if found != null then
156 self.error(nlabel, "Syntax error: label {name} already defined.")
157 end
158 end
159 else
160 name = null
161 end
162 var res = new EscapeMark(name, for_loop)
163 return res
164 end
165
166 # Look for an escape mark optionally associated with a label.
167 # If a label is given, the the escapemark of this label is returned.
168 # If there is no label, the nearest escapemark that is `for loop` is returned.
169 # If there is no valid escapemark, then an error is displayed ans null is returned.
170 # Return nulll if no such a label is found.
171 private fun get_escapemark(node: ANode, nlabel: nullable ALabel): nullable EscapeMark
172 do
173 if nlabel != null then
174 var nid = nlabel.n_id
175 if nid == null then
176 var res = search_label("")
177 if res == null then
178 self.error(nlabel, "Syntax error: invalid anonymous label.")
179 return null
180 end
181 return res
182 end
183 var name = nid.text
184 var res = search_label(name)
185 if res == null then
186 self.error(nlabel, "Syntax error: invalid label {name}.")
187 return null
188 end
189 return res
190 else
191 for scope in scopes do
192 var res = scope.escapemark
193 if res != null then
194 return res
195 end
196 end
197 self.error(node, "Syntax Error: 'break' statment outside block.")
198 return null
199 end
200 end
201
202 # Display an error
203 private fun error(node: ANode, message: String)
204 do
205 self.toolcontext.error(node.hot_location, message)
206 end
207 end
208
209 private class Scope
210 var variables: HashMap[String, Variable] = new HashMap[String, Variable]
211
212 var escapemark: nullable EscapeMark = null
213
214 fun get_variable(name: String): nullable Variable
215 do
216 if self.variables.has_key(name) then
217 return self.variables[name]
218 else
219 return null
220 end
221 end
222 end
223
224 redef class ANode
225 private fun accept_scope_visitor(v: ScopeVisitor)
226 do
227 visit_all(v)
228 end
229 end
230
231 redef class APropdef
232 # Entry point of the scope analysis
233 fun do_scope(toolcontext: ToolContext)
234 do
235 var v = new ScopeVisitor(toolcontext)
236 v.enter_visit(self)
237 end
238 end
239
240 redef class AParam
241 # The variable associated with the parameter
242 var variable: nullable Variable
243 redef fun accept_scope_visitor(v)
244 do
245 super
246 var nid = self.n_id
247 var variable = new Variable(nid.text)
248 v.register_variable(nid, variable)
249 self.variable = variable
250 end
251 end
252
253 redef class AVardeclExpr
254 # The variable associated with the variable declaration
255 var variable: nullable Variable
256 redef fun accept_scope_visitor(v)
257 do
258 super
259 var nid = self.n_id
260 var variable = new Variable(nid.text)
261 v.register_variable(nid, variable)
262 self.variable = variable
263 end
264 end
265
266 redef class ASelfExpr
267 # The variable associated with the self reciever
268 var variable: nullable Variable
269 redef fun accept_scope_visitor(v)
270 do
271 super
272 self.variable = v.selfvariable
273 end
274 end
275
276 redef class AContinueExpr
277 # The escape mark associated with the continue
278 var escapemark: nullable EscapeMark
279 redef fun accept_scope_visitor(v)
280 do
281 super
282 var escapemark = v.get_escapemark(self, self.n_label)
283 if escapemark == null then return # Skip error
284 if not escapemark.for_loop then
285 v.error(self, "Error: cannot 'continue', only 'break'.")
286 end
287 escapemark.continues.add(self)
288 self.escapemark = escapemark
289 end
290 end
291
292 redef class ABreakExpr
293 # The escape mark associated with the break
294 var escapemark: nullable EscapeMark
295 redef fun accept_scope_visitor(v)
296 do
297 super
298 var escapemark = v.get_escapemark(self, self.n_label)
299 if escapemark == null then return # Skip error
300 escapemark.breaks.add(self)
301 self.escapemark = escapemark
302 end
303 end
304
305
306 redef class ADoExpr
307 # The escape mark associated with the 'do' block
308 var escapemark: nullable EscapeMark
309 redef fun accept_scope_visitor(v)
310 do
311 self.escapemark = v.make_escape_mark(n_label, false)
312 v.enter_visit_block(n_block, self.escapemark)
313 end
314 end
315
316 redef class AIfExpr
317 redef fun accept_scope_visitor(v)
318 do
319 v.enter_visit(n_expr)
320 v.enter_visit_block(n_then, null)
321 v.enter_visit_block(n_else, null)
322 end
323 end
324
325 redef class AWhileExpr
326 # The escape mark associated with the 'while'
327 var escapemark: nullable EscapeMark
328 redef fun accept_scope_visitor(v)
329 do
330 var escapemark = v.make_escape_mark(n_label, true)
331 self.escapemark = escapemark
332 v.enter_visit(n_expr)
333 v.enter_visit_block(n_block, escapemark)
334 end
335 end
336
337 redef class ALoopExpr
338 # The escape mark associated with the 'loop'
339 var escapemark: nullable EscapeMark
340 redef fun accept_scope_visitor(v)
341 do
342 var escapemark = v.make_escape_mark(n_label, true)
343 self.escapemark = escapemark
344 v.enter_visit_block(n_block, escapemark)
345 end
346 end
347
348 redef class AForExpr
349 # The automatic variables in order
350 var variables: nullable Array[Variable]
351
352 # The escape mark associated with the 'for'
353 var escapemark: nullable EscapeMark
354
355 redef fun accept_scope_visitor(v)
356 do
357 v.enter_visit(n_expr)
358
359 # Protect automatic variables
360 v.scopes.unshift(new Scope)
361
362 # Create the automatic variables
363 var variables = new Array[Variable]
364 self.variables = variables
365 for nid in n_ids do
366 var va = new Variable(nid.text)
367 v.register_variable(nid, va)
368 variables.add(va)
369 end
370
371 var escapemark = v.make_escape_mark(n_label, true)
372 self.escapemark = escapemark
373 v.enter_visit_block(n_block, escapemark)
374
375 v.scopes.shift
376 end
377 end
378
379 redef class AVarFormExpr
380 # The associated variable
381 var variable: nullable Variable
382 end
383
384 redef class ACallFormExpr
385 redef fun accept_scope_visitor(v)
386 do
387 if n_expr isa AImplicitSelfExpr then
388 var name = n_id.text
389 var variable = v.search_variable(name)
390 if variable != null then
391 var n: AExpr
392 if not n_args.n_exprs.is_empty or n_args isa AParExprs then
393 v.error(self, "Error: {name} is variable, not a function.")
394 return
395 end
396 n = variable_create(variable)
397 n.variable = variable
398 replace_with(n)
399 n.accept_scope_visitor(v)
400 return
401 end
402 end
403
404 super
405 end
406
407 # Create a variable acces corresponding to the call form
408 private fun variable_create(variable: Variable): AVarFormExpr is abstract
409 end
410
411 redef class ACallExpr
412 redef fun variable_create(variable)
413 do
414 return new AVarExpr.init_avarexpr(n_id)
415 end
416 end
417
418 redef class ACallAssignExpr
419 redef fun variable_create(variable)
420 do
421 return new AVarAssignExpr.init_avarassignexpr(n_id, n_assign, n_value)
422 end
423 end
424
425 redef class ACallReassignExpr
426 redef fun variable_create(variable)
427 do
428 return new AVarReassignExpr.init_avarreassignexpr(n_id, n_assign_op, n_value)
429 end
430 end