scope: refuse `&x` where x is a local variable
[nit.git] / src / semantize / 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 scoping of local variables and labels.
18 module scope
19
20 import phase
21 import modelbuilder
22
23 redef class ToolContext
24 # Run `APropdef::do_scope` on each propdef.
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 is writable
38
39 # Alias of `name`
40 redef fun to_s do return self.name
41
42 # The declaration of the variable, if any
43 var location: nullable Location = null is writable
44
45 # Is the local variable not read and need a warning?
46 var warn_unread = false is writable
47 end
48
49 # Mark where break and continue will branch.
50 # Marks are either associated with a label of with a for_loop structure
51 class EscapeMark
52 # The name of the label (unless the mark is an anonymous loop mark)
53 var name: nullable String
54
55 # The associated `continue` mark, if any.
56 # If the mark attached to a loop (loop, while, for), a distinct mark is used.
57 private var continue_mark: nullable EscapeMark = null
58
59 # Each break/continue attached to the mark
60 var escapes = new Array[AEscapeExpr]
61 end
62
63 # Visit a npropdef and:
64 # * Identify variables and labels
65 # * Associate each break and continue to its escapemark
66 # * Transform `ACallFormExpr` that access a variable into `AVarFormExpr`
67 # FIXME: Should the class be private?
68 private class ScopeVisitor
69 super Visitor
70
71 # The tool context used to display errors
72 var toolcontext: ToolContext
73
74 # The analysed property
75 var propdef: APropdef
76
77 var selfvariable = new Variable("self")
78
79 init
80 do
81 scopes.add(new Scope)
82 end
83
84 # All stacked scope. `scopes.first` is the current scope
85 var scopes = new List[Scope]
86
87 # Shift and check the last scope
88 fun shift_scope
89 do
90 assert not scopes.is_empty
91 var scope = scopes.shift
92 for v in scope.variables.values do
93 if v.warn_unread then
94 toolcontext.advice(v.location, "unread-variable", "Warning: local variable {v.name} is never read.")
95 end
96 end
97 end
98
99 # Register a local variable.
100 # Display an error on toolcontext if a variable with the same name is masked.
101 fun register_variable(node: ANode, variable: Variable): Bool
102 do
103 var name = variable.name
104 var found = search_variable(name)
105 if found != null then
106 self.error(node, "Error: a variable named `{name}` already exists.")
107 return false
108 end
109 scopes.first.variables[name] = variable
110 variable.location = node.location
111 return true
112 end
113
114 # Look for a variable named `name`.
115 # Return null if no such a variable is found.
116 fun search_variable(name: String): nullable Variable
117 do
118 for scope in scopes do
119 var res = scope.get_variable(name)
120 if res != null then
121 return res
122 end
123 end
124 return null
125 end
126
127 redef fun visit(n)
128 do
129 n.accept_scope_visitor(self)
130 end
131
132 # Enter in a statement block `node` as inside a new scope.
133 # The block can be optionally attached to an `escapemark`.
134 fun enter_visit_block(node: nullable AExpr, escapemark: nullable EscapeMark)
135 do
136 if node == null then return
137 var scope = new Scope
138 scope.escapemark = escapemark
139 scopes.unshift(scope)
140 enter_visit(node)
141 shift_scope
142 end
143
144 # Look for a label `name`.
145 # Return null if no such a label is found.
146 fun search_label(name: String): nullable EscapeMark
147 do
148 for scope in scopes do
149 var res = scope.escapemark
150 if res != null and res.name == name then
151 return res
152 end
153 end
154 return null
155 end
156
157 # Create a new escape mark (possibly with a label)
158 # Display an error on toolcontext if a label with the same name is masked.
159 fun make_escape_mark(nlabel: nullable ALabel, for_loop: Bool): EscapeMark
160 do
161 var name: nullable String
162 if nlabel != null then
163 var nid = nlabel.n_id
164 if nid == null then
165 var res = search_label("")
166 if res != null then
167 self.error(nlabel, "Syntax Error: anonymous label already defined.")
168 end
169 name = ""
170 else
171 name = nid.text
172 var found = self.search_label(name)
173 if found != null then
174 self.error(nlabel, "Syntax Error: label `{name}` already defined.")
175 end
176 end
177 else
178 name = null
179 end
180 var res = new EscapeMark(name)
181 if for_loop then res.continue_mark = new EscapeMark(name)
182 return res
183 end
184
185 # Look for an escape mark optionally associated with a label.
186 # If a label is given, the escapemark of this label is returned.
187 # If there is no label, the nearest escapemark that is `for loop` is returned.
188 # If there is no valid escapemark, then an error is displayed ans null is returned.
189 # Return null if no such a label is found.
190 fun get_escapemark(node: ANode, nlabel: nullable ALabel): nullable EscapeMark
191 do
192 if nlabel != null then
193 var nid = nlabel.n_id
194 if nid == null then
195 var res = search_label("")
196 if res == null then
197 self.error(nlabel, "Syntax Error: invalid anonymous label.")
198 node.is_broken = true
199 return null
200 end
201 return res
202 end
203 var name = nid.text
204 var res = search_label(name)
205 if res == null then
206 self.error(nlabel, "Syntax Error: invalid label `{name}`.")
207 node.is_broken = true
208 return null
209 end
210 return res
211 else
212 for scope in scopes do
213 var res = scope.escapemark
214 if res != null then
215 return res
216 end
217 end
218 self.error(node, "Syntax Error: `break` statement outside block.")
219 return null
220 end
221 end
222
223 # Display an error
224 fun error(node: ANode, message: String)
225 do
226 self.toolcontext.error(node.hot_location, message)
227 node.is_broken = true
228 end
229 end
230
231 private class Scope
232 var variables = new HashMap[String, Variable]
233
234 var escapemark: nullable EscapeMark = null
235
236 fun get_variable(name: String): nullable Variable
237 do
238 if self.variables.has_key(name) then
239 return self.variables[name]
240 else
241 return null
242 end
243 end
244 end
245
246 redef class ANode
247 private fun accept_scope_visitor(v: ScopeVisitor)
248 do
249 visit_all(v)
250 end
251 end
252
253 redef class APropdef
254 # The break escape mark associated with the return
255 var return_mark: nullable EscapeMark
256
257 # Entry point of the scope analysis
258 fun do_scope(toolcontext: ToolContext)
259 do
260 var v = new ScopeVisitor(toolcontext, self)
261 v.enter_visit(self)
262 v.shift_scope
263 end
264 end
265
266 redef class AParam
267 # The variable associated with the parameter
268 var variable: nullable Variable
269 redef fun accept_scope_visitor(v)
270 do
271 super
272 var nid = self.n_id
273 var variable = new Variable(nid.text)
274 v.register_variable(nid, variable)
275 self.variable = variable
276 end
277 end
278
279 redef class AVardeclExpr
280 # The variable associated with the variable declaration
281 var variable: nullable Variable
282 redef fun accept_scope_visitor(v)
283 do
284 super
285 var nid = self.n_id
286 var variable = new Variable(nid.text)
287 v.register_variable(nid, variable)
288 variable.warn_unread = true # wait for some read mark.
289 self.variable = variable
290 end
291 end
292
293 redef class ASelfExpr
294 # The variable associated with the self receiver
295 var variable: nullable Variable
296 redef fun accept_scope_visitor(v)
297 do
298 super
299 self.variable = v.selfvariable
300 end
301 end
302
303 redef class AEscapeExpr
304 # The escape mark associated with the break/continue
305 var escapemark: nullable EscapeMark
306 end
307
308 redef class AContinueExpr
309 redef fun accept_scope_visitor(v)
310 do
311 super
312 var escapemark = v.get_escapemark(self, self.n_label)
313 if escapemark == null then return # Skip error
314 escapemark = escapemark.continue_mark
315 if escapemark == null then
316 v.error(self, "Error: cannot 'continue', only 'break'.")
317 return
318 end
319 escapemark.escapes.add(self)
320 self.escapemark = escapemark
321 end
322 end
323
324 redef class ABreakExpr
325 redef fun accept_scope_visitor(v)
326 do
327 super
328 var escapemark = v.get_escapemark(self, self.n_label)
329 if escapemark == null then return # Skip error
330 escapemark.escapes.add(self)
331 self.escapemark = escapemark
332 end
333 end
334
335 redef class AReturnExpr
336 redef fun accept_scope_visitor(v)
337 do
338 super
339
340 var escapemark = v.propdef.return_mark
341 if escapemark == null then
342 escapemark = new EscapeMark
343 v.propdef.return_mark = escapemark
344 end
345
346 escapemark.escapes.add(self)
347 self.escapemark = escapemark
348 end
349 end
350
351 redef class ADoExpr
352 # The break escape mark associated with the 'do' block
353 var break_mark: nullable EscapeMark
354
355 redef fun accept_scope_visitor(v)
356 do
357 self.break_mark = v.make_escape_mark(n_label, false)
358 v.enter_visit_block(n_block, self.break_mark)
359 v.enter_visit_block(n_catch)
360 end
361 end
362
363 redef class AIfExpr
364 redef fun accept_scope_visitor(v)
365 do
366 v.enter_visit(n_expr)
367 v.enter_visit_block(n_then, null)
368 v.enter_visit_block(n_else, null)
369 end
370 end
371
372 redef class AWhileExpr
373 # The break escape mark associated with the 'while'
374 var break_mark: nullable EscapeMark
375
376 # The continue escape mark associated with the 'while'
377 var continue_mark: nullable EscapeMark
378
379 redef fun accept_scope_visitor(v)
380 do
381 var escapemark = v.make_escape_mark(n_label, true)
382 self.break_mark = escapemark
383 self.continue_mark = escapemark.continue_mark
384 v.enter_visit(n_expr)
385 v.enter_visit_block(n_block, escapemark)
386 end
387 end
388
389 redef class ALoopExpr
390 # The break escape mark associated with the 'loop'
391 var break_mark: nullable EscapeMark
392
393 # The continue escape mark associated with the 'loop'
394 var continue_mark: nullable EscapeMark
395
396 redef fun accept_scope_visitor(v)
397 do
398 var escapemark = v.make_escape_mark(n_label, true)
399 self.break_mark = escapemark
400 self.continue_mark = escapemark.continue_mark
401 v.enter_visit_block(n_block, escapemark)
402 end
403 end
404
405 redef class AForExpr
406 # The break escape mark associated with the 'for'
407 var break_mark: nullable EscapeMark
408
409 # The continue escape mark associated with the 'for'
410 var continue_mark: nullable EscapeMark
411
412 redef fun accept_scope_visitor(v)
413 do
414 for g in n_groups do
415 v.enter_visit(g.n_expr)
416 end
417
418 # Protect automatic variables
419 v.scopes.unshift(new Scope)
420
421 for g in n_groups do
422 # Create the automatic variables
423 var variables = new Array[Variable]
424 g.variables = variables
425 for nid in g.n_ids do
426 var va = new Variable(nid.text)
427 v.register_variable(nid, va)
428 variables.add(va)
429 end
430 end
431
432 var escapemark = v.make_escape_mark(n_label, true)
433 self.break_mark = escapemark
434 self.continue_mark = escapemark.continue_mark
435 v.enter_visit_block(n_block, escapemark)
436
437 v.shift_scope
438 end
439 end
440
441 redef class AForGroup
442 # The automatic variables in order
443 var variables: nullable Array[Variable]
444 end
445
446 redef class AWithExpr
447 # The break escape mark associated with the 'with'
448 var break_mark: nullable EscapeMark
449
450 redef fun accept_scope_visitor(v)
451 do
452 v.scopes.unshift(new Scope)
453
454 var escapemark = v.make_escape_mark(n_label, true)
455 self.break_mark = escapemark
456
457 v.enter_visit(n_expr)
458 v.enter_visit_block(n_block, escapemark)
459
460 v.shift_scope
461 end
462 end
463
464 redef class AAssertExpr
465 redef fun accept_scope_visitor(v)
466 do
467 v.enter_visit(n_expr)
468 v.enter_visit_block(n_else, null)
469 end
470 end
471
472 redef class AVarFormExpr
473 # The associated variable
474 var variable: nullable Variable is writable
475 end
476
477 redef class ACallFormExpr
478 redef fun accept_scope_visitor(v)
479 do
480 if n_expr isa AImplicitSelfExpr then
481 var name = n_qid.n_id.text
482 var variable = v.search_variable(name)
483 if variable != null then
484 var n: AExpr
485 if not n_args.n_exprs.is_empty or n_args isa AParExprs or self isa ACallrefExpr then
486 v.error(self, "Error: `{name}` is a variable, not a method.")
487 return
488 end
489 n = variable_create(variable)
490 n.variable = variable
491 replace_with(n)
492 n.accept_scope_visitor(v)
493 return
494 end
495 end
496
497 super
498 end
499
500 # Create a variable access corresponding to the call form
501 private fun variable_create(variable: Variable): AVarFormExpr is abstract
502 end
503
504 redef class ACallExpr
505 redef fun variable_create(variable)
506 do
507 variable.warn_unread = false
508 return new AVarExpr.init_avarexpr(n_qid.n_id)
509 end
510 end
511
512 redef class ACallAssignExpr
513 redef fun variable_create(variable)
514 do
515 return new AVarAssignExpr.init_avarassignexpr(n_qid.n_id, n_assign, n_value)
516 end
517 end
518
519 redef class ACallReassignExpr
520 redef fun variable_create(variable)
521 do
522 variable.warn_unread = false
523 return new AVarReassignExpr.init_avarreassignexpr(n_qid.n_id, n_assign_op, n_value)
524 end
525 end