Debian Codegraph @

pypy/interpreter/astcompiler/test/test_symtable.py

raw symbols SCIP
1 import string
2 import py
3 from pypy.interpreter.astcompiler import ast, symtable, consts
4 from pypy.interpreter.pyparser import pyparse
5 from pypy.interpreter.pyparser.error import SyntaxError
6
7
8 class TestSymbolTable:
9
10 def setup_class(cls):
11 cls.parser = pyparse.PegParser(cls.space)
12
13 def mod_scope(self, source, mode="exec"):
14 ec = self.space.getexecutioncontext()
15 module = ec.compiler.compile_to_ast(source, "<test>", mode, 0)
16 info = pyparse.CompileInfo("<test>", mode, 0)
17 builder = symtable.SymtableBuilder(self.space, module, info)
18 scope = builder.find_scope(module)
19 assert isinstance(scope, symtable.ModuleScope)
20 return scope
21
22 def func_scope(self, func_code):
23 mod_scope = self.mod_scope(func_code)
24 assert len(mod_scope.children) == 1
25 func_name = mod_scope.lookup("f")
26 assert func_name == symtable.SCOPE_LOCAL
27 func_scope = mod_scope.children[0]
28 assert isinstance(func_scope, symtable.FunctionScope)
29 return func_scope
30
31 def class_scope(self, class_code):
32 mod_scope = self.mod_scope(class_code)
33 assert len(mod_scope.children) == 1
34 class_name = mod_scope.lookup("x")
35 assert class_name == symtable.SCOPE_LOCAL
36 class_scope = mod_scope.children[0]
37 assert isinstance(class_scope, symtable.ClassScope)
38 return class_scope
39
40 def gen_scope(self, gen_code):
41 mod_scope = self.mod_scope(gen_code)
42 assert len(mod_scope.children) == 1
43 gen_scope = mod_scope.children[0]
44 assert isinstance(gen_scope, symtable.FunctionScope)
45 assert not gen_scope.children
46 assert gen_scope.name == "<genexpr>"
47 return mod_scope, gen_scope
48
49 def check_unknown(self, scp, *names):
50 for name in names:
51 assert scp.lookup(name) == symtable.SCOPE_UNKNOWN
52
53 def test_toplevel(self):
54 scp = self.mod_scope("x = 4")
55 assert scp.lookup("x") == symtable.SCOPE_LOCAL
56 assert not scp.optimized
57 scp = self.mod_scope("x = 4", "single")
58 assert not scp.optimized
59 assert scp.lookup("x") == symtable.SCOPE_LOCAL
60 scp = self.mod_scope("x*4*6", "eval")
61 assert not scp.optimized
62 assert scp.lookup("x") == symtable.SCOPE_GLOBAL_IMPLICIT
63
64 def test_duplicate_argument(self):
65 input = "def f(x, x): pass"
66 exc = py.test.raises(SyntaxError, self.mod_scope, input).value
67 assert exc.msg == "duplicate argument 'x' in function definition"
68 input = "def f(x,\nx): pass"
69 exc = py.test.raises(SyntaxError, self.mod_scope, input).value
70 assert exc.msg == "duplicate argument 'x' in function definition"
71 assert exc.lineno == 2
72
73 def test_function_defaults(self):
74 scp = self.mod_scope("y = w = 4\ndef f(x=y, *, z=w): return x")
75 self.check_unknown(scp, "x")
76 self.check_unknown(scp, "z")
77 assert scp.lookup("y") == symtable.SCOPE_LOCAL
78 assert scp.lookup("w") == symtable.SCOPE_LOCAL
79 scp = scp.children[0]
80 assert scp.lookup("x") == symtable.SCOPE_LOCAL
81 assert scp.lookup("z") == symtable.SCOPE_LOCAL
82 self.check_unknown(scp, "y")
83 self.check_unknown(scp, "w")
84
85 def test_function_annotations(self):
86 scp = self.mod_scope("def f(x : X) -> Y: pass")
87 assert scp.lookup("X") == symtable.SCOPE_GLOBAL_IMPLICIT
88 assert scp.lookup("Y") == symtable.SCOPE_GLOBAL_IMPLICIT
89 scp = scp.children[0]
90 self.check_unknown(scp, "X")
91 self.check_unknown(scp, "Y")
92
93 def check_comprehension(self, template):
94 def brack(s):
95 return template % (s,)
96 scp, gscp = self.gen_scope(brack("y[1] for y in z"))
97 assert scp.lookup("z") == symtable.SCOPE_GLOBAL_IMPLICIT
98 self.check_unknown(scp, "y", "x")
99 self.check_unknown(gscp, "z")
100 assert gscp.lookup("y") == symtable.SCOPE_LOCAL
101 assert gscp.lookup(".0") == symtable.SCOPE_LOCAL
102 scp, gscp = self.gen_scope(brack("x for x in z if x"))
103 self.check_unknown(scp, "x")
104 assert gscp.lookup("x") == symtable.SCOPE_LOCAL
105 scp, gscp = self.gen_scope(brack("x for y in g for f in n if f[h]"))
106 self.check_unknown(scp, "f")
107 assert gscp.lookup("f") == symtable.SCOPE_LOCAL
108
109 def test_genexp(self):
110 self.check_comprehension("(%s)")
111
112 def test_listcomp(self):
113 self.check_comprehension("[%s]")
114
115 def test_setcomp(self):
116 self.check_comprehension("{%s}")
117
118 def test_dictcomp(self):
119 scp, gscp = self.gen_scope("{x : x[3] for x in y}")
120 assert scp.lookup("y") == symtable.SCOPE_GLOBAL_IMPLICIT
121 self.check_unknown(scp, "a", "b", "x")
122 self.check_unknown(gscp, "y")
123 assert gscp.lookup("x") == symtable.SCOPE_LOCAL
124 assert gscp.lookup(".0") == symtable.SCOPE_LOCAL
125 scp, gscp = self.gen_scope("{x : x[1] for x in y if x[23]}")
126 self.check_unknown(scp, "x")
127 assert gscp.lookup("x") == symtable.SCOPE_LOCAL
128
129 def test_arguments(self):
130 scp = self.func_scope("def f(): pass")
131 assert not scp.children
132 self.check_unknown(scp, "x", "y")
133 assert not scp.symbols
134 assert not scp.roles
135 scp = self.func_scope("def f(x): pass")
136 assert scp.lookup("x") == symtable.SCOPE_LOCAL
137 scp = self.func_scope("def f(*x): pass")
138 assert scp.has_variable_arg
139 assert not scp.has_keywords_arg
140 assert scp.lookup("x") == symtable.SCOPE_LOCAL
141 scp = self.func_scope("def f(**x): pass")
142 assert scp.has_keywords_arg
143 assert not scp.has_variable_arg
144 assert scp.lookup("x") == symtable.SCOPE_LOCAL
145
146 def test_arguments_kwonly(self):
147 scp = self.func_scope("def f(a, *b, c, **d): pass")
148 varnames = ["a", "c", "b", "d"]
149 for name in varnames:
150 assert scp.lookup(name) == symtable.SCOPE_LOCAL
151 assert scp.varnames == varnames
152 scp = self.func_scope("def f(a, b=0, *args, k1, k2=0): pass")
153 assert scp.varnames == ["a", "b", "k1", "k2", "args"]
154
155 def test_function(self):
156 scp = self.func_scope("def f(): x = 4")
157 assert scp.lookup("x") == symtable.SCOPE_LOCAL
158 scp = self.func_scope("def f(): x")
159 assert scp.lookup("x") == symtable.SCOPE_GLOBAL_IMPLICIT
160
161 def test_exception_variable(self):
162 scp = self.mod_scope("try: pass\nexcept ValueError as e: pass")
163 assert scp.lookup("e") == symtable.SCOPE_LOCAL
164
165 def test_nested_scopes(self):
166 def nested_scope(*bodies):
167 names = enumerate("f" + string.ascii_letters)
168 lines = []
169 for body, (level, name) in zip(bodies, names):
170 lines.append(" " * level + "def %s():\n" % (name,))
171 if body:
172 if isinstance(body, str):
173 body = [body]
174 lines.extend(" " * (level + 1) + line + "\n"
175 for line in body)
176 return self.func_scope("".join(lines))
177 scp = nested_scope("x = 1", "return x")
178 assert not scp.has_free
179 assert scp.child_has_free
180 assert scp.lookup("x") == symtable.SCOPE_CELL
181 child = scp.children[0]
182 assert child.has_free
183 assert child.lookup("x") == symtable.SCOPE_FREE
184 scp = nested_scope("x = 1", None, "return x")
185 assert not scp.has_free
186 assert scp.child_has_free
187 assert scp.lookup("x") == symtable.SCOPE_CELL
188 child = scp.children[0]
189 assert not child.has_free
190 assert child.child_has_free
191 assert child.lookup("x") == symtable.SCOPE_FREE
192 child = child.children[0]
193 assert child.has_free
194 assert not child.child_has_free
195 assert child.lookup("x") == symtable.SCOPE_FREE
196 scp = nested_scope("x = 1", "x = 3", "return x")
197 assert scp.child_has_free
198 assert not scp.has_free
199 assert scp.lookup("x") == symtable.SCOPE_LOCAL
200 child = scp.children[0]
201 assert child.child_has_free
202 assert not child.has_free
203 assert child.lookup("x") == symtable.SCOPE_CELL
204 child = child.children[0]
205 assert child.has_free
206 assert child.lookup("x") == symtable.SCOPE_FREE
207
208 def test_class(self):
209 scp = self.mod_scope("class x(A, B): pass")
210 cscp = scp.children[0]
211 for name in ("A", "B"):
212 assert scp.lookup(name) == symtable.SCOPE_GLOBAL_IMPLICIT
213 self.check_unknown(cscp, name)
214 scp = self.func_scope("""def f(x):
215 class X:
216 def n():
217 return x
218 a = x
219 return X()""")
220 self.check_unknown(scp, "a")
221 assert scp.lookup("x") == symtable.SCOPE_CELL
222 assert scp.lookup("X") == symtable.SCOPE_LOCAL
223 cscp = scp.children[0]
224 assert cscp.lookup("a") == symtable.SCOPE_LOCAL
225 assert cscp.lookup("x") == symtable.SCOPE_FREE
226 fscp = cscp.children[0]
227 assert fscp.lookup("x") == symtable.SCOPE_FREE
228 self.check_unknown(fscp, "a")
229 scp = self.func_scope("""def f(n):
230 class X:
231 def n():
232 return y
233 def x():
234 return n""")
235 assert scp.lookup("n") == symtable.SCOPE_CELL
236 cscp = scp.children[0]
237 assert cscp.lookup("n") == symtable.SCOPE_LOCAL
238 assert "n" in cscp.free_vars
239 xscp = cscp.children[1]
240 assert xscp.lookup("n") == symtable.SCOPE_FREE
241
242 def test_class_kwargs(self):
243 scp = self.func_scope("""def f(n):
244 class X(meta=Z, *args, **kwargs):
245 pass""")
246 assert scp.lookup("X") == symtable.SCOPE_LOCAL
247 assert scp.lookup("Z") == symtable.SCOPE_GLOBAL_IMPLICIT
248 assert scp.lookup("args") == symtable.SCOPE_GLOBAL_IMPLICIT
249 assert scp.lookup("kwargs") == symtable.SCOPE_GLOBAL_IMPLICIT
250
251 def test_lambda(self):
252 scp = self.mod_scope("lambda x: y")
253 self.check_unknown(scp, "x", "y")
254 assert len(scp.children) == 1
255 lscp = scp.children[0]
256 assert isinstance(lscp, symtable.FunctionScope)
257 assert lscp.name == "<lambda>"
258 assert lscp.lookup("x") == symtable.SCOPE_LOCAL
259 assert lscp.lookup("y") == symtable.SCOPE_GLOBAL_IMPLICIT
260 scp = self.mod_scope("lambda x=a: b")
261 self.check_unknown(scp, "x", "b")
262 assert scp.lookup("a") == symtable.SCOPE_GLOBAL_IMPLICIT
263 lscp = scp.children[0]
264 self.check_unknown(lscp, "a")
265
266 def test_import(self):
267 scp = self.mod_scope("import x")
268 assert scp.lookup("x") == symtable.SCOPE_LOCAL
269 scp = self.mod_scope("import x as y")
270 assert scp.lookup("y") == symtable.SCOPE_LOCAL
271 self.check_unknown(scp, "x")
272 scp = self.mod_scope("import x.y")
273 assert scp.lookup("x") == symtable.SCOPE_LOCAL
274 self.check_unknown(scp, "y")
275
276 def test_from_import(self):
277 scp = self.mod_scope("from x import y")
278 self.check_unknown("x")
279 assert scp.lookup("y") == symtable.SCOPE_LOCAL
280 scp = self.mod_scope("from a import b as y")
281 assert scp.lookup("y") == symtable.SCOPE_LOCAL
282 self.check_unknown(scp, "a", "b")
283 scp = self.mod_scope("from x import *")
284 self.check_unknown("x")
285
286 def test_global(self):
287 scp = self.func_scope("def f():\n global x\n x = 4")
288 assert scp.lookup("x") == symtable.SCOPE_GLOBAL_EXPLICIT
289 scp = self.func_scope("""def f():
290 y = 3
291 def x():
292 global y
293 y = 4
294 def z():
295 return y""")
296 assert scp.lookup("y") == symtable.SCOPE_CELL
297 xscp, zscp = scp.children
298 assert xscp.lookup("y") == symtable.SCOPE_GLOBAL_EXPLICIT
299 assert zscp.lookup("y") == symtable.SCOPE_FREE
300
301 src = "def f(x):\n global x"
302 exc = py.test.raises(SyntaxError, self.func_scope, src).value
303 assert exc.msg == "name 'x' is parameter and global"
304 assert exc.lineno == 2
305
306 def test_global_nested(self):
307 src = """
308 def f(x):
309 def g(x):
310 global x"""
311 exc = py.test.raises(SyntaxError, self.func_scope, src).value
312 assert exc.lineno == 4
313 assert exc.msg == "name 'x' is parameter and global"
314
315 scp = self.func_scope("""
316 def f(x):
317 def g():
318 global x""")
319 g = scp.children[0]
320 assert g.name == 'g'
321 x = g.lookup_role('x')
322 assert x == symtable.SYM_GLOBAL
323
324 def test_global_after_assignment(self):
325 src = ("def f():\n"
326 " x = 1\n"
327 " global x\n")
328 exc = py.test.raises(SyntaxError, self.func_scope, src).value
329 assert exc.lineno == 3
330 assert exc.msg == "name 'x' is assigned to before global declaration"
331
332 def test_nonlocal(self):
333 src = """
334 x = 1
335 def f():
336 nonlocal x"""
337 exc = py.test.raises(SyntaxError, self.func_scope, src).value
338 assert exc.msg == "no binding for nonlocal 'x' found"
339 assert exc.lineno == 4
340
341 src = str(py.code.Source("""
342 def f(x):
343 nonlocal x
344 """))
345 exc = py.test.raises(SyntaxError, self.func_scope, src).value
346 assert exc.msg == "name 'x' is parameter and nonlocal"
347 assert exc.lineno == 3
348 #
349 src = str(py.code.Source("""
350 def f():
351 nonlocal x
352 """))
353 exc = py.test.raises(SyntaxError, self.func_scope, src).value
354 assert exc.msg == "no binding for nonlocal 'x' found"
355 #
356 src = "nonlocal x"
357 exc = py.test.raises(SyntaxError, self.func_scope, src).value
358 assert exc.msg == "nonlocal declaration not allowed at module level"
359 assert exc.lineno == 1
360
361 src = "x = 2\nnonlocal x"
362 exc = py.test.raises(SyntaxError, self.func_scope, src).value
363 assert exc.msg == "nonlocal declaration not allowed at module level"
364 assert exc.lineno == 2
365
366 def test_nonlocal_and_global(self):
367 """This test differs from CPython3 behaviour. CPython points to the
368 first occurance of the global/local expression. PyPy will point to the
369 last expression which makes the problem."""
370 src = """
371 def f():
372 nonlocal x
373 global x"""
374 exc = py.test.raises(SyntaxError, self.func_scope, src).value
375 assert exc.msg == "name 'x' is nonlocal and global"
376 assert exc.lineno == 4
377 assert exc.offset == 5
378 assert exc.end_offset == 13
379
380 src = """
381 def f():
382 global x
383 nonlocal x """
384 exc = py.test.raises(SyntaxError, self.func_scope, src).value
385 assert exc.msg == "name 'x' is nonlocal and global"
386 assert exc.lineno == 4
387
388 def test_nonlocal_nested(self):
389 scp = self.func_scope("""
390 def f(x):
391 def g():
392 nonlocal x""")
393 g = scp.children[0]
394 x = g.lookup_role('x')
395 assert x == symtable.SYM_NONLOCAL
396
397 scp = self.func_scope("""
398 def f():
399 def g():
400 nonlocal x
401 x = 1""")
402 g = scp.children[0]
403 x = g.lookup_role('x')
404 assert x == symtable.SYM_NONLOCAL
405
406 src = """
407 def f(x):
408 def g(x):
409 nonlocal x"""
410 exc = py.test.raises(SyntaxError, self.func_scope, src).value
411 assert exc.msg == "name 'x' is parameter and nonlocal"
412 assert exc.lineno == 4
413
414 def test_nonlocal_after_assignment(self):
415 src = ("def f():\n"
416 " x = 1\n"
417 " nonlocal x\n")
418 exc = py.test.raises(SyntaxError, self.func_scope, src).value
419 assert exc.lineno == 3
420 assert exc.msg == "name 'x' is assigned to before nonlocal declaration"
421
422 def test_optimization(self):
423 assert not self.mod_scope("").can_be_optimized
424 assert not self.class_scope("class x: pass").can_be_optimized
425 assert self.func_scope("def f(): pass").can_be_optimized
426
427 def test_importstar_nonglobal(self):
428 src = str(py.code.Source("""
429 def f():
430 from re import *
431 """))
432 exc = py.test.raises(SyntaxError, self.mod_scope, src)
433 assert exc.value.msg == "import * only allowed at module level"
434 #
435 src = str(py.code.Source("""
436 def f():
437 def g():
438 from re import *
439 """))
440 exc = py.test.raises(SyntaxError, self.mod_scope, src)
441 assert exc.value.msg == "import * only allowed at module level"
442
443 src = str(py.code.Source("""
444 if True:
445 from re import *
446 """))
447 scp = self.mod_scope(src)
448 assert scp # did not raise
449
450 def test_yield(self):
451 scp = self.func_scope("def f(): yield x")
452 assert scp.is_generator
453 for input in ("yield x", "class y: yield x"):
454 exc = py.test.raises(SyntaxError, self.mod_scope, "yield x").value
455 assert exc.msg == "'yield' outside function"
456 for input in ("yield\n return x", "return x\n yield"):
457 input = "def f():\n " + input
458 scp = self.func_scope(input)
459 scp = self.func_scope("def f():\n return\n yield x")
460
461 def test_async_def(self):
462 # CPython compatibility only; "is_generator" is otherwise ignored
463 scp = self.func_scope("async def f(): pass")
464 assert not scp.is_generator
465 scp = self.func_scope("async def f(): await 5")
466 assert not scp.is_generator
467
468 def test_yield_inside_try(self):
469 scp = self.func_scope("def f(): yield x")
470 assert not scp.has_yield_inside_try
471 scp = self.func_scope("def f():\n try:\n yield x\n except: pass")
472 assert scp.has_yield_inside_try
473 scp = self.func_scope("def f():\n try:\n yield x\n finally: pass")
474 assert scp.has_yield_inside_try
475 scp = self.func_scope("def f():\n with x: yield y")
476 assert scp.has_yield_inside_try
477
478 def test_yield_outside_try(self):
479 for input in ("try: pass\n except: pass",
480 "try: pass\n except: yield y",
481 "try: pass\n finally: pass",
482 "try: pass\n finally: yield y",
483 "with x: pass"):
484 input = "def f():\n yield y\n %s\n yield y" % (input,)
485 assert not self.func_scope(input).has_yield_inside_try
486
487 def test_tmpnames(self):
488 scp = self.mod_scope("with x: pass")
489 assert scp.lookup("_[1]") == symtable.SCOPE_LOCAL
490
491 def test_annotation_global(self):
492 src_global = ("def f():\n"
493 " x: int\n"
494 " global x\n")
495 exc_global = py.test.raises(SyntaxError, self.func_scope, src_global).value
496 assert exc_global.msg == "annotated name 'x' can't be global"
497 assert exc_global.lineno == 3
498
499 def test_annotation_global2(self):
500 src_global = ("def f():\n"
501 " global x\n"
502 " x: int\n")
503 exc_global = py.test.raises(SyntaxError, self.func_scope, src_global).value
504 assert exc_global.msg == "annotated name 'x' can't be global"
505 assert exc_global.lineno == 3
506
507 def test_annotation_global4(self):
508 src_global = ("class A:\n"
509 " global x\n"
510 " x: int\n")
511 exc_global = py.test.raises(SyntaxError, self.func_scope, src_global).value
512 assert exc_global.msg == "annotated name 'x' can't be global"
513 assert exc_global.lineno == 3
514
515 def test_annotation_nonlocal(self):
516 src_nonlocal = ("def f():\n"
517 " x: int\n"
518 " nonlocal x\n")
519 exc_nonlocal = py.test.raises(SyntaxError, self.func_scope, src_nonlocal).value
520 assert exc_nonlocal.msg == "annotated name 'x' can't be nonlocal"
521 assert exc_nonlocal.lineno == 3
522
523 def test_annotation_assignment(self):
524 scp = self.mod_scope("x: int = 1")
525 assert scp.contains_annotated == True
526
527 scp2 = self.mod_scope("x = 1")
528 assert scp2.contains_annotated == False
529
530 fscp = self.func_scope("def f(): x: int")
531 assert fscp.contains_annotated == False
532 assert fscp.lookup("x") == symtable.SCOPE_LOCAL
533
534 def test_nonsimple_annotation(self):
535 fscp = self.func_scope("def f(): implicit_global[0]: int")
536 assert fscp.lookup("implicit_global") == symtable.SCOPE_GLOBAL_IMPLICIT
537
538 fscp = self.func_scope("def f(): (implicit_global): int")
539 assert fscp.lookup("implicit_global") == symtable.SCOPE_UNKNOWN
540
541 def test_issue13343(self):
542 scp = self.mod_scope("lambda *, k1=x, k2: None")
543 assert scp.lookup("x") == symtable.SCOPE_GLOBAL_IMPLICIT
544
545 def test_named_expr_list_comprehension(self):
546 fscp = self.func_scope("def f(): [(y := x) for x in range(5)]")
547 assert fscp.lookup("y") == symtable.SCOPE_CELL