Debian Codegraph @

lib-python/3/test/test_ast.py

raw symbols SCIP
1 import ast
2 import builtins
3 import dis
4 import enum
5 import os
6 import re
7 import sys
8 import types
9 import unittest
10 import warnings
11 import weakref
12 from textwrap import dedent
13
14 from test import support
15
16 def to_tuple(t):
17 if t is None or isinstance(t, (str, int, complex)) or t is Ellipsis:
18 return t
19 elif isinstance(t, list):
20 return [to_tuple(e) for e in t]
21 result = [t.__class__.__name__]
22 if hasattr(t, 'lineno') and hasattr(t, 'col_offset'):
23 result.append((t.lineno, t.col_offset))
24 if hasattr(t, 'end_lineno') and hasattr(t, 'end_col_offset'):
25 result[-1] += (t.end_lineno, t.end_col_offset)
26 if t._fields is None:
27 return tuple(result)
28 for f in t._fields:
29 result.append(to_tuple(getattr(t, f)))
30 return tuple(result)
31
32
33 # These tests are compiled through "exec"
34 # There should be at least one test per statement
35 exec_tests = [
36 # None
37 "None",
38 # Module docstring
39 "'module docstring'",
40 # FunctionDef
41 "def f(): pass",
42 # FunctionDef with docstring
43 "def f(): 'function docstring'",
44 # FunctionDef with arg
45 "def f(a): pass",
46 # FunctionDef with arg and default value
47 "def f(a=0): pass",
48 # FunctionDef with varargs
49 "def f(*args): pass",
50 # FunctionDef with varargs as TypeVarTuple
51 "def f(*args: *Ts): pass",
52 # FunctionDef with varargs as unpacked Tuple
53 "def f(*args: *tuple[int, ...]): pass",
54 # FunctionDef with varargs as unpacked Tuple *and* TypeVarTuple
55 "def f(*args: *tuple[int, *Ts]): pass",
56 # FunctionDef with kwargs
57 "def f(**kwargs): pass",
58 # FunctionDef with all kind of args and docstring
59 "def f(a, b=1, c=None, d=[], e={}, *args, f=42, **kwargs): 'doc for f()'",
60 # FunctionDef with type annotation on return involving unpacking
61 "def f() -> tuple[*Ts]: pass",
62 "def f() -> tuple[int, *Ts]: pass",
63 "def f() -> tuple[int, *tuple[int, ...]]: pass",
64 # ClassDef
65 "class C:pass",
66 # ClassDef with docstring
67 "class C: 'docstring for class C'",
68 # ClassDef, new style class
69 "class C(object): pass",
70 # Return
71 "def f():return 1",
72 # Delete
73 "del v",
74 # Assign
75 "v = 1",
76 "a,b = c",
77 "(a,b) = c",
78 "[a,b] = c",
79 # AnnAssign with unpacked types
80 "x: tuple[*Ts]",
81 "x: tuple[int, *Ts]",
82 "x: tuple[int, *tuple[str, ...]]",
83 # AugAssign
84 "v += 1",
85 # For
86 "for v in v:pass",
87 # While
88 "while v:pass",
89 # If
90 "if v:pass",
91 # If-Elif
92 "if a:\n pass\nelif b:\n pass",
93 # If-Elif-Else
94 "if a:\n pass\nelif b:\n pass\nelse:\n pass",
95 # With
96 "with x as y: pass",
97 "with x as y, z as q: pass",
98 # Raise
99 "raise Exception('string')",
100 # TryExcept
101 "try:\n pass\nexcept Exception:\n pass",
102 # TryFinally
103 "try:\n pass\nfinally:\n pass",
104 # TryStarExcept
105 "try:\n pass\nexcept* Exception:\n pass",
106 # Assert
107 "assert v",
108 # Import
109 "import sys",
110 # ImportFrom
111 "from sys import v",
112 # Global
113 "global v",
114 # Expr
115 "1",
116 # Pass,
117 "pass",
118 # Break
119 "for v in v:break",
120 # Continue
121 "for v in v:continue",
122 # for statements with naked tuples (see http://bugs.python.org/issue6704)
123 "for a,b in c: pass",
124 "for (a,b) in c: pass",
125 "for [a,b] in c: pass",
126 # Multiline generator expression (test for .lineno & .col_offset)
127 """(
128 (
129 Aa
130 ,
131 Bb
132 )
133 for
134 Aa
135 ,
136 Bb in Cc
137 )""",
138 # dictcomp
139 "{a : b for w in x for m in p if g}",
140 # dictcomp with naked tuple
141 "{a : b for v,w in x}",
142 # setcomp
143 "{r for l in x if g}",
144 # setcomp with naked tuple
145 "{r for l,m in x}",
146 # AsyncFunctionDef
147 "async def f():\n 'async function'\n await something()",
148 # AsyncFor
149 "async def f():\n async for e in i: 1\n else: 2",
150 # AsyncWith
151 "async def f():\n async with a as b: 1",
152 # PEP 448: Additional Unpacking Generalizations
153 "{**{1:2}, 2:3}",
154 "{*{1, 2}, 3}",
155 # Asynchronous comprehensions
156 "async def f():\n [i async for b in c]",
157 # Decorated FunctionDef
158 "@deco1\n@deco2()\n@deco3(1)\ndef f(): pass",
159 # Decorated AsyncFunctionDef
160 "@deco1\n@deco2()\n@deco3(1)\nasync def f(): pass",
161 # Decorated ClassDef
162 "@deco1\n@deco2()\n@deco3(1)\nclass C: pass",
163 # Decorator with generator argument
164 "@deco(a for a in b)\ndef f(): pass",
165 # Decorator with attribute
166 "@a.b.c\ndef f(): pass",
167 # Simple assignment expression
168 "(a := 1)",
169 # Positional-only arguments
170 "def f(a, /,): pass",
171 "def f(a, /, c, d, e): pass",
172 "def f(a, /, c, *, d, e): pass",
173 "def f(a, /, c, *, d, e, **kwargs): pass",
174 # Positional-only arguments with defaults
175 "def f(a=1, /,): pass",
176 "def f(a=1, /, b=2, c=4): pass",
177 "def f(a=1, /, b=2, *, c=4): pass",
178 "def f(a=1, /, b=2, *, c): pass",
179 "def f(a=1, /, b=2, *, c=4, **kwargs): pass",
180 "def f(a=1, /, b=2, *, c, **kwargs): pass",
181
182 ]
183
184 # These are compiled through "single"
185 # because of overlap with "eval", it just tests what
186 # can't be tested with "eval"
187 single_tests = [
188 "1+2"
189 ]
190
191 # These are compiled through "eval"
192 # It should test all expressions
193 eval_tests = [
194 # None
195 "None",
196 # BoolOp
197 "a and b",
198 # BinOp
199 "a + b",
200 # UnaryOp
201 "not v",
202 # Lambda
203 "lambda:None",
204 # Dict
205 "{ 1:2 }",
206 # Empty dict
207 "{}",
208 # Set
209 "{None,}",
210 # Multiline dict (test for .lineno & .col_offset)
211 """{
212 1
213 :
214 2
215 }""",
216 # ListComp
217 "[a for b in c if d]",
218 # GeneratorExp
219 "(a for b in c if d)",
220 # Comprehensions with multiple for targets
221 "[(a,b) for a,b in c]",
222 "[(a,b) for (a,b) in c]",
223 "[(a,b) for [a,b] in c]",
224 "{(a,b) for a,b in c}",
225 "{(a,b) for (a,b) in c}",
226 "{(a,b) for [a,b] in c}",
227 "((a,b) for a,b in c)",
228 "((a,b) for (a,b) in c)",
229 "((a,b) for [a,b] in c)",
230 # Yield - yield expressions can't work outside a function
231 #
232 # Compare
233 "1 < 2 < 3",
234 # Call
235 "f(1,2,c=3,*d,**e)",
236 # Call with multi-character starred
237 "f(*[0, 1])",
238 # Call with a generator argument
239 "f(a for a in b)",
240 # Num
241 "10",
242 # Str
243 "'string'",
244 # Attribute
245 "a.b",
246 # Subscript
247 "a[b:c]",
248 # Name
249 "v",
250 # List
251 "[1,2,3]",
252 # Empty list
253 "[]",
254 # Tuple
255 "1,2,3",
256 # Tuple
257 "(1,2,3)",
258 # Empty tuple
259 "()",
260 # Combination
261 "a.b.c.d(a.b[1:2])",
262
263 ]
264
265 # TODO: expr_context, slice, boolop, operator, unaryop, cmpop, comprehension
266 # excepthandler, arguments, keywords, alias
267
268 class AST_Tests(unittest.TestCase):
269
270 def _is_ast_node(self, name, node):
271 if not isinstance(node, type):
272 return False
273 if "ast" not in node.__module__:
274 return False
275 return name != 'AST' and name[0].isupper()
276
277 def _assertTrueorder(self, ast_node, parent_pos):
278 if not isinstance(ast_node, ast.AST) or ast_node._fields is None:
279 return
280 if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)):
281 node_pos = (ast_node.lineno, ast_node.col_offset)
282 self.assertGreaterEqual(node_pos, parent_pos)
283 parent_pos = (ast_node.lineno, ast_node.col_offset)
284 for name in ast_node._fields:
285 value = getattr(ast_node, name)
286 if isinstance(value, list):
287 first_pos = parent_pos
288 if value and name == 'decorator_list':
289 first_pos = (value[0].lineno, value[0].col_offset)
290 for child in value:
291 self._assertTrueorder(child, first_pos)
292 elif value is not None:
293 self._assertTrueorder(value, parent_pos)
294 self.assertEqual(ast_node._fields, ast_node.__match_args__)
295
296 def test_AST_objects(self):
297 if not support.check_impl_detail():
298 # PyPy also provides a __dict__ to the ast.AST base class.
299 return
300
301 x = ast.AST()
302 self.assertEqual(x._fields, ())
303 x.foobar = 42
304 self.assertEqual(x.foobar, 42)
305 self.assertEqual(x.__dict__["foobar"], 42)
306
307 with self.assertRaises(AttributeError):
308 x.vararg
309
310 with self.assertRaises(TypeError):
311 # "ast.AST constructor takes 0 positional arguments"
312 ast.AST(2)
313
314 def test_AST_garbage_collection(self):
315 class X:
316 pass
317 a = ast.AST()
318 a.x = X()
319 a.x.a = a
320 ref = weakref.ref(a.x)
321 del a
322 support.gc_collect()
323 self.assertIsNone(ref())
324
325 def test_snippets(self):
326 for input, output, kind in ((exec_tests, exec_results, "exec"),
327 (single_tests, single_results, "single"),
328 (eval_tests, eval_results, "eval")):
329 for i, o in zip(input, output):
330 with self.subTest(action="parsing", input=i):
331 ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST)
332 self.assertEqual(to_tuple(ast_tree), o)
333 self._assertTrueorder(ast_tree, (0, 0))
334 with self.subTest(action="compiling", input=i, kind=kind):
335 compile(ast_tree, "?", kind)
336
337 def test_ast_validation(self):
338 # compile() is the only function that calls PyAST_Validate
339 snippets_to_validate = exec_tests + single_tests + eval_tests
340 for snippet in snippets_to_validate:
341 tree = ast.parse(snippet)
342 compile(tree, '<string>', 'exec')
343
344 @support.cpython_only
345 def test_invalid_position_information(self):
346 invalid_linenos = [
347 (10, 1), (-10, -11), (10, -11), (-5, -2), (-5, 1)
348 ]
349
350 for lineno, end_lineno in invalid_linenos:
351 with self.subTest(f"Check invalid linenos {lineno}:{end_lineno}"):
352 snippet = "a = 1"
353 tree = ast.parse(snippet)
354 tree.body[0].lineno = lineno
355 tree.body[0].end_lineno = end_lineno
356 with self.assertRaises(ValueError):
357 compile(tree, '<string>', 'exec')
358
359 invalid_col_offsets = [
360 (10, 1), (-10, -11), (10, -11), (-5, -2), (-5, 1)
361 ]
362 for col_offset, end_col_offset in invalid_col_offsets:
363 with self.subTest(f"Check invalid col_offset {col_offset}:{end_col_offset}"):
364 snippet = "a = 1"
365 tree = ast.parse(snippet)
366 tree.body[0].col_offset = col_offset
367 tree.body[0].end_col_offset = end_col_offset
368 with self.assertRaises(ValueError):
369 compile(tree, '<string>', 'exec')
370
371 def test_compilation_of_ast_nodes_with_default_end_position_values(self):
372 tree = ast.Module(body=[
373 ast.Import(names=[ast.alias(name='builtins', lineno=1, col_offset=0)], lineno=1, col_offset=0),
374 ast.Import(names=[ast.alias(name='traceback', lineno=0, col_offset=0)], lineno=0, col_offset=1)
375 ], type_ignores=[])
376
377 # Check that compilation doesn't crash. Note: this may crash explicitly only on debug mode.
378 compile(tree, "<string>", "exec")
379
380 def test_slice(self):
381 slc = ast.parse("x[::]").body[0].value.slice
382 self.assertIsNone(slc.upper)
383 self.assertIsNone(slc.lower)
384 self.assertIsNone(slc.step)
385
386 def test_from_import(self):
387 im = ast.parse("from . import y").body[0]
388 self.assertIsNone(im.module)
389
390 def test_non_interned_future_from_ast(self):
391 mod = ast.parse("from __future__ import division")
392 self.assertIsInstance(mod.body[0], ast.ImportFrom)
393 mod.body[0].module = " __future__ ".strip()
394 compile(mod, "<test>", "exec")
395
396 def test_alias(self):
397 im = ast.parse("from bar import y").body[0]
398 self.assertEqual(len(im.names), 1)
399 alias = im.names[0]
400 self.assertEqual(alias.name, 'y')
401 self.assertIsNone(alias.asname)
402 self.assertEqual(alias.lineno, 1)
403 self.assertEqual(alias.end_lineno, 1)
404 self.assertEqual(alias.col_offset, 16)
405 self.assertEqual(alias.end_col_offset, 17)
406
407 im = ast.parse("from bar import *").body[0]
408 alias = im.names[0]
409 self.assertEqual(alias.name, '*')
410 self.assertIsNone(alias.asname)
411 self.assertEqual(alias.lineno, 1)
412 self.assertEqual(alias.end_lineno, 1)
413 self.assertEqual(alias.col_offset, 16)
414 self.assertEqual(alias.end_col_offset, 17)
415
416 im = ast.parse("from bar import y as z").body[0]
417 alias = im.names[0]
418 self.assertEqual(alias.name, "y")
419 self.assertEqual(alias.asname, "z")
420 self.assertEqual(alias.lineno, 1)
421 self.assertEqual(alias.end_lineno, 1)
422 self.assertEqual(alias.col_offset, 16)
423 self.assertEqual(alias.end_col_offset, 22)
424
425 im = ast.parse("import bar as foo").body[0]
426 alias = im.names[0]
427 self.assertEqual(alias.name, "bar")
428 self.assertEqual(alias.asname, "foo")
429 self.assertEqual(alias.lineno, 1)
430 self.assertEqual(alias.end_lineno, 1)
431 self.assertEqual(alias.col_offset, 7)
432 self.assertEqual(alias.end_col_offset, 17)
433
434 def test_base_classes(self):
435 self.assertTrue(issubclass(ast.For, ast.stmt))
436 self.assertTrue(issubclass(ast.Name, ast.expr))
437 self.assertTrue(issubclass(ast.stmt, ast.AST))
438 self.assertTrue(issubclass(ast.expr, ast.AST))
439 self.assertTrue(issubclass(ast.comprehension, ast.AST))
440 self.assertTrue(issubclass(ast.Gt, ast.AST))
441
442 def test_field_attr_existence(self):
443 for name, item in ast.__dict__.items():
444 if self._is_ast_node(name, item):
445 if name == 'Index':
446 # Index(value) just returns value now.
447 # The argument is required.
448 continue
449 x = item()
450 if isinstance(x, ast.AST):
451 self.assertEqual(type(x._fields), tuple)
452
453 def test_arguments(self):
454 x = ast.arguments()
455 self.assertEqual(x._fields, ('posonlyargs', 'args', 'vararg', 'kwonlyargs',
456 'kw_defaults', 'kwarg', 'defaults'))
457
458 with self.assertRaises(AttributeError):
459 x.args
460 self.assertIsNone(x.vararg)
461
462 x = ast.arguments(*range(1, 8))
463 self.assertEqual(x.args, 2)
464 self.assertEqual(x.vararg, 3)
465
466 def test_field_attr_writable(self):
467 x = ast.Num()
468 # We can assign to _fields
469 x._fields = 666
470 self.assertEqual(x._fields, 666)
471
472 def test_classattrs(self):
473 x = ast.Num()
474 self.assertEqual(x._fields, ('value', 'kind'))
475
476 with self.assertRaises(AttributeError):
477 x.value
478
479 with self.assertRaises(AttributeError):
480 x.n
481
482 x = ast.Num(42)
483 self.assertEqual(x.value, 42)
484 self.assertEqual(x.n, 42)
485
486 with self.assertRaises(AttributeError):
487 x.lineno
488
489 with self.assertRaises(AttributeError):
490 x.foobar
491
492 x = ast.Num(lineno=2)
493 self.assertEqual(x.lineno, 2)
494
495 x = ast.Num(42, lineno=0)
496 self.assertEqual(x.lineno, 0)
497 self.assertEqual(x._fields, ('value', 'kind'))
498 self.assertEqual(x.value, 42)
499 self.assertEqual(x.n, 42)
500
501 self.assertRaises(TypeError, ast.Num, 1, None, 2)
502 self.assertRaises(TypeError, ast.Num, 1, None, 2, lineno=0)
503
504 # Arbitrary keyword arguments are supported
505 self.assertEqual(ast.Constant(1, foo='bar').foo, 'bar')
506 self.assertEqual(ast.Num(1, foo='bar').foo, 'bar')
507
508 with self.assertRaisesRegex(TypeError, "Num got multiple values for argument 'n'"):
509 ast.Num(1, n=2)
510 with self.assertRaisesRegex(TypeError, "Constant got multiple values for argument 'value'"):
511 ast.Constant(1, value=2)
512
513 self.assertEqual(ast.Num(42).n, 42)
514 self.assertEqual(ast.Num(4.25).n, 4.25)
515 self.assertEqual(ast.Num(4.25j).n, 4.25j)
516 self.assertEqual(ast.Str('42').s, '42')
517 self.assertEqual(ast.Bytes(b'42').s, b'42')
518 self.assertIs(ast.NameConstant(True).value, True)
519 self.assertIs(ast.NameConstant(False).value, False)
520 self.assertIs(ast.NameConstant(None).value, None)
521
522 self.assertEqual(ast.Constant(42).value, 42)
523 self.assertEqual(ast.Constant(4.25).value, 4.25)
524 self.assertEqual(ast.Constant(4.25j).value, 4.25j)
525 self.assertEqual(ast.Constant('42').value, '42')
526 self.assertEqual(ast.Constant(b'42').value, b'42')
527 self.assertIs(ast.Constant(True).value, True)
528 self.assertIs(ast.Constant(False).value, False)
529 self.assertIs(ast.Constant(None).value, None)
530 self.assertIs(ast.Constant(...).value, ...)
531
532 def test_realtype(self):
533 self.assertEqual(type(ast.Num(42)), ast.Constant)
534 self.assertEqual(type(ast.Num(4.25)), ast.Constant)
535 self.assertEqual(type(ast.Num(4.25j)), ast.Constant)
536 self.assertEqual(type(ast.Str('42')), ast.Constant)
537 self.assertEqual(type(ast.Bytes(b'42')), ast.Constant)
538 self.assertEqual(type(ast.NameConstant(True)), ast.Constant)
539 self.assertEqual(type(ast.NameConstant(False)), ast.Constant)
540 self.assertEqual(type(ast.NameConstant(None)), ast.Constant)
541 self.assertEqual(type(ast.Ellipsis()), ast.Constant)
542
543 def test_isinstance(self):
544 self.assertTrue(isinstance(ast.Num(42), ast.Num))
545 self.assertTrue(isinstance(ast.Num(4.2), ast.Num))
546 self.assertTrue(isinstance(ast.Num(4.2j), ast.Num))
547 self.assertTrue(isinstance(ast.Str('42'), ast.Str))
548 self.assertTrue(isinstance(ast.Bytes(b'42'), ast.Bytes))
549 self.assertTrue(isinstance(ast.NameConstant(True), ast.NameConstant))
550 self.assertTrue(isinstance(ast.NameConstant(False), ast.NameConstant))
551 self.assertTrue(isinstance(ast.NameConstant(None), ast.NameConstant))
552 self.assertTrue(isinstance(ast.Ellipsis(), ast.Ellipsis))
553
554 self.assertTrue(isinstance(ast.Constant(42), ast.Num))
555 self.assertTrue(isinstance(ast.Constant(4.2), ast.Num))
556 self.assertTrue(isinstance(ast.Constant(4.2j), ast.Num))
557 self.assertTrue(isinstance(ast.Constant('42'), ast.Str))
558 self.assertTrue(isinstance(ast.Constant(b'42'), ast.Bytes))
559 self.assertTrue(isinstance(ast.Constant(True), ast.NameConstant))
560 self.assertTrue(isinstance(ast.Constant(False), ast.NameConstant))
561 self.assertTrue(isinstance(ast.Constant(None), ast.NameConstant))
562 self.assertTrue(isinstance(ast.Constant(...), ast.Ellipsis))
563
564 self.assertFalse(isinstance(ast.Str('42'), ast.Num))
565 self.assertFalse(isinstance(ast.Num(42), ast.Str))
566 self.assertFalse(isinstance(ast.Str('42'), ast.Bytes))
567 self.assertFalse(isinstance(ast.Num(42), ast.NameConstant))
568 self.assertFalse(isinstance(ast.Num(42), ast.Ellipsis))
569 self.assertFalse(isinstance(ast.NameConstant(True), ast.Num))
570 self.assertFalse(isinstance(ast.NameConstant(False), ast.Num))
571
572 self.assertFalse(isinstance(ast.Constant('42'), ast.Num))
573 self.assertFalse(isinstance(ast.Constant(42), ast.Str))
574 self.assertFalse(isinstance(ast.Constant('42'), ast.Bytes))
575 self.assertFalse(isinstance(ast.Constant(42), ast.NameConstant))
576 self.assertFalse(isinstance(ast.Constant(42), ast.Ellipsis))
577 self.assertFalse(isinstance(ast.Constant(True), ast.Num))
578 self.assertFalse(isinstance(ast.Constant(False), ast.Num))
579
580 self.assertFalse(isinstance(ast.Constant(), ast.Num))
581 self.assertFalse(isinstance(ast.Constant(), ast.Str))
582 self.assertFalse(isinstance(ast.Constant(), ast.Bytes))
583 self.assertFalse(isinstance(ast.Constant(), ast.NameConstant))
584 self.assertFalse(isinstance(ast.Constant(), ast.Ellipsis))
585
586 class S(str): pass
587 self.assertTrue(isinstance(ast.Constant(S('42')), ast.Str))
588 self.assertFalse(isinstance(ast.Constant(S('42')), ast.Num))
589
590 def test_subclasses(self):
591 class N(ast.Num):
592 def __init__(self, *args, **kwargs):
593 super().__init__(*args, **kwargs)
594 self.z = 'spam'
595 class N2(ast.Num):
596 pass
597
598 n = N(42)
599 self.assertEqual(n.n, 42)
600 self.assertEqual(n.z, 'spam')
601 self.assertEqual(type(n), N)
602 self.assertTrue(isinstance(n, N))
603 self.assertTrue(isinstance(n, ast.Num))
604 self.assertFalse(isinstance(n, N2))
605 self.assertFalse(isinstance(ast.Num(42), N))
606 n = N(n=42)
607 self.assertEqual(n.n, 42)
608 self.assertEqual(type(n), N)
609
610 def test_module(self):
611 body = [ast.Num(42)]
612 x = ast.Module(body, [])
613 self.assertEqual(x.body, body)
614
615 def test_nodeclasses(self):
616 # Zero arguments constructor explicitly allowed
617 x = ast.BinOp()
618 self.assertEqual(x._fields, ('left', 'op', 'right'))
619
620 # Random attribute allowed too
621 x.foobarbaz = 5
622 self.assertEqual(x.foobarbaz, 5)
623
624 n1 = ast.Num(1)
625 n3 = ast.Num(3)
626 addop = ast.Add()
627 x = ast.BinOp(n1, addop, n3)
628 self.assertEqual(x.left, n1)
629 self.assertEqual(x.op, addop)
630 self.assertEqual(x.right, n3)
631
632 x = ast.BinOp(1, 2, 3)
633 self.assertEqual(x.left, 1)
634 self.assertEqual(x.op, 2)
635 self.assertEqual(x.right, 3)
636
637 x = ast.BinOp(1, 2, 3, lineno=0)
638 self.assertEqual(x.left, 1)
639 self.assertEqual(x.op, 2)
640 self.assertEqual(x.right, 3)
641 self.assertEqual(x.lineno, 0)
642
643 # node raises exception when given too many arguments
644 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4)
645 # node raises exception when given too many arguments
646 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4, lineno=0)
647
648 # can set attributes through kwargs too
649 x = ast.BinOp(left=1, op=2, right=3, lineno=0)
650 self.assertEqual(x.left, 1)
651 self.assertEqual(x.op, 2)
652 self.assertEqual(x.right, 3)
653 self.assertEqual(x.lineno, 0)
654
655 # Random kwargs also allowed
656 x = ast.BinOp(1, 2, 3, foobarbaz=42)
657 self.assertEqual(x.foobarbaz, 42)
658
659 def test_no_fields(self):
660 # this used to fail because Sub._fields was None
661 x = ast.Sub()
662 self.assertEqual(x._fields, ())
663
664 def test_pickling(self):
665 import pickle
666 mods = [pickle]
667 try:
668 import cPickle
669 mods.append(cPickle)
670 except ImportError:
671 pass
672 protocols = [0, 1, 2]
673 for mod in mods:
674 for protocol in protocols:
675 for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests):
676 ast2 = mod.loads(mod.dumps(ast, protocol))
677 self.assertEqual(to_tuple(ast2), to_tuple(ast))
678
679 def test_invalid_sum(self):
680 pos = dict(lineno=2, col_offset=3)
681 m = ast.Module([ast.Expr(ast.expr(**pos), **pos)], [])
682 with self.assertRaises(TypeError) as cm:
683 compile(m, "<test>", "exec")
684 self.assertIn("but got <ast.expr", str(cm.exception))
685
686 def test_invalid_identifier(self):
687 if sys.implementation.name == "pypy":
688 msg = "expected str, got int object"
689 else:
690 msg = "identifier must be of type str"
691 m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))], [])
692 ast.fix_missing_locations(m)
693 with self.assertRaises(TypeError) as cm:
694 compile(m, "<test>", "exec")
695 self.assertIn(msg, str(cm.exception))
696
697 def test_invalid_constant(self):
698 for invalid_constant in int, (1, 2, int), frozenset((1, 2, int)):
699 e = ast.Expression(body=ast.Constant(invalid_constant))
700 ast.fix_missing_locations(e)
701 with self.assertRaisesRegex(
702 TypeError, "invalid type in Constant: type"
703 ):
704 compile(e, "<test>", "eval")
705
706 def test_empty_yield_from(self):
707 # Issue 16546: yield from value is not optional.
708 empty_yield_from = ast.parse("def f():\n yield from g()")
709 empty_yield_from.body[0].body[0].value.value = None
710 with self.assertRaises(ValueError) as cm:
711 compile(empty_yield_from, "<test>", "exec")
712 self.assertIn("field 'value' is required", str(cm.exception))
713
714 @support.cpython_only
715 def test_issue31592(self):
716 # There shouldn't be an assertion failure in case of a bad
717 # unicodedata.normalize().
718 import unicodedata
719 def bad_normalize(*args):
720 return None
721 with support.swap_attr(unicodedata, 'normalize', bad_normalize):
722 self.assertRaises(TypeError, ast.parse, '\u03D5')
723
724 def test_issue18374_binop_col_offset(self):
725 tree = ast.parse('4+5+6+7')
726 parent_binop = tree.body[0].value
727 child_binop = parent_binop.left
728 grandchild_binop = child_binop.left
729 self.assertEqual(parent_binop.col_offset, 0)
730 self.assertEqual(parent_binop.end_col_offset, 7)
731 self.assertEqual(child_binop.col_offset, 0)
732 self.assertEqual(child_binop.end_col_offset, 5)
733 self.assertEqual(grandchild_binop.col_offset, 0)
734 self.assertEqual(grandchild_binop.end_col_offset, 3)
735
736 tree = ast.parse('4+5-\\\n 6-7')
737 parent_binop = tree.body[0].value
738 child_binop = parent_binop.left
739 grandchild_binop = child_binop.left
740 self.assertEqual(parent_binop.col_offset, 0)
741 self.assertEqual(parent_binop.lineno, 1)
742 self.assertEqual(parent_binop.end_col_offset, 4)
743 self.assertEqual(parent_binop.end_lineno, 2)
744
745 self.assertEqual(child_binop.col_offset, 0)
746 self.assertEqual(child_binop.lineno, 1)
747 self.assertEqual(child_binop.end_col_offset, 2)
748 self.assertEqual(child_binop.end_lineno, 2)
749
750 self.assertEqual(grandchild_binop.col_offset, 0)
751 self.assertEqual(grandchild_binop.lineno, 1)
752 self.assertEqual(grandchild_binop.end_col_offset, 3)
753 self.assertEqual(grandchild_binop.end_lineno, 1)
754
755 def test_issue39579_dotted_name_end_col_offset(self):
756 tree = ast.parse('@a.b.c\ndef f(): pass')
757 attr_b = tree.body[0].decorator_list[0].value
758 self.assertEqual(attr_b.end_col_offset, 4)
759
760 def test_ast_asdl_signature(self):
761 self.assertEqual(ast.withitem.__doc__, "withitem(expr context_expr, expr? optional_vars)")
762 self.assertEqual(ast.GtE.__doc__, "GtE")
763 self.assertEqual(ast.Name.__doc__, "Name(identifier id, expr_context ctx)")
764 self.assertEqual(ast.cmpop.__doc__, "cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn")
765 expressions = [f" | {node.__doc__}" for node in ast.expr.__subclasses__()]
766 expressions[0] = f"expr = {ast.expr.__subclasses__()[0].__doc__}"
767 self.assertCountEqual(ast.expr.__doc__.split("\n"), expressions)
768
769 def test_positional_only_feature_version(self):
770 ast.parse('def foo(x, /): ...', feature_version=(3, 8))
771 ast.parse('def bar(x=1, /): ...', feature_version=(3, 8))
772 with self.assertRaises(SyntaxError):
773 ast.parse('def foo(x, /): ...', feature_version=(3, 7))
774 with self.assertRaises(SyntaxError):
775 ast.parse('def bar(x=1, /): ...', feature_version=(3, 7))
776
777 ast.parse('lambda x, /: ...', feature_version=(3, 8))
778 ast.parse('lambda x=1, /: ...', feature_version=(3, 8))
779 with self.assertRaises(SyntaxError):
780 ast.parse('lambda x, /: ...', feature_version=(3, 7))
781 with self.assertRaises(SyntaxError):
782 ast.parse('lambda x=1, /: ...', feature_version=(3, 7))
783
784 def test_debug_f_string_feature_version(self):
785 ast.parse('f"{x=}"', feature_version=(3, 8))
786 with self.assertRaises(SyntaxError):
787 ast.parse('f"{x=}"', feature_version=(3, 7))
788
789 def test_assignment_expression_feature_version(self):
790 ast.parse('(x := 0)', feature_version=(3, 8))
791 with self.assertRaises(SyntaxError):
792 ast.parse('(x := 0)', feature_version=(3, 7))
793
794 def test_conditional_context_managers_parse_with_low_feature_version(self):
795 # regression test for gh-115881
796 ast.parse('with (x() if y else z()): ...', feature_version=(3, 8))
797
798 def test_exception_groups_feature_version(self):
799 code = dedent('''
800 try: ...
801 except* Exception: ...
802 ''')
803 ast.parse(code)
804 with self.assertRaises(SyntaxError):
805 ast.parse(code, feature_version=(3, 10))
806
807 def test_constant_as_name(self):
808 for constant in "True", "False", "None":
809 expr = ast.Expression(ast.Name(constant, ast.Load()))
810 ast.fix_missing_locations(expr)
811 with self.assertRaisesRegex(ValueError, f"identifier field can't represent '{constant}' constant"):
812 compile(expr, "<test>", "eval")
813
814 def test_precedence_enum(self):
815 class _Precedence(enum.IntEnum):
816 """Precedence table that originated from python grammar."""
817 NAMED_EXPR = enum.auto() # <target> := <expr1>
818 TUPLE = enum.auto() # <expr1>, <expr2>
819 YIELD = enum.auto() # 'yield', 'yield from'
820 TEST = enum.auto() # 'if'-'else', 'lambda'
821 OR = enum.auto() # 'or'
822 AND = enum.auto() # 'and'
823 NOT = enum.auto() # 'not'
824 CMP = enum.auto() # '<', '>', '==', '>=', '<=', '!=',
825 # 'in', 'not in', 'is', 'is not'
826 EXPR = enum.auto()
827 BOR = EXPR # '|'
828 BXOR = enum.auto() # '^'
829 BAND = enum.auto() # '&'
830 SHIFT = enum.auto() # '<<', '>>'
831 ARITH = enum.auto() # '+', '-'
832 TERM = enum.auto() # '*', '@', '/', '%', '//'
833 FACTOR = enum.auto() # unary '+', '-', '~'
834 POWER = enum.auto() # '**'
835 AWAIT = enum.auto() # 'await'
836 ATOM = enum.auto()
837 def next(self):
838 try:
839 return self.__class__(self + 1)
840 except ValueError:
841 return self
842 enum._test_simple_enum(_Precedence, ast._Precedence)
843
844 @support.cpython_only
845 def test_ast_recursion_limit(self):
846 fail_depth = sys.getrecursionlimit() * 3
847 crash_depth = sys.getrecursionlimit() * 300
848 success_depth = int(fail_depth * 0.75)
849
850 def check_limit(prefix, repeated):
851 expect_ok = prefix + repeated * success_depth
852 ast.parse(expect_ok)
853 for depth in (fail_depth, crash_depth):
854 broken = prefix + repeated * depth
855 details = "Compiling ({!r} + {!r} * {})".format(
856 prefix, repeated, depth)
857 with self.assertRaises(RecursionError, msg=details):
858 with support.infinite_recursion():
859 ast.parse(broken)
860
861 check_limit("a", "()")
862 check_limit("a", ".b")
863 check_limit("a", "[0]")
864 check_limit("a", "*a")
865
866 def test_null_bytes(self):
867 with self.assertRaises(SyntaxError,
868 msg="source code string cannot contain null bytes"):
869 ast.parse("a\0b")
870
871 def assert_none_check(self, node: type[ast.AST], attr: str, source: str) -> None:
872 with self.subTest(f"{node.__name__}.{attr}"):
873 tree = ast.parse(source)
874 found = 0
875 for child in ast.walk(tree):
876 if isinstance(child, node):
877 setattr(child, attr, None)
878 found += 1
879 self.assertEqual(found, 1)
880 e = re.escape(f"field '{attr}' is required for {node.__name__}")
881 with self.assertRaisesRegex(ValueError, f"^{e}$"):
882 compile(tree, "<test>", "exec")
883
884 def test_none_checks(self) -> None:
885 tests = [
886 (ast.alias, "name", "import spam as SPAM"),
887 (ast.arg, "arg", "def spam(SPAM): spam"),
888 (ast.comprehension, "target", "[spam for SPAM in spam]"),
889 (ast.comprehension, "iter", "[spam for spam in SPAM]"),
890 (ast.keyword, "value", "spam(**SPAM)"),
891 (ast.match_case, "pattern", "match spam:\n case SPAM: spam"),
892 (ast.withitem, "context_expr", "with SPAM: spam"),
893 ]
894 for node, attr, source in tests:
895 self.assert_none_check(node, attr, source)
896
897 class ASTHelpers_Test(unittest.TestCase):
898 maxDiff = None
899
900 def test_parse(self):
901 a = ast.parse('foo(1 + 1)')
902 b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST)
903 self.assertEqual(ast.dump(a), ast.dump(b))
904
905 def test_parse_in_error(self):
906 try:
907 1/0
908 except Exception:
909 with self.assertRaises(SyntaxError) as e:
910 ast.literal_eval(r"'\U'")
911 self.assertIsNotNone(e.exception.__context__)
912
913 def test_dump(self):
914 node = ast.parse('spam(eggs, "and cheese")')
915 self.assertEqual(ast.dump(node),
916 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
917 "args=[Name(id='eggs', ctx=Load()), Constant(value='and cheese')], "
918 "keywords=[]))], type_ignores=[])"
919 )
920 self.assertEqual(ast.dump(node, annotate_fields=False),
921 "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
922 "Constant('and cheese')], []))], [])"
923 )
924 self.assertEqual(ast.dump(node, include_attributes=True),
925 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
926 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=4), "
927 "args=[Name(id='eggs', ctx=Load(), lineno=1, col_offset=5, "
928 "end_lineno=1, end_col_offset=9), Constant(value='and cheese', "
929 "lineno=1, col_offset=11, end_lineno=1, end_col_offset=23)], keywords=[], "
930 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=24), "
931 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=24)], type_ignores=[])"
932 )
933
934 def test_dump_indent(self):
935 node = ast.parse('spam(eggs, "and cheese")')
936 self.assertEqual(ast.dump(node, indent=3), """\
937 Module(
938 body=[
939 Expr(
940 value=Call(
941 func=Name(id='spam', ctx=Load()),
942 args=[
943 Name(id='eggs', ctx=Load()),
944 Constant(value='and cheese')],
945 keywords=[]))],
946 type_ignores=[])""")
947 self.assertEqual(ast.dump(node, annotate_fields=False, indent='\t'), """\
948 Module(
949 \t[
950 \t\tExpr(
951 \t\t\tCall(
952 \t\t\t\tName('spam', Load()),
953 \t\t\t\t[
954 \t\t\t\t\tName('eggs', Load()),
955 \t\t\t\t\tConstant('and cheese')],
956 \t\t\t\t[]))],
957 \t[])""")
958 self.assertEqual(ast.dump(node, include_attributes=True, indent=3), """\
959 Module(
960 body=[
961 Expr(
962 value=Call(
963 func=Name(
964 id='spam',
965 ctx=Load(),
966 lineno=1,
967 col_offset=0,
968 end_lineno=1,
969 end_col_offset=4),
970 args=[
971 Name(
972 id='eggs',
973 ctx=Load(),
974 lineno=1,
975 col_offset=5,
976 end_lineno=1,
977 end_col_offset=9),
978 Constant(
979 value='and cheese',
980 lineno=1,
981 col_offset=11,
982 end_lineno=1,
983 end_col_offset=23)],
984 keywords=[],
985 lineno=1,
986 col_offset=0,
987 end_lineno=1,
988 end_col_offset=24),
989 lineno=1,
990 col_offset=0,
991 end_lineno=1,
992 end_col_offset=24)],
993 type_ignores=[])""")
994
995 def test_dump_incomplete(self):
996 node = ast.Raise(lineno=3, col_offset=4)
997 self.assertEqual(ast.dump(node),
998 "Raise()"
999 )
1000 self.assertEqual(ast.dump(node, include_attributes=True),
1001 "Raise(lineno=3, col_offset=4)"
1002 )
1003 node = ast.Raise(exc=ast.Name(id='e', ctx=ast.Load()), lineno=3, col_offset=4)
1004 self.assertEqual(ast.dump(node),
1005 "Raise(exc=Name(id='e', ctx=Load()))"
1006 )
1007 self.assertEqual(ast.dump(node, annotate_fields=False),
1008 "Raise(Name('e', Load()))"
1009 )
1010 self.assertEqual(ast.dump(node, include_attributes=True),
1011 "Raise(exc=Name(id='e', ctx=Load()), lineno=3, col_offset=4)"
1012 )
1013 self.assertEqual(ast.dump(node, annotate_fields=False, include_attributes=True),
1014 "Raise(Name('e', Load()), lineno=3, col_offset=4)"
1015 )
1016 node = ast.Raise(cause=ast.Name(id='e', ctx=ast.Load()))
1017 self.assertEqual(ast.dump(node),
1018 "Raise(cause=Name(id='e', ctx=Load()))"
1019 )
1020 self.assertEqual(ast.dump(node, annotate_fields=False),
1021 "Raise(cause=Name('e', Load()))"
1022 )
1023
1024 def test_copy_location(self):
1025 src = ast.parse('1 + 1', mode='eval')
1026 src.body.right = ast.copy_location(ast.Num(2), src.body.right)
1027 self.assertEqual(ast.dump(src, include_attributes=True),
1028 'Expression(body=BinOp(left=Constant(value=1, lineno=1, col_offset=0, '
1029 'end_lineno=1, end_col_offset=1), op=Add(), right=Constant(value=2, '
1030 'lineno=1, col_offset=4, end_lineno=1, end_col_offset=5), lineno=1, '
1031 'col_offset=0, end_lineno=1, end_col_offset=5))'
1032 )
1033 src = ast.Call(col_offset=1, lineno=1, end_lineno=1, end_col_offset=1)
1034 new = ast.copy_location(src, ast.Call(col_offset=None, lineno=None))
1035 self.assertIsNone(new.end_lineno)
1036 self.assertIsNone(new.end_col_offset)
1037 self.assertEqual(new.lineno, 1)
1038 self.assertEqual(new.col_offset, 1)
1039
1040 def test_fix_missing_locations(self):
1041 src = ast.parse('write("spam")')
1042 src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()),
1043 [ast.Str('eggs')], [])))
1044 self.assertEqual(src, ast.fix_missing_locations(src))
1045 self.maxDiff = None
1046 self.assertEqual(ast.dump(src, include_attributes=True),
1047 "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), "
1048 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=5), "
1049 "args=[Constant(value='spam', lineno=1, col_offset=6, end_lineno=1, "
1050 "end_col_offset=12)], keywords=[], lineno=1, col_offset=0, end_lineno=1, "
1051 "end_col_offset=13), lineno=1, col_offset=0, end_lineno=1, "
1052 "end_col_offset=13), Expr(value=Call(func=Name(id='spam', ctx=Load(), "
1053 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=0), "
1054 "args=[Constant(value='eggs', lineno=1, col_offset=0, end_lineno=1, "
1055 "end_col_offset=0)], keywords=[], lineno=1, col_offset=0, end_lineno=1, "
1056 "end_col_offset=0), lineno=1, col_offset=0, end_lineno=1, end_col_offset=0)], "
1057 "type_ignores=[])"
1058 )
1059
1060 def test_increment_lineno(self):
1061 src = ast.parse('1 + 1', mode='eval')
1062 self.assertEqual(ast.increment_lineno(src, n=3), src)
1063 self.assertEqual(ast.dump(src, include_attributes=True),
1064 'Expression(body=BinOp(left=Constant(value=1, lineno=4, col_offset=0, '
1065 'end_lineno=4, end_col_offset=1), op=Add(), right=Constant(value=1, '
1066 'lineno=4, col_offset=4, end_lineno=4, end_col_offset=5), lineno=4, '
1067 'col_offset=0, end_lineno=4, end_col_offset=5))'
1068 )
1069 # issue10869: do not increment lineno of root twice
1070 src = ast.parse('1 + 1', mode='eval')
1071 self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
1072 self.assertEqual(ast.dump(src, include_attributes=True),
1073 'Expression(body=BinOp(left=Constant(value=1, lineno=4, col_offset=0, '
1074 'end_lineno=4, end_col_offset=1), op=Add(), right=Constant(value=1, '
1075 'lineno=4, col_offset=4, end_lineno=4, end_col_offset=5), lineno=4, '
1076 'col_offset=0, end_lineno=4, end_col_offset=5))'
1077 )
1078 src = ast.Call(
1079 func=ast.Name("test", ast.Load()), args=[], keywords=[], lineno=1
1080 )
1081 self.assertEqual(ast.increment_lineno(src).lineno, 2)
1082 self.assertIsNone(ast.increment_lineno(src).end_lineno)
1083
1084 def test_increment_lineno_on_module(self):
1085 src = ast.parse(dedent("""\
1086 a = 1
1087 b = 2 # type: ignore
1088 c = 3
1089 d = 4 # type: ignore@tag
1090 """), type_comments=True)
1091 ast.increment_lineno(src, n=5)
1092 self.assertEqual(src.type_ignores[0].lineno, 7)
1093 self.assertEqual(src.type_ignores[1].lineno, 9)
1094 self.assertEqual(src.type_ignores[1].tag, '@tag')
1095
1096 def test_iter_fields(self):
1097 node = ast.parse('foo()', mode='eval')
1098 d = dict(ast.iter_fields(node.body))
1099 self.assertEqual(d.pop('func').id, 'foo')
1100 self.assertEqual(d, {'keywords': [], 'args': []})
1101
1102 def test_iter_child_nodes(self):
1103 node = ast.parse("spam(23, 42, eggs='leek')", mode='eval')
1104 self.assertEqual(len(list(ast.iter_child_nodes(node.body))), 4)
1105 iterator = ast.iter_child_nodes(node.body)
1106 self.assertEqual(next(iterator).id, 'spam')
1107 self.assertEqual(next(iterator).value, 23)
1108 self.assertEqual(next(iterator).value, 42)
1109 self.assertEqual(ast.dump(next(iterator)),
1110 "keyword(arg='eggs', value=Constant(value='leek'))"
1111 )
1112
1113 def test_get_docstring(self):
1114 node = ast.parse('"""line one\n line two"""')
1115 self.assertEqual(ast.get_docstring(node),
1116 'line one\nline two')
1117
1118 node = ast.parse('class foo:\n """line one\n line two"""')
1119 self.assertEqual(ast.get_docstring(node.body[0]),
1120 'line one\nline two')
1121
1122 node = ast.parse('def foo():\n """line one\n line two"""')
1123 self.assertEqual(ast.get_docstring(node.body[0]),
1124 'line one\nline two')
1125
1126 node = ast.parse('async def foo():\n """spam\n ham"""')
1127 self.assertEqual(ast.get_docstring(node.body[0]), 'spam\nham')
1128
1129 def test_get_docstring_none(self):
1130 self.assertIsNone(ast.get_docstring(ast.parse('')))
1131 node = ast.parse('x = "not docstring"')
1132 self.assertIsNone(ast.get_docstring(node))
1133 node = ast.parse('def foo():\n pass')
1134 self.assertIsNone(ast.get_docstring(node))
1135
1136 node = ast.parse('class foo:\n pass')
1137 self.assertIsNone(ast.get_docstring(node.body[0]))
1138 node = ast.parse('class foo:\n x = "not docstring"')
1139 self.assertIsNone(ast.get_docstring(node.body[0]))
1140 node = ast.parse('class foo:\n def bar(self): pass')
1141 self.assertIsNone(ast.get_docstring(node.body[0]))
1142
1143 node = ast.parse('def foo():\n pass')
1144 self.assertIsNone(ast.get_docstring(node.body[0]))
1145 node = ast.parse('def foo():\n x = "not docstring"')
1146 self.assertIsNone(ast.get_docstring(node.body[0]))
1147
1148 node = ast.parse('async def foo():\n pass')
1149 self.assertIsNone(ast.get_docstring(node.body[0]))
1150 node = ast.parse('async def foo():\n x = "not docstring"')
1151 self.assertIsNone(ast.get_docstring(node.body[0]))
1152
1153 def test_multi_line_docstring_col_offset_and_lineno_issue16806(self):
1154 node = ast.parse(
1155 '"""line one\nline two"""\n\n'
1156 'def foo():\n """line one\n line two"""\n\n'
1157 ' def bar():\n """line one\n line two"""\n'
1158 ' """line one\n line two"""\n'
1159 '"""line one\nline two"""\n\n'
1160 )
1161 self.assertEqual(node.body[0].col_offset, 0)
1162 self.assertEqual(node.body[0].lineno, 1)
1163 self.assertEqual(node.body[1].body[0].col_offset, 2)
1164 self.assertEqual(node.body[1].body[0].lineno, 5)
1165 self.assertEqual(node.body[1].body[1].body[0].col_offset, 4)
1166 self.assertEqual(node.body[1].body[1].body[0].lineno, 9)
1167 self.assertEqual(node.body[1].body[2].col_offset, 2)
1168 self.assertEqual(node.body[1].body[2].lineno, 11)
1169 self.assertEqual(node.body[2].col_offset, 0)
1170 self.assertEqual(node.body[2].lineno, 13)
1171
1172 def test_elif_stmt_start_position(self):
1173 node = ast.parse('if a:\n pass\nelif b:\n pass\n')
1174 elif_stmt = node.body[0].orelse[0]
1175 self.assertEqual(elif_stmt.lineno, 3)
1176 self.assertEqual(elif_stmt.col_offset, 0)
1177
1178 def test_elif_stmt_start_position_with_else(self):
1179 node = ast.parse('if a:\n pass\nelif b:\n pass\nelse:\n pass\n')
1180 elif_stmt = node.body[0].orelse[0]
1181 self.assertEqual(elif_stmt.lineno, 3)
1182 self.assertEqual(elif_stmt.col_offset, 0)
1183
1184 def test_starred_expr_end_position_within_call(self):
1185 node = ast.parse('f(*[0, 1])')
1186 starred_expr = node.body[0].value.args[0]
1187 self.assertEqual(starred_expr.end_lineno, 1)
1188 self.assertEqual(starred_expr.end_col_offset, 9)
1189
1190 def test_literal_eval(self):
1191 self.assertEqual(ast.literal_eval('[1, 2, 3]'), [1, 2, 3])
1192 self.assertEqual(ast.literal_eval('{"foo": 42}'), {"foo": 42})
1193 self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None))
1194 self.assertEqual(ast.literal_eval('{1, 2, 3}'), {1, 2, 3})
1195 self.assertEqual(ast.literal_eval('b"hi"'), b"hi")
1196 self.assertEqual(ast.literal_eval('set()'), set())
1197 self.assertRaises(ValueError, ast.literal_eval, 'foo()')
1198 self.assertEqual(ast.literal_eval('6'), 6)
1199 self.assertEqual(ast.literal_eval('+6'), 6)
1200 self.assertEqual(ast.literal_eval('-6'), -6)
1201 self.assertEqual(ast.literal_eval('3.25'), 3.25)
1202 self.assertEqual(ast.literal_eval('+3.25'), 3.25)
1203 self.assertEqual(ast.literal_eval('-3.25'), -3.25)
1204 self.assertEqual(repr(ast.literal_eval('-0.0')), '-0.0')
1205 self.assertRaises(ValueError, ast.literal_eval, '++6')
1206 self.assertRaises(ValueError, ast.literal_eval, '+True')
1207 self.assertRaises(ValueError, ast.literal_eval, '2+3')
1208
1209 def test_literal_eval_str_int_limit(self):
1210 with support.adjust_int_max_str_digits(4000):
1211 ast.literal_eval('3'*4000) # no error
1212 with self.assertRaises(SyntaxError) as err_ctx:
1213 ast.literal_eval('3'*4001)
1214 self.assertIn('Exceeds the limit ', str(err_ctx.exception))
1215 self.assertIn(' Consider hexadecimal ', str(err_ctx.exception))
1216
1217 def test_literal_eval_complex(self):
1218 # Issue #4907
1219 self.assertEqual(ast.literal_eval('6j'), 6j)
1220 self.assertEqual(ast.literal_eval('-6j'), -6j)
1221 self.assertEqual(ast.literal_eval('6.75j'), 6.75j)
1222 self.assertEqual(ast.literal_eval('-6.75j'), -6.75j)
1223 self.assertEqual(ast.literal_eval('3+6j'), 3+6j)
1224 self.assertEqual(ast.literal_eval('-3+6j'), -3+6j)
1225 self.assertEqual(ast.literal_eval('3-6j'), 3-6j)
1226 self.assertEqual(ast.literal_eval('-3-6j'), -3-6j)
1227 self.assertEqual(ast.literal_eval('3.25+6.75j'), 3.25+6.75j)
1228 self.assertEqual(ast.literal_eval('-3.25+6.75j'), -3.25+6.75j)
1229 self.assertEqual(ast.literal_eval('3.25-6.75j'), 3.25-6.75j)
1230 self.assertEqual(ast.literal_eval('-3.25-6.75j'), -3.25-6.75j)
1231 self.assertEqual(ast.literal_eval('(3+6j)'), 3+6j)
1232 self.assertRaises(ValueError, ast.literal_eval, '-6j+3')
1233 self.assertRaises(ValueError, ast.literal_eval, '-6j+3j')
1234 self.assertRaises(ValueError, ast.literal_eval, '3+-6j')
1235 self.assertRaises(ValueError, ast.literal_eval, '3+(0+6j)')
1236 self.assertRaises(ValueError, ast.literal_eval, '-(3+6j)')
1237
1238 def test_literal_eval_malformed_dict_nodes(self):
1239 malformed = ast.Dict(keys=[ast.Constant(1), ast.Constant(2)], values=[ast.Constant(3)])
1240 self.assertRaises(ValueError, ast.literal_eval, malformed)
1241 malformed = ast.Dict(keys=[ast.Constant(1)], values=[ast.Constant(2), ast.Constant(3)])
1242 self.assertRaises(ValueError, ast.literal_eval, malformed)
1243
1244 def test_literal_eval_trailing_ws(self):
1245 self.assertEqual(ast.literal_eval(" -1"), -1)
1246 self.assertEqual(ast.literal_eval("\t\t-1"), -1)
1247 self.assertEqual(ast.literal_eval(" \t -1"), -1)
1248 self.assertRaises(IndentationError, ast.literal_eval, "\n -1")
1249
1250 def test_literal_eval_malformed_lineno(self):
1251 msg = r'malformed node or string on line 3:'
1252 with self.assertRaisesRegex(ValueError, msg):
1253 ast.literal_eval("{'a': 1,\n'b':2,\n'c':++3,\n'd':4}")
1254
1255 node = ast.UnaryOp(
1256 ast.UAdd(), ast.UnaryOp(ast.UAdd(), ast.Constant(6)))
1257 self.assertIsNone(getattr(node, 'lineno', None))
1258 msg = r'malformed node or string:'
1259 with self.assertRaisesRegex(ValueError, msg):
1260 ast.literal_eval(node)
1261
1262 def test_literal_eval_syntax_errors(self):
1263 if sys.implementation.name == 'pypy':
1264 errmsg = "unexpected character"
1265 else:
1266 errmsg = "unxepected indent"
1267 with self.assertRaisesRegex(SyntaxError, errmsg):
1268 ast.literal_eval(r'''
1269 \
1270 (\
1271 \ ''')
1272
1273 @support.cpython_only
1274 def test_bad_integer(self):
1275 # issue13436: Bad error message with invalid numeric values
1276 body = [ast.ImportFrom(module='time',
1277 names=[ast.alias(name='sleep')],
1278 level=None,
1279 lineno=None, col_offset=None)]
1280 mod = ast.Module(body, [])
1281 with self.assertRaises(ValueError) as cm:
1282 compile(mod, 'test', 'exec')
1283 self.assertIn("invalid integer value: None", str(cm.exception))
1284
1285 def test_level_as_none(self):
1286 body = [ast.ImportFrom(module='time',
1287 names=[ast.alias(name='sleep',
1288 lineno=0, col_offset=0)],
1289 level=None,
1290 lineno=0, col_offset=0)]
1291 mod = ast.Module(body, [])
1292 code = compile(mod, 'test', 'exec')
1293 ns = {}
1294 exec(code, ns)
1295 self.assertIn('sleep', ns)
1296
1297 def test_recursion_direct(self):
1298 e = ast.UnaryOp(op=ast.Not(), lineno=0, col_offset=0)
1299 e.operand = e
1300 with self.assertRaises(RecursionError):
1301 with support.infinite_recursion():
1302 compile(ast.Expression(e), "<test>", "eval")
1303
1304 def test_recursion_indirect(self):
1305 e = ast.UnaryOp(op=ast.Not(), lineno=0, col_offset=0)
1306 f = ast.UnaryOp(op=ast.Not(), lineno=0, col_offset=0)
1307 e.operand = f
1308 f.operand = e
1309 with self.assertRaises(RecursionError):
1310 with support.infinite_recursion():
1311 compile(ast.Expression(e), "<test>", "eval")
1312
1313
1314 class ASTValidatorTests(unittest.TestCase):
1315
1316 def mod(self, mod, msg=None, mode="exec", *, exc=ValueError):
1317 mod.lineno = mod.col_offset = 0
1318 ast.fix_missing_locations(mod)
1319 if msg is None:
1320 compile(mod, "<test>", mode)
1321 else:
1322 with self.assertRaises(exc) as cm:
1323 compile(mod, "<test>", mode)
1324 self.assertIn(msg, str(cm.exception))
1325
1326 def expr(self, node, msg=None, *, exc=ValueError):
1327 mod = ast.Module([ast.Expr(node)], [])
1328 self.mod(mod, msg, exc=exc)
1329
1330 def stmt(self, stmt, msg=None):
1331 mod = ast.Module([stmt], [])
1332 self.mod(mod, msg)
1333
1334 def test_module(self):
1335 m = ast.Interactive([ast.Expr(ast.Name("x", ast.Store()))])
1336 self.mod(m, "must have Load context", "single")
1337 m = ast.Expression(ast.Name("x", ast.Store()))
1338 self.mod(m, "must have Load context", "eval")
1339
1340 def _check_arguments(self, fac, check):
1341 def arguments(args=None, posonlyargs=None, vararg=None,
1342 kwonlyargs=None, kwarg=None,
1343 defaults=None, kw_defaults=None):
1344 if args is None:
1345 args = []
1346 if posonlyargs is None:
1347 posonlyargs = []
1348 if kwonlyargs is None:
1349 kwonlyargs = []
1350 if defaults is None:
1351 defaults = []
1352 if kw_defaults is None:
1353 kw_defaults = []
1354 args = ast.arguments(args, posonlyargs, vararg, kwonlyargs,
1355 kw_defaults, kwarg, defaults)
1356 return fac(args)
1357 args = [ast.arg("x", ast.Name("x", ast.Store()))]
1358 check(arguments(args=args), "must have Load context")
1359 check(arguments(posonlyargs=args), "must have Load context")
1360 check(arguments(kwonlyargs=args), "must have Load context")
1361 check(arguments(defaults=[ast.Num(3)]),
1362 "more positional defaults than args")
1363 check(arguments(kw_defaults=[ast.Num(4)]),
1364 "length of kwonlyargs is not the same as kw_defaults")
1365 args = [ast.arg("x", ast.Name("x", ast.Load()))]
1366 check(arguments(args=args, defaults=[ast.Name("x", ast.Store())]),
1367 "must have Load context")
1368 args = [ast.arg("a", ast.Name("x", ast.Load())),
1369 ast.arg("b", ast.Name("y", ast.Load()))]
1370 check(arguments(kwonlyargs=args,
1371 kw_defaults=[None, ast.Name("x", ast.Store())]),
1372 "must have Load context")
1373
1374 def test_funcdef(self):
1375 a = ast.arguments([], [], None, [], [], None, [])
1376 f = ast.FunctionDef("x", a, [], [], None)
1377 self.stmt(f, "empty body on FunctionDef")
1378 f = ast.FunctionDef("x", a, [ast.Pass()], [ast.Name("x", ast.Store())],
1379 None)
1380 self.stmt(f, "must have Load context")
1381 f = ast.FunctionDef("x", a, [ast.Pass()], [],
1382 ast.Name("x", ast.Store()))
1383 self.stmt(f, "must have Load context")
1384 def fac(args):
1385 return ast.FunctionDef("x", args, [ast.Pass()], [], None)
1386 self._check_arguments(fac, self.stmt)
1387
1388 def test_classdef(self):
1389 def cls(bases=None, keywords=None, body=None, decorator_list=None):
1390 if bases is None:
1391 bases = []
1392 if keywords is None:
1393 keywords = []
1394 if body is None:
1395 body = [ast.Pass()]
1396 if decorator_list is None:
1397 decorator_list = []
1398 return ast.ClassDef("myclass", bases, keywords,
1399 body, decorator_list)
1400 self.stmt(cls(bases=[ast.Name("x", ast.Store())]),
1401 "must have Load context")
1402 self.stmt(cls(keywords=[ast.keyword("x", ast.Name("x", ast.Store()))]),
1403 "must have Load context")
1404 self.stmt(cls(body=[]), "empty body on ClassDef")
1405 self.stmt(cls(body=[None]), "None disallowed")
1406 self.stmt(cls(decorator_list=[ast.Name("x", ast.Store())]),
1407 "must have Load context")
1408
1409 def test_delete(self):
1410 self.stmt(ast.Delete([]), "empty targets on Delete")
1411 self.stmt(ast.Delete([None]), "None disallowed")
1412 self.stmt(ast.Delete([ast.Name("x", ast.Load())]),
1413 "must have Del context")
1414
1415 def test_assign(self):
1416 self.stmt(ast.Assign([], ast.Num(3)), "empty targets on Assign")
1417 self.stmt(ast.Assign([None], ast.Num(3)), "None disallowed")
1418 self.stmt(ast.Assign([ast.Name("x", ast.Load())], ast.Num(3)),
1419 "must have Store context")
1420 self.stmt(ast.Assign([ast.Name("x", ast.Store())],
1421 ast.Name("y", ast.Store())),
1422 "must have Load context")
1423
1424 def test_augassign(self):
1425 aug = ast.AugAssign(ast.Name("x", ast.Load()), ast.Add(),
1426 ast.Name("y", ast.Load()))
1427 self.stmt(aug, "must have Store context")
1428 aug = ast.AugAssign(ast.Name("x", ast.Store()), ast.Add(),
1429 ast.Name("y", ast.Store()))
1430 self.stmt(aug, "must have Load context")
1431
1432 def test_for(self):
1433 x = ast.Name("x", ast.Store())
1434 y = ast.Name("y", ast.Load())
1435 p = ast.Pass()
1436 self.stmt(ast.For(x, y, [], []), "empty body on For")
1437 self.stmt(ast.For(ast.Name("x", ast.Load()), y, [p], []),
1438 "must have Store context")
1439 self.stmt(ast.For(x, ast.Name("y", ast.Store()), [p], []),
1440 "must have Load context")
1441 e = ast.Expr(ast.Name("x", ast.Store()))
1442 self.stmt(ast.For(x, y, [e], []), "must have Load context")
1443 self.stmt(ast.For(x, y, [p], [e]), "must have Load context")
1444
1445 def test_while(self):
1446 self.stmt(ast.While(ast.Num(3), [], []), "empty body on While")
1447 self.stmt(ast.While(ast.Name("x", ast.Store()), [ast.Pass()], []),
1448 "must have Load context")
1449 self.stmt(ast.While(ast.Num(3), [ast.Pass()],
1450 [ast.Expr(ast.Name("x", ast.Store()))]),
1451 "must have Load context")
1452
1453 def test_if(self):
1454 self.stmt(ast.If(ast.Num(3), [], []), "empty body on If")
1455 i = ast.If(ast.Name("x", ast.Store()), [ast.Pass()], [])
1456 self.stmt(i, "must have Load context")
1457 i = ast.If(ast.Num(3), [ast.Expr(ast.Name("x", ast.Store()))], [])
1458 self.stmt(i, "must have Load context")
1459 i = ast.If(ast.Num(3), [ast.Pass()],
1460 [ast.Expr(ast.Name("x", ast.Store()))])
1461 self.stmt(i, "must have Load context")
1462
1463 def test_with(self):
1464 p = ast.Pass()
1465 self.stmt(ast.With([], [p]), "empty items on With")
1466 i = ast.withitem(ast.Num(3), None)
1467 self.stmt(ast.With([i], []), "empty body on With")
1468 i = ast.withitem(ast.Name("x", ast.Store()), None)
1469 self.stmt(ast.With([i], [p]), "must have Load context")
1470 i = ast.withitem(ast.Num(3), ast.Name("x", ast.Load()))
1471 self.stmt(ast.With([i], [p]), "must have Store context")
1472
1473 def test_raise(self):
1474 r = ast.Raise(None, ast.Num(3))
1475 self.stmt(r, "Raise with cause but no exception")
1476 r = ast.Raise(ast.Name("x", ast.Store()), None)
1477 self.stmt(r, "must have Load context")
1478 r = ast.Raise(ast.Num(4), ast.Name("x", ast.Store()))
1479 self.stmt(r, "must have Load context")
1480
1481 def test_try(self):
1482 p = ast.Pass()
1483 t = ast.Try([], [], [], [p])
1484 self.stmt(t, "empty body on Try")
1485 t = ast.Try([ast.Expr(ast.Name("x", ast.Store()))], [], [], [p])
1486 self.stmt(t, "must have Load context")
1487 t = ast.Try([p], [], [], [])
1488 self.stmt(t, "Try has neither except handlers nor finalbody")
1489 t = ast.Try([p], [], [p], [p])
1490 self.stmt(t, "Try has orelse but no except handlers")
1491 t = ast.Try([p], [ast.ExceptHandler(None, "x", [])], [], [])
1492 self.stmt(t, "empty body on ExceptHandler")
1493 e = [ast.ExceptHandler(ast.Name("x", ast.Store()), "y", [p])]
1494 self.stmt(ast.Try([p], e, [], []), "must have Load context")
1495 e = [ast.ExceptHandler(None, "x", [p])]
1496 t = ast.Try([p], e, [ast.Expr(ast.Name("x", ast.Store()))], [p])
1497 self.stmt(t, "must have Load context")
1498 t = ast.Try([p], e, [p], [ast.Expr(ast.Name("x", ast.Store()))])
1499 self.stmt(t, "must have Load context")
1500
1501 def test_try_star(self):
1502 p = ast.Pass()
1503 t = ast.TryStar([], [], [], [p])
1504 self.stmt(t, "empty body on TryStar")
1505 t = ast.TryStar([ast.Expr(ast.Name("x", ast.Store()))], [], [], [p])
1506 self.stmt(t, "must have Load context")
1507 t = ast.TryStar([p], [], [], [])
1508 self.stmt(t, "TryStar has neither except handlers nor finalbody")
1509 t = ast.TryStar([p], [], [p], [p])
1510 self.stmt(t, "TryStar has orelse but no except handlers")
1511 t = ast.TryStar([p], [ast.ExceptHandler(None, "x", [])], [], [])
1512 self.stmt(t, "empty body on ExceptHandler")
1513 e = [ast.ExceptHandler(ast.Name("x", ast.Store()), "y", [p])]
1514 self.stmt(ast.TryStar([p], e, [], []), "must have Load context")
1515 e = [ast.ExceptHandler(None, "x", [p])]
1516 t = ast.TryStar([p], e, [ast.Expr(ast.Name("x", ast.Store()))], [p])
1517 self.stmt(t, "must have Load context")
1518 t = ast.TryStar([p], e, [p], [ast.Expr(ast.Name("x", ast.Store()))])
1519 self.stmt(t, "must have Load context")
1520
1521 def test_assert(self):
1522 self.stmt(ast.Assert(ast.Name("x", ast.Store()), None),
1523 "must have Load context")
1524 assrt = ast.Assert(ast.Name("x", ast.Load()),
1525 ast.Name("y", ast.Store()))
1526 self.stmt(assrt, "must have Load context")
1527
1528 def test_import(self):
1529 self.stmt(ast.Import([]), "empty names on Import")
1530
1531 def test_importfrom(self):
1532 imp = ast.ImportFrom(None, [ast.alias("x", None)], -42)
1533 self.stmt(imp, "Negative ImportFrom level")
1534 self.stmt(ast.ImportFrom(None, [], 0), "empty names on ImportFrom")
1535
1536 def test_global(self):
1537 self.stmt(ast.Global([]), "empty names on Global")
1538
1539 def test_nonlocal(self):
1540 self.stmt(ast.Nonlocal([]), "empty names on Nonlocal")
1541
1542 def test_expr(self):
1543 e = ast.Expr(ast.Name("x", ast.Store()))
1544 self.stmt(e, "must have Load context")
1545
1546 def test_boolop(self):
1547 b = ast.BoolOp(ast.And(), [])
1548 self.expr(b, "less than 2 values")
1549 b = ast.BoolOp(ast.And(), [ast.Num(3)])
1550 self.expr(b, "less than 2 values")
1551 b = ast.BoolOp(ast.And(), [ast.Num(4), None])
1552 self.expr(b, "None disallowed")
1553 b = ast.BoolOp(ast.And(), [ast.Num(4), ast.Name("x", ast.Store())])
1554 self.expr(b, "must have Load context")
1555
1556 def test_unaryop(self):
1557 u = ast.UnaryOp(ast.Not(), ast.Name("x", ast.Store()))
1558 self.expr(u, "must have Load context")
1559
1560 def test_lambda(self):
1561 a = ast.arguments([], [], None, [], [], None, [])
1562 self.expr(ast.Lambda(a, ast.Name("x", ast.Store())),
1563 "must have Load context")
1564 def fac(args):
1565 return ast.Lambda(args, ast.Name("x", ast.Load()))
1566 self._check_arguments(fac, self.expr)
1567
1568 def test_ifexp(self):
1569 l = ast.Name("x", ast.Load())
1570 s = ast.Name("y", ast.Store())
1571 for args in (s, l, l), (l, s, l), (l, l, s):
1572 self.expr(ast.IfExp(*args), "must have Load context")
1573
1574 def test_dict(self):
1575 d = ast.Dict([], [ast.Name("x", ast.Load())])
1576 self.expr(d, "same number of keys as values")
1577 d = ast.Dict([ast.Name("x", ast.Load())], [None])
1578 self.expr(d, "None disallowed")
1579
1580 def test_set(self):
1581 self.expr(ast.Set([None]), "None disallowed")
1582 s = ast.Set([ast.Name("x", ast.Store())])
1583 self.expr(s, "must have Load context")
1584
1585 def _check_comprehension(self, fac):
1586 self.expr(fac([]), "comprehension with no generators")
1587 g = ast.comprehension(ast.Name("x", ast.Load()),
1588 ast.Name("x", ast.Load()), [], 0)
1589 self.expr(fac([g]), "must have Store context")
1590 g = ast.comprehension(ast.Name("x", ast.Store()),
1591 ast.Name("x", ast.Store()), [], 0)
1592 self.expr(fac([g]), "must have Load context")
1593 x = ast.Name("x", ast.Store())
1594 y = ast.Name("y", ast.Load())
1595 g = ast.comprehension(x, y, [None], 0)
1596 self.expr(fac([g]), "None disallowed")
1597 g = ast.comprehension(x, y, [ast.Name("x", ast.Store())], 0)
1598 self.expr(fac([g]), "must have Load context")
1599
1600 def _simple_comp(self, fac):
1601 g = ast.comprehension(ast.Name("x", ast.Store()),
1602 ast.Name("x", ast.Load()), [], 0)
1603 self.expr(fac(ast.Name("x", ast.Store()), [g]),
1604 "must have Load context")
1605 def wrap(gens):
1606 return fac(ast.Name("x", ast.Store()), gens)
1607 self._check_comprehension(wrap)
1608
1609 def test_listcomp(self):
1610 self._simple_comp(ast.ListComp)
1611
1612 def test_setcomp(self):
1613 self._simple_comp(ast.SetComp)
1614
1615 def test_generatorexp(self):
1616 self._simple_comp(ast.GeneratorExp)
1617
1618 def test_dictcomp(self):
1619 g = ast.comprehension(ast.Name("y", ast.Store()),
1620 ast.Name("p", ast.Load()), [], 0)
1621 c = ast.DictComp(ast.Name("x", ast.Store()),
1622 ast.Name("y", ast.Load()), [g])
1623 self.expr(c, "must have Load context")
1624 c = ast.DictComp(ast.Name("x", ast.Load()),
1625 ast.Name("y", ast.Store()), [g])
1626 self.expr(c, "must have Load context")
1627 def factory(comps):
1628 k = ast.Name("x", ast.Load())
1629 v = ast.Name("y", ast.Load())
1630 return ast.DictComp(k, v, comps)
1631 self._check_comprehension(factory)
1632
1633 def test_yield(self):
1634 self.expr(ast.Yield(ast.Name("x", ast.Store())), "must have Load")
1635 self.expr(ast.YieldFrom(ast.Name("x", ast.Store())), "must have Load")
1636
1637 def test_compare(self):
1638 left = ast.Name("x", ast.Load())
1639 comp = ast.Compare(left, [ast.In()], [])
1640 self.expr(comp, "no comparators")
1641 comp = ast.Compare(left, [ast.In()], [ast.Num(4), ast.Num(5)])
1642 self.expr(comp, "different number of comparators and operands")
1643 comp = ast.Compare(ast.Num("blah"), [ast.In()], [left])
1644 self.expr(comp)
1645 comp = ast.Compare(left, [ast.In()], [ast.Num("blah")])
1646 self.expr(comp)
1647
1648 def test_call(self):
1649 func = ast.Name("x", ast.Load())
1650 args = [ast.Name("y", ast.Load())]
1651 keywords = [ast.keyword("w", ast.Name("z", ast.Load()))]
1652 call = ast.Call(ast.Name("x", ast.Store()), args, keywords)
1653 self.expr(call, "must have Load context")
1654 call = ast.Call(func, [None], keywords)
1655 self.expr(call, "None disallowed")
1656 bad_keywords = [ast.keyword("w", ast.Name("z", ast.Store()))]
1657 call = ast.Call(func, args, bad_keywords)
1658 self.expr(call, "must have Load context")
1659
1660 def test_num(self):
1661 class subint(int):
1662 pass
1663 class subfloat(float):
1664 pass
1665 class subcomplex(complex):
1666 pass
1667 for obj in "0", "hello":
1668 self.expr(ast.Num(obj))
1669 for obj in subint(), subfloat(), subcomplex():
1670 self.expr(ast.Num(obj), "invalid type", exc=TypeError)
1671
1672 def test_attribute(self):
1673 attr = ast.Attribute(ast.Name("x", ast.Store()), "y", ast.Load())
1674 self.expr(attr, "must have Load context")
1675
1676 def test_subscript(self):
1677 sub = ast.Subscript(ast.Name("x", ast.Store()), ast.Num(3),
1678 ast.Load())
1679 self.expr(sub, "must have Load context")
1680 x = ast.Name("x", ast.Load())
1681 sub = ast.Subscript(x, ast.Name("y", ast.Store()),
1682 ast.Load())
1683 self.expr(sub, "must have Load context")
1684 s = ast.Name("x", ast.Store())
1685 for args in (s, None, None), (None, s, None), (None, None, s):
1686 sl = ast.Slice(*args)
1687 self.expr(ast.Subscript(x, sl, ast.Load()),
1688 "must have Load context")
1689 sl = ast.Tuple([], ast.Load())
1690 self.expr(ast.Subscript(x, sl, ast.Load()))
1691 sl = ast.Tuple([s], ast.Load())
1692 self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context")
1693
1694 def test_starred(self):
1695 left = ast.List([ast.Starred(ast.Name("x", ast.Load()), ast.Store())],
1696 ast.Store())
1697 assign = ast.Assign([left], ast.Num(4))
1698 self.stmt(assign, "must have Store context")
1699
1700 def _sequence(self, fac):
1701 self.expr(fac([None], ast.Load()), "None disallowed")
1702 self.expr(fac([ast.Name("x", ast.Store())], ast.Load()),
1703 "must have Load context")
1704
1705 def test_list(self):
1706 self._sequence(ast.List)
1707
1708 def test_tuple(self):
1709 self._sequence(ast.Tuple)
1710
1711 def test_nameconstant(self):
1712 self.expr(ast.NameConstant(4))
1713
1714 @support.requires_resource('cpu')
1715 def test_stdlib_validates(self):
1716 stdlib = os.path.dirname(ast.__file__)
1717 tests = [fn for fn in os.listdir(stdlib) if fn.endswith(".py")]
1718 tests.extend(["test/test_grammar.py", "test/test_unpack_ex.py"])
1719 for module in tests:
1720 with self.subTest(module):
1721 fn = os.path.join(stdlib, module)
1722 with open(fn, "r", encoding="utf-8") as fp:
1723 source = fp.read()
1724 mod = ast.parse(source, fn)
1725 compile(mod, fn, "exec")
1726
1727 constant_1 = ast.Constant(1)
1728 pattern_1 = ast.MatchValue(constant_1)
1729
1730 constant_x = ast.Constant('x')
1731 pattern_x = ast.MatchValue(constant_x)
1732
1733 constant_true = ast.Constant(True)
1734 pattern_true = ast.MatchSingleton(True)
1735
1736 name_carter = ast.Name('carter', ast.Load())
1737
1738 _MATCH_PATTERNS = [
1739 ast.MatchValue(
1740 ast.Attribute(
1741 ast.Attribute(
1742 ast.Name('x', ast.Store()),
1743 'y', ast.Load()
1744 ),
1745 'z', ast.Load()
1746 )
1747 ),
1748 ast.MatchValue(
1749 ast.Attribute(
1750 ast.Attribute(
1751 ast.Name('x', ast.Load()),
1752 'y', ast.Store()
1753 ),
1754 'z', ast.Load()
1755 )
1756 ),
1757 ast.MatchValue(
1758 ast.Constant(...)
1759 ),
1760 ast.MatchValue(
1761 ast.Constant(True)
1762 ),
1763 ast.MatchValue(
1764 ast.Constant((1,2,3))
1765 ),
1766 ast.MatchSingleton('string'),
1767 ast.MatchSequence([
1768 ast.MatchSingleton('string')
1769 ]),
1770 ast.MatchSequence(
1771 [
1772 ast.MatchSequence(
1773 [
1774 ast.MatchSingleton('string')
1775 ]
1776 )
1777 ]
1778 ),
1779 ast.MatchMapping(
1780 [constant_1, constant_true],
1781 [pattern_x]
1782 ),
1783 ast.MatchMapping(
1784 [constant_true, constant_1],
1785 [pattern_x, pattern_1],
1786 rest='True'
1787 ),
1788 ast.MatchMapping(
1789 [constant_true, ast.Starred(ast.Name('lol', ast.Load()), ast.Load())],
1790 [pattern_x, pattern_1],
1791 rest='legit'
1792 ),
1793 ast.MatchClass(
1794 ast.Attribute(
1795 ast.Attribute(
1796 constant_x,
1797 'y', ast.Load()),
1798 'z', ast.Load()),
1799 patterns=[], kwd_attrs=[], kwd_patterns=[]
1800 ),
1801 ast.MatchClass(
1802 name_carter,
1803 patterns=[],
1804 kwd_attrs=['True'],
1805 kwd_patterns=[pattern_1]
1806 ),
1807 ast.MatchClass(
1808 name_carter,
1809 patterns=[],
1810 kwd_attrs=[],
1811 kwd_patterns=[pattern_1]
1812 ),
1813 ast.MatchClass(
1814 name_carter,
1815 patterns=[ast.MatchSingleton('string')],
1816 kwd_attrs=[],
1817 kwd_patterns=[]
1818 ),
1819 ast.MatchClass(
1820 name_carter,
1821 patterns=[ast.MatchStar()],
1822 kwd_attrs=[],
1823 kwd_patterns=[]
1824 ),
1825 ast.MatchClass(
1826 name_carter,
1827 patterns=[],
1828 kwd_attrs=[],
1829 kwd_patterns=[ast.MatchStar()]
1830 ),
1831 ast.MatchClass(
1832 constant_true, # invalid name
1833 patterns=[],
1834 kwd_attrs=['True'],
1835 kwd_patterns=[pattern_1]
1836 ),
1837 ast.MatchSequence(
1838 [
1839 ast.MatchStar("True")
1840 ]
1841 ),
1842 ast.MatchAs(
1843 name='False'
1844 ),
1845 ast.MatchOr(
1846 []
1847 ),
1848 ast.MatchOr(
1849 [pattern_1]
1850 ),
1851 ast.MatchOr(
1852 [pattern_1, pattern_x, ast.MatchSingleton('xxx')]
1853 ),
1854 ast.MatchAs(name="_"),
1855 ast.MatchStar(name="x"),
1856 ast.MatchSequence([ast.MatchStar("_")]),
1857 ast.MatchMapping([], [], rest="_"),
1858 ]
1859
1860 def test_match_validation_pattern(self):
1861 name_x = ast.Name('x', ast.Load())
1862 for pattern in self._MATCH_PATTERNS:
1863 with self.subTest(ast.dump(pattern, indent=4)):
1864 node = ast.Match(
1865 subject=name_x,
1866 cases = [
1867 ast.match_case(
1868 pattern=pattern,
1869 body = [ast.Pass()]
1870 )
1871 ]
1872 )
1873 node = ast.fix_missing_locations(node)
1874 module = ast.Module([node], [])
1875 with self.assertRaises(ValueError):
1876 compile(module, "<test>", "exec")
1877
1878
1879 class ConstantTests(unittest.TestCase):
1880 """Tests on the ast.Constant node type."""
1881
1882 def compile_constant(self, value):
1883 tree = ast.parse("x = 123")
1884
1885 node = tree.body[0].value
1886 new_node = ast.Constant(value=value)
1887 ast.copy_location(new_node, node)
1888 tree.body[0].value = new_node
1889
1890 code = compile(tree, "<string>", "exec")
1891
1892 ns = {}
1893 exec(code, ns)
1894 return ns['x']
1895
1896 def test_validation(self):
1897 with self.assertRaises(TypeError) as cm:
1898 self.compile_constant([1, 2, 3])
1899 self.assertEqual(str(cm.exception),
1900 "got an invalid type in Constant: list")
1901
1902 def test_singletons(self):
1903 for const in (None, False, True, Ellipsis, b'', frozenset()):
1904 with self.subTest(const=const):
1905 value = self.compile_constant(const)
1906 self.assertIs(value, const)
1907
1908 def test_values(self):
1909 nested_tuple = (1,)
1910 nested_frozenset = frozenset({1})
1911 for level in range(3):
1912 nested_tuple = (nested_tuple, 2)
1913 nested_frozenset = frozenset({nested_frozenset, 2})
1914 values = (123, 123.0, 123j,
1915 "unicode", b'bytes',
1916 tuple("tuple"), frozenset("frozenset"),
1917 nested_tuple, nested_frozenset)
1918 for value in values:
1919 with self.subTest(value=value):
1920 result = self.compile_constant(value)
1921 self.assertEqual(result, value)
1922
1923 def test_assign_to_constant(self):
1924 tree = ast.parse("x = 1")
1925
1926 target = tree.body[0].targets[0]
1927 new_target = ast.Constant(value=1)
1928 ast.copy_location(new_target, target)
1929 tree.body[0].targets[0] = new_target
1930
1931 with self.assertRaises(ValueError) as cm:
1932 compile(tree, "string", "exec")
1933 self.assertEqual(str(cm.exception),
1934 "expression which can't be assigned "
1935 "to in Store context")
1936
1937 def test_get_docstring(self):
1938 tree = ast.parse("'docstring'\nx = 1")
1939 self.assertEqual(ast.get_docstring(tree), 'docstring')
1940
1941 def get_load_const(self, tree):
1942 # Compile to bytecode, disassemble and get parameter of LOAD_CONST
1943 # instructions
1944 co = compile(tree, '<string>', 'exec')
1945 consts = []
1946 for instr in dis.get_instructions(co):
1947 if instr.opname == 'LOAD_CONST':
1948 consts.append(instr.argval)
1949 return consts
1950
1951 @support.cpython_only
1952 def test_load_const(self):
1953 consts = [None,
1954 True, False,
1955 124,
1956 2.0,
1957 3j,
1958 "unicode",
1959 b'bytes',
1960 (1, 2, 3)]
1961
1962 code = '\n'.join(['x={!r}'.format(const) for const in consts])
1963 code += '\nx = ...'
1964 consts.extend((Ellipsis, None))
1965
1966 tree = ast.parse(code)
1967 self.assertEqual(self.get_load_const(tree),
1968 consts)
1969
1970 # Replace expression nodes with constants
1971 for assign, const in zip(tree.body, consts):
1972 assert isinstance(assign, ast.Assign), ast.dump(assign)
1973 new_node = ast.Constant(value=const)
1974 ast.copy_location(new_node, assign.value)
1975 assign.value = new_node
1976
1977 self.assertEqual(self.get_load_const(tree),
1978 consts)
1979
1980 def test_literal_eval(self):
1981 tree = ast.parse("1 + 2")
1982 binop = tree.body[0].value
1983
1984 new_left = ast.Constant(value=10)
1985 ast.copy_location(new_left, binop.left)
1986 binop.left = new_left
1987
1988 new_right = ast.Constant(value=20j)
1989 ast.copy_location(new_right, binop.right)
1990 binop.right = new_right
1991
1992 self.assertEqual(ast.literal_eval(binop), 10+20j)
1993
1994 def test_string_kind(self):
1995 c = ast.parse('"x"', mode='eval').body
1996 self.assertEqual(c.value, "x")
1997 self.assertEqual(c.kind, None)
1998
1999 c = ast.parse('u"x"', mode='eval').body
2000 self.assertEqual(c.value, "x")
2001 self.assertEqual(c.kind, "u")
2002
2003 c = ast.parse('r"x"', mode='eval').body
2004 self.assertEqual(c.value, "x")
2005 self.assertEqual(c.kind, None)
2006
2007 c = ast.parse('b"x"', mode='eval').body
2008 self.assertEqual(c.value, b"x")
2009 self.assertEqual(c.kind, None)
2010
2011
2012 class EndPositionTests(unittest.TestCase):
2013 """Tests for end position of AST nodes.
2014
2015 Testing end positions of nodes requires a bit of extra care
2016 because of how LL parsers work.
2017 """
2018 def _check_end_pos(self, ast_node, end_lineno, end_col_offset):
2019 self.assertEqual(ast_node.end_lineno, end_lineno)
2020 self.assertEqual(ast_node.end_col_offset, end_col_offset)
2021
2022 def _check_content(self, source, ast_node, content):
2023 self.assertEqual(ast.get_source_segment(source, ast_node), content)
2024
2025 def _parse_value(self, s):
2026 # Use duck-typing to support both single expression
2027 # and a right hand side of an assignment statement.
2028 return ast.parse(s).body[0].value
2029
2030 def test_lambda(self):
2031 s = 'lambda x, *y: None'
2032 lam = self._parse_value(s)
2033 self._check_content(s, lam.body, 'None')
2034 self._check_content(s, lam.args.args[0], 'x')
2035 self._check_content(s, lam.args.vararg, 'y')
2036
2037 def test_func_def(self):
2038 s = dedent('''
2039 def func(x: int,
2040 *args: str,
2041 z: float = 0,
2042 **kwargs: Any) -> bool:
2043 return True
2044 ''').strip()
2045 fdef = ast.parse(s).body[0]
2046 self._check_end_pos(fdef, 5, 15)
2047 self._check_content(s, fdef.body[0], 'return True')
2048 self._check_content(s, fdef.args.args[0], 'x: int')
2049 self._check_content(s, fdef.args.args[0].annotation, 'int')
2050 self._check_content(s, fdef.args.kwarg, 'kwargs: Any')
2051 self._check_content(s, fdef.args.kwarg.annotation, 'Any')
2052
2053 def test_call(self):
2054 s = 'func(x, y=2, **kw)'
2055 call = self._parse_value(s)
2056 self._check_content(s, call.func, 'func')
2057 self._check_content(s, call.keywords[0].value, '2')
2058 self._check_content(s, call.keywords[1].value, 'kw')
2059
2060 def test_call_noargs(self):
2061 s = 'x[0]()'
2062 call = self._parse_value(s)
2063 self._check_content(s, call.func, 'x[0]')
2064 self._check_end_pos(call, 1, 6)
2065
2066 def test_class_def(self):
2067 s = dedent('''
2068 class C(A, B):
2069 x: int = 0
2070 ''').strip()
2071 cdef = ast.parse(s).body[0]
2072 self._check_end_pos(cdef, 2, 14)
2073 self._check_content(s, cdef.bases[1], 'B')
2074 self._check_content(s, cdef.body[0], 'x: int = 0')
2075
2076 def test_class_kw(self):
2077 s = 'class S(metaclass=abc.ABCMeta): pass'
2078 cdef = ast.parse(s).body[0]
2079 self._check_content(s, cdef.keywords[0].value, 'abc.ABCMeta')
2080
2081 def test_multi_line_str(self):
2082 s = dedent('''
2083 x = """Some multi-line text.
2084
2085 It goes on starting from same indent."""
2086 ''').strip()
2087 assign = ast.parse(s).body[0]
2088 self._check_end_pos(assign, 3, 40)
2089 self._check_end_pos(assign.value, 3, 40)
2090
2091 def test_continued_str(self):
2092 s = dedent('''
2093 x = "first part" \\
2094 "second part"
2095 ''').strip()
2096 assign = ast.parse(s).body[0]
2097 self._check_end_pos(assign, 2, 13)
2098 self._check_end_pos(assign.value, 2, 13)
2099
2100 def test_suites(self):
2101 # We intentionally put these into the same string to check
2102 # that empty lines are not part of the suite.
2103 s = dedent('''
2104 while True:
2105 pass
2106
2107 if one():
2108 x = None
2109 elif other():
2110 y = None
2111 else:
2112 z = None
2113
2114 for x, y in stuff:
2115 assert True
2116
2117 try:
2118 raise RuntimeError
2119 except TypeError as e:
2120 pass
2121
2122 pass
2123 ''').strip()
2124 mod = ast.parse(s)
2125 while_loop = mod.body[0]
2126 if_stmt = mod.body[1]
2127 for_loop = mod.body[2]
2128 try_stmt = mod.body[3]
2129 pass_stmt = mod.body[4]
2130
2131 self._check_end_pos(while_loop, 2, 8)
2132 self._check_end_pos(if_stmt, 9, 12)
2133 self._check_end_pos(for_loop, 12, 15)
2134 self._check_end_pos(try_stmt, 17, 8)
2135 self._check_end_pos(pass_stmt, 19, 4)
2136
2137 self._check_content(s, while_loop.test, 'True')
2138 self._check_content(s, if_stmt.body[0], 'x = None')
2139 self._check_content(s, if_stmt.orelse[0].test, 'other()')
2140 self._check_content(s, for_loop.target, 'x, y')
2141 self._check_content(s, try_stmt.body[0], 'raise RuntimeError')
2142 self._check_content(s, try_stmt.handlers[0].type, 'TypeError')
2143
2144 def test_fstring(self):
2145 s = 'x = f"abc {x + y} abc"'
2146 fstr = self._parse_value(s)
2147 binop = fstr.values[1].value
2148 self._check_content(s, binop, 'x + y')
2149
2150 def test_fstring_multi_line(self):
2151 s = dedent('''
2152 f"""Some multi-line text.
2153 {
2154 arg_one
2155 +
2156 arg_two
2157 }
2158 It goes on..."""
2159 ''').strip()
2160 fstr = self._parse_value(s)
2161 binop = fstr.values[1].value
2162 self._check_end_pos(binop, 5, 7)
2163 self._check_content(s, binop.left, 'arg_one')
2164 self._check_content(s, binop.right, 'arg_two')
2165
2166 def test_import_from_multi_line(self):
2167 s = dedent('''
2168 from x.y.z import (
2169 a, b, c as c
2170 )
2171 ''').strip()
2172 imp = ast.parse(s).body[0]
2173 self._check_end_pos(imp, 3, 1)
2174 self._check_end_pos(imp.names[2], 2, 16)
2175
2176 def test_slices(self):
2177 s1 = 'f()[1, 2] [0]'
2178 s2 = 'x[ a.b: c.d]'
2179 sm = dedent('''
2180 x[ a.b: f () ,
2181 g () : c.d
2182 ]
2183 ''').strip()
2184 i1, i2, im = map(self._parse_value, (s1, s2, sm))
2185 self._check_content(s1, i1.value, 'f()[1, 2]')
2186 self._check_content(s1, i1.value.slice, '1, 2')
2187 self._check_content(s2, i2.slice.lower, 'a.b')
2188 self._check_content(s2, i2.slice.upper, 'c.d')
2189 self._check_content(sm, im.slice.elts[0].upper, 'f ()')
2190 self._check_content(sm, im.slice.elts[1].lower, 'g ()')
2191 self._check_end_pos(im, 3, 3)
2192
2193 def test_binop(self):
2194 s = dedent('''
2195 (1 * 2 + (3 ) +
2196 4
2197 )
2198 ''').strip()
2199 binop = self._parse_value(s)
2200 self._check_end_pos(binop, 2, 6)
2201 self._check_content(s, binop.right, '4')
2202 self._check_content(s, binop.left, '1 * 2 + (3 )')
2203 self._check_content(s, binop.left.right, '3')
2204
2205 def test_boolop(self):
2206 s = dedent('''
2207 if (one_condition and
2208 (other_condition or yet_another_one)):
2209 pass
2210 ''').strip()
2211 bop = ast.parse(s).body[0].test
2212 self._check_end_pos(bop, 2, 44)
2213 self._check_content(s, bop.values[1],
2214 'other_condition or yet_another_one')
2215
2216 def test_tuples(self):
2217 s1 = 'x = () ;'
2218 s2 = 'x = 1 , ;'
2219 s3 = 'x = (1 , 2 ) ;'
2220 sm = dedent('''
2221 x = (
2222 a, b,
2223 )
2224 ''').strip()
2225 t1, t2, t3, tm = map(self._parse_value, (s1, s2, s3, sm))
2226 self._check_content(s1, t1, '()')
2227 self._check_content(s2, t2, '1 ,')
2228 self._check_content(s3, t3, '(1 , 2 )')
2229 self._check_end_pos(tm, 3, 1)
2230
2231 def test_attribute_spaces(self):
2232 s = 'func(x. y .z)'
2233 call = self._parse_value(s)
2234 self._check_content(s, call, s)
2235 self._check_content(s, call.args[0], 'x. y .z')
2236
2237 def test_redundant_parenthesis(self):
2238 s = '( ( ( a + b ) ) )'
2239 v = ast.parse(s).body[0].value
2240 self.assertEqual(type(v).__name__, 'BinOp')
2241 self._check_content(s, v, 'a + b')
2242 s2 = 'await ' + s
2243 v = ast.parse(s2).body[0].value.value
2244 self.assertEqual(type(v).__name__, 'BinOp')
2245 self._check_content(s2, v, 'a + b')
2246
2247 def test_trailers_with_redundant_parenthesis(self):
2248 tests = (
2249 ('( ( ( a ) ) ) ( )', 'Call'),
2250 ('( ( ( a ) ) ) ( b )', 'Call'),
2251 ('( ( ( a ) ) ) [ b ]', 'Subscript'),
2252 ('( ( ( a ) ) ) . b', 'Attribute'),
2253 )
2254 for s, t in tests:
2255 with self.subTest(s):
2256 v = ast.parse(s).body[0].value
2257 self.assertEqual(type(v).__name__, t)
2258 self._check_content(s, v, s)
2259 s2 = 'await ' + s
2260 v = ast.parse(s2).body[0].value.value
2261 self.assertEqual(type(v).__name__, t)
2262 self._check_content(s2, v, s)
2263
2264 def test_displays(self):
2265 s1 = '[{}, {1, }, {1, 2,} ]'
2266 s2 = '{a: b, f (): g () ,}'
2267 c1 = self._parse_value(s1)
2268 c2 = self._parse_value(s2)
2269 self._check_content(s1, c1.elts[0], '{}')
2270 self._check_content(s1, c1.elts[1], '{1, }')
2271 self._check_content(s1, c1.elts[2], '{1, 2,}')
2272 self._check_content(s2, c2.keys[1], 'f ()')
2273 self._check_content(s2, c2.values[1], 'g ()')
2274
2275 def test_comprehensions(self):
2276 s = dedent('''
2277 x = [{x for x, y in stuff
2278 if cond.x} for stuff in things]
2279 ''').strip()
2280 cmp = self._parse_value(s)
2281 self._check_end_pos(cmp, 2, 37)
2282 self._check_content(s, cmp.generators[0].iter, 'things')
2283 self._check_content(s, cmp.elt.generators[0].iter, 'stuff')
2284 self._check_content(s, cmp.elt.generators[0].ifs[0], 'cond.x')
2285 self._check_content(s, cmp.elt.generators[0].target, 'x, y')
2286
2287 def test_yield_await(self):
2288 s = dedent('''
2289 async def f():
2290 yield x
2291 await y
2292 ''').strip()
2293 fdef = ast.parse(s).body[0]
2294 self._check_content(s, fdef.body[0].value, 'yield x')
2295 self._check_content(s, fdef.body[1].value, 'await y')
2296
2297 def test_source_segment_multi(self):
2298 s_orig = dedent('''
2299 x = (
2300 a, b,
2301 ) + ()
2302 ''').strip()
2303 s_tuple = dedent('''
2304 (
2305 a, b,
2306 )
2307 ''').strip()
2308 binop = self._parse_value(s_orig)
2309 self.assertEqual(ast.get_source_segment(s_orig, binop.left), s_tuple)
2310
2311 def test_source_segment_padded(self):
2312 s_orig = dedent('''
2313 class C:
2314 def fun(self) -> None:
2315 "ЖЖЖЖЖ"
2316 ''').strip()
2317 s_method = ' def fun(self) -> None:\n' \
2318 ' "ЖЖЖЖЖ"'
2319 cdef = ast.parse(s_orig).body[0]
2320 self.assertEqual(ast.get_source_segment(s_orig, cdef.body[0], padded=True),
2321 s_method)
2322
2323 def test_source_segment_endings(self):
2324 s = 'v = 1\r\nw = 1\nx = 1\n\ry = 1\rz = 1\r\n'
2325 v, w, x, y, z = ast.parse(s).body
2326 self._check_content(s, v, 'v = 1')
2327 self._check_content(s, w, 'w = 1')
2328 self._check_content(s, x, 'x = 1')
2329 self._check_content(s, y, 'y = 1')
2330 self._check_content(s, z, 'z = 1')
2331
2332 def test_source_segment_tabs(self):
2333 s = dedent('''
2334 class C:
2335 \t\f def fun(self) -> None:
2336 \t\f pass
2337 ''').strip()
2338 s_method = ' \t\f def fun(self) -> None:\n' \
2339 ' \t\f pass'
2340
2341 cdef = ast.parse(s).body[0]
2342 self.assertEqual(ast.get_source_segment(s, cdef.body[0], padded=True), s_method)
2343
2344 def test_source_segment_missing_info(self):
2345 s = 'v = 1\r\nw = 1\nx = 1\n\ry = 1\r\n'
2346 v, w, x, y = ast.parse(s).body
2347 del v.lineno
2348 del w.end_lineno
2349 del x.col_offset
2350 del y.end_col_offset
2351 self.assertIsNone(ast.get_source_segment(s, v))
2352 self.assertIsNone(ast.get_source_segment(s, w))
2353 self.assertIsNone(ast.get_source_segment(s, x))
2354 self.assertIsNone(ast.get_source_segment(s, y))
2355
2356 class NodeVisitorTests(unittest.TestCase):
2357 def test_old_constant_nodes(self):
2358 class Visitor(ast.NodeVisitor):
2359 def visit_Num(self, node):
2360 log.append((node.lineno, 'Num', node.n))
2361 def visit_Str(self, node):
2362 log.append((node.lineno, 'Str', node.s))
2363 def visit_Bytes(self, node):
2364 log.append((node.lineno, 'Bytes', node.s))
2365 def visit_NameConstant(self, node):
2366 log.append((node.lineno, 'NameConstant', node.value))
2367 def visit_Ellipsis(self, node):
2368 log.append((node.lineno, 'Ellipsis', ...))
2369 mod = ast.parse(dedent('''\
2370 i = 42
2371 f = 4.25
2372 c = 4.25j
2373 s = 'string'
2374 b = b'bytes'
2375 t = True
2376 n = None
2377 e = ...
2378 '''))
2379 visitor = Visitor()
2380 log = []
2381 with warnings.catch_warnings(record=True) as wlog:
2382 warnings.filterwarnings('always', '', DeprecationWarning)
2383 visitor.visit(mod)
2384 self.assertEqual(log, [
2385 (1, 'Num', 42),
2386 (2, 'Num', 4.25),
2387 (3, 'Num', 4.25j),
2388 (4, 'Str', 'string'),
2389 (5, 'Bytes', b'bytes'),
2390 (6, 'NameConstant', True),
2391 (7, 'NameConstant', None),
2392 (8, 'Ellipsis', ...),
2393 ])
2394 self.assertEqual([str(w.message) for w in wlog], [
2395 'visit_Num is deprecated; add visit_Constant',
2396 'visit_Num is deprecated; add visit_Constant',
2397 'visit_Num is deprecated; add visit_Constant',
2398 'visit_Str is deprecated; add visit_Constant',
2399 'visit_Bytes is deprecated; add visit_Constant',
2400 'visit_NameConstant is deprecated; add visit_Constant',
2401 'visit_NameConstant is deprecated; add visit_Constant',
2402 'visit_Ellipsis is deprecated; add visit_Constant',
2403 ])
2404
2405
2406 @support.cpython_only
2407 class ModuleStateTests(unittest.TestCase):
2408 # bpo-41194, bpo-41261, bpo-41631: The _ast module uses a global state.
2409
2410 def check_ast_module(self):
2411 # Check that the _ast module still works as expected
2412 code = 'x + 1'
2413 filename = '<string>'
2414 mode = 'eval'
2415
2416 # Create _ast.AST subclasses instances
2417 ast_tree = compile(code, filename, mode, flags=ast.PyCF_ONLY_AST)
2418
2419 # Call PyAST_Check()
2420 code = compile(ast_tree, filename, mode)
2421 self.assertIsInstance(code, types.CodeType)
2422
2423 def test_reload_module(self):
2424 # bpo-41194: Importing the _ast module twice must not crash.
2425 with support.swap_item(sys.modules, '_ast', None):
2426 del sys.modules['_ast']
2427 import _ast as ast1
2428
2429 del sys.modules['_ast']
2430 import _ast as ast2
2431
2432 self.check_ast_module()
2433
2434 # Unloading the two _ast module instances must not crash.
2435 del ast1
2436 del ast2
2437 support.gc_collect()
2438
2439 self.check_ast_module()
2440
2441 def test_sys_modules(self):
2442 # bpo-41631: Test reproducing a Mercurial crash when PyAST_Check()
2443 # imported the _ast module internally.
2444 lazy_mod = object()
2445
2446 def my_import(name, *args, **kw):
2447 sys.modules[name] = lazy_mod
2448 return lazy_mod
2449
2450 with support.swap_item(sys.modules, '_ast', None):
2451 del sys.modules['_ast']
2452
2453 with support.swap_attr(builtins, '__import__', my_import):
2454 # Test that compile() does not import the _ast module
2455 self.check_ast_module()
2456 self.assertNotIn('_ast', sys.modules)
2457
2458 # Sanity check of the test itself
2459 import _ast
2460 self.assertIs(_ast, lazy_mod)
2461
2462 def test_subinterpreter(self):
2463 # bpo-41631: Importing and using the _ast module in a subinterpreter
2464 # must not crash.
2465 code = dedent('''
2466 import _ast
2467 import ast
2468 import gc
2469 import sys
2470 import types
2471
2472 # Create _ast.AST subclasses instances and call PyAST_Check()
2473 ast_tree = compile('x+1', '<string>', 'eval',
2474 flags=ast.PyCF_ONLY_AST)
2475 code = compile(ast_tree, 'string', 'eval')
2476 if not isinstance(code, types.CodeType):
2477 raise AssertionError
2478
2479 # Unloading the _ast module must not crash.
2480 del ast, _ast
2481 del sys.modules['ast'], sys.modules['_ast']
2482 gc.collect()
2483 ''')
2484 res = support.run_in_subinterp(code)
2485 self.assertEqual(res, 0)
2486
2487
2488 def main():
2489 if __name__ != '__main__':
2490 return
2491 if sys.argv[1:] == ['-g']:
2492 for statements, kind in ((exec_tests, "exec"), (single_tests, "single"),
2493 (eval_tests, "eval")):
2494 print(kind+"_results = [")
2495 for statement in statements:
2496 tree = ast.parse(statement, "?", kind)
2497 print("%r," % (to_tuple(tree),))
2498 print("]")
2499 print("main()")
2500 raise SystemExit
2501 unittest.main()
2502
2503 #### EVERYTHING BELOW IS GENERATED BY python Lib/test/test_ast.py -g #####
2504 exec_results = [
2505 ('Module', [('Expr', (1, 0, 1, 4), ('Constant', (1, 0, 1, 4), None, None))], []),
2506 ('Module', [('Expr', (1, 0, 1, 18), ('Constant', (1, 0, 1, 18), 'module docstring', None))], []),
2507 ('Module', [('FunctionDef', (1, 0, 1, 13), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (1, 9, 1, 13))], [], None, None)], []),
2508 ('Module', [('FunctionDef', (1, 0, 1, 29), 'f', ('arguments', [], [], None, [], [], None, []), [('Expr', (1, 9, 1, 29), ('Constant', (1, 9, 1, 29), 'function docstring', None))], [], None, None)], []),
2509 ('Module', [('FunctionDef', (1, 0, 1, 14), 'f', ('arguments', [], [('arg', (1, 6, 1, 7), 'a', None, None)], None, [], [], None, []), [('Pass', (1, 10, 1, 14))], [], None, None)], []),
2510 ('Module', [('FunctionDef', (1, 0, 1, 16), 'f', ('arguments', [], [('arg', (1, 6, 1, 7), 'a', None, None)], None, [], [], None, [('Constant', (1, 8, 1, 9), 0, None)]), [('Pass', (1, 12, 1, 16))], [], None, None)], []),
2511 ('Module', [('FunctionDef', (1, 0, 1, 18), 'f', ('arguments', [], [], ('arg', (1, 7, 1, 11), 'args', None, None), [], [], None, []), [('Pass', (1, 14, 1, 18))], [], None, None)], []),
2512 ('Module', [('FunctionDef', (1, 0, 1, 23), 'f', ('arguments', [], [], ('arg', (1, 7, 1, 16), 'args', ('Starred', (1, 13, 1, 16), ('Name', (1, 14, 1, 16), 'Ts', ('Load',)), ('Load',)), None), [], [], None, []), [('Pass', (1, 19, 1, 23))], [], None, None)], []),
2513 ('Module', [('FunctionDef', (1, 0, 1, 36), 'f', ('arguments', [], [], ('arg', (1, 7, 1, 29), 'args', ('Starred', (1, 13, 1, 29), ('Subscript', (1, 14, 1, 29), ('Name', (1, 14, 1, 19), 'tuple', ('Load',)), ('Tuple', (1, 20, 1, 28), [('Name', (1, 20, 1, 23), 'int', ('Load',)), ('Constant', (1, 25, 1, 28), Ellipsis, None)], ('Load',)), ('Load',)), ('Load',)), None), [], [], None, []), [('Pass', (1, 32, 1, 36))], [], None, None)], []),
2514 ('Module', [('FunctionDef', (1, 0, 1, 36), 'f', ('arguments', [], [], ('arg', (1, 7, 1, 29), 'args', ('Starred', (1, 13, 1, 29), ('Subscript', (1, 14, 1, 29), ('Name', (1, 14, 1, 19), 'tuple', ('Load',)), ('Tuple', (1, 20, 1, 28), [('Name', (1, 20, 1, 23), 'int', ('Load',)), ('Starred', (1, 25, 1, 28), ('Name', (1, 26, 1, 28), 'Ts', ('Load',)), ('Load',))], ('Load',)), ('Load',)), ('Load',)), None), [], [], None, []), [('Pass', (1, 32, 1, 36))], [], None, None)], []),
2515 ('Module', [('FunctionDef', (1, 0, 1, 21), 'f', ('arguments', [], [], None, [], [], ('arg', (1, 8, 1, 14), 'kwargs', None, None), []), [('Pass', (1, 17, 1, 21))], [], None, None)], []),
2516 ('Module', [('FunctionDef', (1, 0, 1, 71), 'f', ('arguments', [], [('arg', (1, 6, 1, 7), 'a', None, None), ('arg', (1, 9, 1, 10), 'b', None, None), ('arg', (1, 14, 1, 15), 'c', None, None), ('arg', (1, 22, 1, 23), 'd', None, None), ('arg', (1, 28, 1, 29), 'e', None, None)], ('arg', (1, 35, 1, 39), 'args', None, None), [('arg', (1, 41, 1, 42), 'f', None, None)], [('Constant', (1, 43, 1, 45), 42, None)], ('arg', (1, 49, 1, 55), 'kwargs', None, None), [('Constant', (1, 11, 1, 12), 1, None), ('Constant', (1, 16, 1, 20), None, None), ('List', (1, 24, 1, 26), [], ('Load',)), ('Dict', (1, 30, 1, 32), [], [])]), [('Expr', (1, 58, 1, 71), ('Constant', (1, 58, 1, 71), 'doc for f()', None))], [], None, None)], []),
2517 ('Module', [('FunctionDef', (1, 0, 1, 27), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (1, 23, 1, 27))], [], ('Subscript', (1, 11, 1, 21), ('Name', (1, 11, 1, 16), 'tuple', ('Load',)), ('Tuple', (1, 17, 1, 20), [('Starred', (1, 17, 1, 20), ('Name', (1, 18, 1, 20), 'Ts', ('Load',)), ('Load',))], ('Load',)), ('Load',)), None)], []),
2518 ('Module', [('FunctionDef', (1, 0, 1, 32), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (1, 28, 1, 32))], [], ('Subscript', (1, 11, 1, 26), ('Name', (1, 11, 1, 16), 'tuple', ('Load',)), ('Tuple', (1, 17, 1, 25), [('Name', (1, 17, 1, 20), 'int', ('Load',)), ('Starred', (1, 22, 1, 25), ('Name', (1, 23, 1, 25), 'Ts', ('Load',)), ('Load',))], ('Load',)), ('Load',)), None)], []),
2519 ('Module', [('FunctionDef', (1, 0, 1, 45), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (1, 41, 1, 45))], [], ('Subscript', (1, 11, 1, 39), ('Name', (1, 11, 1, 16), 'tuple', ('Load',)), ('Tuple', (1, 17, 1, 38), [('Name', (1, 17, 1, 20), 'int', ('Load',)), ('Starred', (1, 22, 1, 38), ('Subscript', (1, 23, 1, 38), ('Name', (1, 23, 1, 28), 'tuple', ('Load',)), ('Tuple', (1, 29, 1, 37), [('Name', (1, 29, 1, 32), 'int', ('Load',)), ('Constant', (1, 34, 1, 37), Ellipsis, None)], ('Load',)), ('Load',)), ('Load',))], ('Load',)), ('Load',)), None)], []),
2520 ('Module', [('ClassDef', (1, 0, 1, 12), 'C', [], [], [('Pass', (1, 8, 1, 12))], [])], []),
2521 ('Module', [('ClassDef', (1, 0, 1, 32), 'C', [], [], [('Expr', (1, 9, 1, 32), ('Constant', (1, 9, 1, 32), 'docstring for class C', None))], [])], []),
2522 ('Module', [('ClassDef', (1, 0, 1, 21), 'C', [('Name', (1, 8, 1, 14), 'object', ('Load',))], [], [('Pass', (1, 17, 1, 21))], [])], []),
2523 ('Module', [('FunctionDef', (1, 0, 1, 16), 'f', ('arguments', [], [], None, [], [], None, []), [('Return', (1, 8, 1, 16), ('Constant', (1, 15, 1, 16), 1, None))], [], None, None)], []),
2524 ('Module', [('Delete', (1, 0, 1, 5), [('Name', (1, 4, 1, 5), 'v', ('Del',))])], []),
2525 ('Module', [('Assign', (1, 0, 1, 5), [('Name', (1, 0, 1, 1), 'v', ('Store',))], ('Constant', (1, 4, 1, 5), 1, None), None)], []),
2526 ('Module', [('Assign', (1, 0, 1, 7), [('Tuple', (1, 0, 1, 3), [('Name', (1, 0, 1, 1), 'a', ('Store',)), ('Name', (1, 2, 1, 3), 'b', ('Store',))], ('Store',))], ('Name', (1, 6, 1, 7), 'c', ('Load',)), None)], []),
2527 ('Module', [('Assign', (1, 0, 1, 9), [('Tuple', (1, 0, 1, 5), [('Name', (1, 1, 1, 2), 'a', ('Store',)), ('Name', (1, 3, 1, 4), 'b', ('Store',))], ('Store',))], ('Name', (1, 8, 1, 9), 'c', ('Load',)), None)], []),
2528 ('Module', [('Assign', (1, 0, 1, 9), [('List', (1, 0, 1, 5), [('Name', (1, 1, 1, 2), 'a', ('Store',)), ('Name', (1, 3, 1, 4), 'b', ('Store',))], ('Store',))], ('Name', (1, 8, 1, 9), 'c', ('Load',)), None)], []),
2529 ('Module', [('AnnAssign', (1, 0, 1, 13), ('Name', (1, 0, 1, 1), 'x', ('Store',)), ('Subscript', (1, 3, 1, 13), ('Name', (1, 3, 1, 8), 'tuple', ('Load',)), ('Tuple', (1, 9, 1, 12), [('Starred', (1, 9, 1, 12), ('Name', (1, 10, 1, 12), 'Ts', ('Load',)), ('Load',))], ('Load',)), ('Load',)), None, 1)], []),
2530 ('Module', [('AnnAssign', (1, 0, 1, 18), ('Name', (1, 0, 1, 1), 'x', ('Store',)), ('Subscript', (1, 3, 1, 18), ('Name', (1, 3, 1, 8), 'tuple', ('Load',)), ('Tuple', (1, 9, 1, 17), [('Name', (1, 9, 1, 12), 'int', ('Load',)), ('Starred', (1, 14, 1, 17), ('Name', (1, 15, 1, 17), 'Ts', ('Load',)), ('Load',))], ('Load',)), ('Load',)), None, 1)], []),
2531 ('Module', [('AnnAssign', (1, 0, 1, 31), ('Name', (1, 0, 1, 1), 'x', ('Store',)), ('Subscript', (1, 3, 1, 31), ('Name', (1, 3, 1, 8), 'tuple', ('Load',)), ('Tuple', (1, 9, 1, 30), [('Name', (1, 9, 1, 12), 'int', ('Load',)), ('Starred', (1, 14, 1, 30), ('Subscript', (1, 15, 1, 30), ('Name', (1, 15, 1, 20), 'tuple', ('Load',)), ('Tuple', (1, 21, 1, 29), [('Name', (1, 21, 1, 24), 'str', ('Load',)), ('Constant', (1, 26, 1, 29), Ellipsis, None)], ('Load',)), ('Load',)), ('Load',))], ('Load',)), ('Load',)), None, 1)], []),
2532 ('Module', [('AugAssign', (1, 0, 1, 6), ('Name', (1, 0, 1, 1), 'v', ('Store',)), ('Add',), ('Constant', (1, 5, 1, 6), 1, None))], []),
2533 ('Module', [('For', (1, 0, 1, 15), ('Name', (1, 4, 1, 5), 'v', ('Store',)), ('Name', (1, 9, 1, 10), 'v', ('Load',)), [('Pass', (1, 11, 1, 15))], [], None)], []),
2534 ('Module', [('While', (1, 0, 1, 12), ('Name', (1, 6, 1, 7), 'v', ('Load',)), [('Pass', (1, 8, 1, 12))], [])], []),
2535 ('Module', [('If', (1, 0, 1, 9), ('Name', (1, 3, 1, 4), 'v', ('Load',)), [('Pass', (1, 5, 1, 9))], [])], []),
2536 ('Module', [('If', (1, 0, 4, 6), ('Name', (1, 3, 1, 4), 'a', ('Load',)), [('Pass', (2, 2, 2, 6))], [('If', (3, 0, 4, 6), ('Name', (3, 5, 3, 6), 'b', ('Load',)), [('Pass', (4, 2, 4, 6))], [])])], []),
2537 ('Module', [('If', (1, 0, 6, 6), ('Name', (1, 3, 1, 4), 'a', ('Load',)), [('Pass', (2, 2, 2, 6))], [('If', (3, 0, 6, 6), ('Name', (3, 5, 3, 6), 'b', ('Load',)), [('Pass', (4, 2, 4, 6))], [('Pass', (6, 2, 6, 6))])])], []),
2538 ('Module', [('With', (1, 0, 1, 17), [('withitem', ('Name', (1, 5, 1, 6), 'x', ('Load',)), ('Name', (1, 10, 1, 11), 'y', ('Store',)))], [('Pass', (1, 13, 1, 17))], None)], []),
2539 ('Module', [('With', (1, 0, 1, 25), [('withitem', ('Name', (1, 5, 1, 6), 'x', ('Load',)), ('Name', (1, 10, 1, 11), 'y', ('Store',))), ('withitem', ('Name', (1, 13, 1, 14), 'z', ('Load',)), ('Name', (1, 18, 1, 19), 'q', ('Store',)))], [('Pass', (1, 21, 1, 25))], None)], []),
2540 ('Module', [('Raise', (1, 0, 1, 25), ('Call', (1, 6, 1, 25), ('Name', (1, 6, 1, 15), 'Exception', ('Load',)), [('Constant', (1, 16, 1, 24), 'string', None)], []), None)], []),
2541 ('Module', [('Try', (1, 0, 4, 6), [('Pass', (2, 2, 2, 6))], [('ExceptHandler', (3, 0, 4, 6), ('Name', (3, 7, 3, 16), 'Exception', ('Load',)), None, [('Pass', (4, 2, 4, 6))])], [], [])], []),
2542 ('Module', [('Try', (1, 0, 4, 6), [('Pass', (2, 2, 2, 6))], [], [], [('Pass', (4, 2, 4, 6))])], []),
2543 ('Module', [('TryStar', (1, 0, 4, 6), [('Pass', (2, 2, 2, 6))], [('ExceptHandler', (3, 0, 4, 6), ('Name', (3, 8, 3, 17), 'Exception', ('Load',)), None, [('Pass', (4, 2, 4, 6))])], [], [])], []),
2544 ('Module', [('Assert', (1, 0, 1, 8), ('Name', (1, 7, 1, 8), 'v', ('Load',)), None)], []),
2545 ('Module', [('Import', (1, 0, 1, 10), [('alias', (1, 7, 1, 10), 'sys', None)])], []),
2546 ('Module', [('ImportFrom', (1, 0, 1, 17), 'sys', [('alias', (1, 16, 1, 17), 'v', None)], 0)], []),
2547 ('Module', [('Global', (1, 0, 1, 8), ['v'])], []),
2548 ('Module', [('Expr', (1, 0, 1, 1), ('Constant', (1, 0, 1, 1), 1, None))], []),
2549 ('Module', [('Pass', (1, 0, 1, 4))], []),
2550 ('Module', [('For', (1, 0, 1, 16), ('Name', (1, 4, 1, 5), 'v', ('Store',)), ('Name', (1, 9, 1, 10), 'v', ('Load',)), [('Break', (1, 11, 1, 16))], [], None)], []),
2551 ('Module', [('For', (1, 0, 1, 19), ('Name', (1, 4, 1, 5), 'v', ('Store',)), ('Name', (1, 9, 1, 10), 'v', ('Load',)), [('Continue', (1, 11, 1, 19))], [], None)], []),
2552 ('Module', [('For', (1, 0, 1, 18), ('Tuple', (1, 4, 1, 7), [('Name', (1, 4, 1, 5), 'a', ('Store',)), ('Name', (1, 6, 1, 7), 'b', ('Store',))], ('Store',)), ('Name', (1, 11, 1, 12), 'c', ('Load',)), [('Pass', (1, 14, 1, 18))], [], None)], []),
2553 ('Module', [('For', (1, 0, 1, 20), ('Tuple', (1, 4, 1, 9), [('Name', (1, 5, 1, 6), 'a', ('Store',)), ('Name', (1, 7, 1, 8), 'b', ('Store',))], ('Store',)), ('Name', (1, 13, 1, 14), 'c', ('Load',)), [('Pass', (1, 16, 1, 20))], [], None)], []),
2554 ('Module', [('For', (1, 0, 1, 20), ('List', (1, 4, 1, 9), [('Name', (1, 5, 1, 6), 'a', ('Store',)), ('Name', (1, 7, 1, 8), 'b', ('Store',))], ('Store',)), ('Name', (1, 13, 1, 14), 'c', ('Load',)), [('Pass', (1, 16, 1, 20))], [], None)], []),
2555 ('Module', [('Expr', (1, 0, 11, 5), ('GeneratorExp', (1, 0, 11, 5), ('Tuple', (2, 4, 6, 5), [('Name', (3, 4, 3, 6), 'Aa', ('Load',)), ('Name', (5, 7, 5, 9), 'Bb', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (8, 4, 10, 6), [('Name', (8, 4, 8, 6), 'Aa', ('Store',)), ('Name', (10, 4, 10, 6), 'Bb', ('Store',))], ('Store',)), ('Name', (10, 10, 10, 12), 'Cc', ('Load',)), [], 0)]))], []),
2556 ('Module', [('Expr', (1, 0, 1, 34), ('DictComp', (1, 0, 1, 34), ('Name', (1, 1, 1, 2), 'a', ('Load',)), ('Name', (1, 5, 1, 6), 'b', ('Load',)), [('comprehension', ('Name', (1, 11, 1, 12), 'w', ('Store',)), ('Name', (1, 16, 1, 17), 'x', ('Load',)), [], 0), ('comprehension', ('Name', (1, 22, 1, 23), 'm', ('Store',)), ('Name', (1, 27, 1, 28), 'p', ('Load',)), [('Name', (1, 32, 1, 33), 'g', ('Load',))], 0)]))], []),
2557 ('Module', [('Expr', (1, 0, 1, 20), ('DictComp', (1, 0, 1, 20), ('Name', (1, 1, 1, 2), 'a', ('Load',)), ('Name', (1, 5, 1, 6), 'b', ('Load',)), [('comprehension', ('Tuple', (1, 11, 1, 14), [('Name', (1, 11, 1, 12), 'v', ('Store',)), ('Name', (1, 13, 1, 14), 'w', ('Store',))], ('Store',)), ('Name', (1, 18, 1, 19), 'x', ('Load',)), [], 0)]))], []),
2558 ('Module', [('Expr', (1, 0, 1, 19), ('SetComp', (1, 0, 1, 19), ('Name', (1, 1, 1, 2), 'r', ('Load',)), [('comprehension', ('Name', (1, 7, 1, 8), 'l', ('Store',)), ('Name', (1, 12, 1, 13), 'x', ('Load',)), [('Name', (1, 17, 1, 18), 'g', ('Load',))], 0)]))], []),
2559 ('Module', [('Expr', (1, 0, 1, 16), ('SetComp', (1, 0, 1, 16), ('Name', (1, 1, 1, 2), 'r', ('Load',)), [('comprehension', ('Tuple', (1, 7, 1, 10), [('Name', (1, 7, 1, 8), 'l', ('Store',)), ('Name', (1, 9, 1, 10), 'm', ('Store',))], ('Store',)), ('Name', (1, 14, 1, 15), 'x', ('Load',)), [], 0)]))], []),
2560 ('Module', [('AsyncFunctionDef', (1, 0, 3, 18), 'f', ('arguments', [], [], None, [], [], None, []), [('Expr', (2, 1, 2, 17), ('Constant', (2, 1, 2, 17), 'async function', None)), ('Expr', (3, 1, 3, 18), ('Await', (3, 1, 3, 18), ('Call', (3, 7, 3, 18), ('Name', (3, 7, 3, 16), 'something', ('Load',)), [], [])))], [], None, None)], []),
2561 ('Module', [('AsyncFunctionDef', (1, 0, 3, 8), 'f', ('arguments', [], [], None, [], [], None, []), [('AsyncFor', (2, 1, 3, 8), ('Name', (2, 11, 2, 12), 'e', ('Store',)), ('Name', (2, 16, 2, 17), 'i', ('Load',)), [('Expr', (2, 19, 2, 20), ('Constant', (2, 19, 2, 20), 1, None))], [('Expr', (3, 7, 3, 8), ('Constant', (3, 7, 3, 8), 2, None))], None)], [], None, None)], []),
2562 ('Module', [('AsyncFunctionDef', (1, 0, 2, 21), 'f', ('arguments', [], [], None, [], [], None, []), [('AsyncWith', (2, 1, 2, 21), [('withitem', ('Name', (2, 12, 2, 13), 'a', ('Load',)), ('Name', (2, 17, 2, 18), 'b', ('Store',)))], [('Expr', (2, 20, 2, 21), ('Constant', (2, 20, 2, 21), 1, None))], None)], [], None, None)], []),
2563 ('Module', [('Expr', (1, 0, 1, 14), ('Dict', (1, 0, 1, 14), [None, ('Constant', (1, 10, 1, 11), 2, None)], [('Dict', (1, 3, 1, 8), [('Constant', (1, 4, 1, 5), 1, None)], [('Constant', (1, 6, 1, 7), 2, None)]), ('Constant', (1, 12, 1, 13), 3, None)]))], []),
2564 ('Module', [('Expr', (1, 0, 1, 12), ('Set', (1, 0, 1, 12), [('Starred', (1, 1, 1, 8), ('Set', (1, 2, 1, 8), [('Constant', (1, 3, 1, 4), 1, None), ('Constant', (1, 6, 1, 7), 2, None)]), ('Load',)), ('Constant', (1, 10, 1, 11), 3, None)]))], []),
2565 ('Module', [('AsyncFunctionDef', (1, 0, 2, 21), 'f', ('arguments', [], [], None, [], [], None, []), [('Expr', (2, 1, 2, 21), ('ListComp', (2, 1, 2, 21), ('Name', (2, 2, 2, 3), 'i', ('Load',)), [('comprehension', ('Name', (2, 14, 2, 15), 'b', ('Store',)), ('Name', (2, 19, 2, 20), 'c', ('Load',)), [], 1)]))], [], None, None)], []),
2566 ('Module', [('FunctionDef', (4, 0, 4, 13), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (4, 9, 4, 13))], [('Name', (1, 1, 1, 6), 'deco1', ('Load',)), ('Call', (2, 1, 2, 8), ('Name', (2, 1, 2, 6), 'deco2', ('Load',)), [], []), ('Call', (3, 1, 3, 9), ('Name', (3, 1, 3, 6), 'deco3', ('Load',)), [('Constant', (3, 7, 3, 8), 1, None)], [])], None, None)], []),
2567 ('Module', [('AsyncFunctionDef', (4, 0, 4, 19), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (4, 15, 4, 19))], [('Name', (1, 1, 1, 6), 'deco1', ('Load',)), ('Call', (2, 1, 2, 8), ('Name', (2, 1, 2, 6), 'deco2', ('Load',)), [], []), ('Call', (3, 1, 3, 9), ('Name', (3, 1, 3, 6), 'deco3', ('Load',)), [('Constant', (3, 7, 3, 8), 1, None)], [])], None, None)], []),
2568 ('Module', [('ClassDef', (4, 0, 4, 13), 'C', [], [], [('Pass', (4, 9, 4, 13))], [('Name', (1, 1, 1, 6), 'deco1', ('Load',)), ('Call', (2, 1, 2, 8), ('Name', (2, 1, 2, 6), 'deco2', ('Load',)), [], []), ('Call', (3, 1, 3, 9), ('Name', (3, 1, 3, 6), 'deco3', ('Load',)), [('Constant', (3, 7, 3, 8), 1, None)], [])])], []),
2569 ('Module', [('FunctionDef', (2, 0, 2, 13), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (2, 9, 2, 13))], [('Call', (1, 1, 1, 19), ('Name', (1, 1, 1, 5), 'deco', ('Load',)), [('GeneratorExp', (1, 5, 1, 19), ('Name', (1, 6, 1, 7), 'a', ('Load',)), [('comprehension', ('Name', (1, 12, 1, 13), 'a', ('Store',)), ('Name', (1, 17, 1, 18), 'b', ('Load',)), [], 0)])], [])], None, None)], []),
2570 ('Module', [('FunctionDef', (2, 0, 2, 13), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (2, 9, 2, 13))], [('Attribute', (1, 1, 1, 6), ('Attribute', (1, 1, 1, 4), ('Name', (1, 1, 1, 2), 'a', ('Load',)), 'b', ('Load',)), 'c', ('Load',))], None, None)], []),
2571 ('Module', [('Expr', (1, 0, 1, 8), ('NamedExpr', (1, 1, 1, 7), ('Name', (1, 1, 1, 2), 'a', ('Store',)), ('Constant', (1, 6, 1, 7), 1, None)))], []),
2572 ('Module', [('FunctionDef', (1, 0, 1, 18), 'f', ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [], None, [], [], None, []), [('Pass', (1, 14, 1, 18))], [], None, None)], []),
2573 ('Module', [('FunctionDef', (1, 0, 1, 26), 'f', ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 12, 1, 13), 'c', None, None), ('arg', (1, 15, 1, 16), 'd', None, None), ('arg', (1, 18, 1, 19), 'e', None, None)], None, [], [], None, []), [('Pass', (1, 22, 1, 26))], [], None, None)], []),
2574 ('Module', [('FunctionDef', (1, 0, 1, 29), 'f', ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 12, 1, 13), 'c', None, None)], None, [('arg', (1, 18, 1, 19), 'd', None, None), ('arg', (1, 21, 1, 22), 'e', None, None)], [None, None], None, []), [('Pass', (1, 25, 1, 29))], [], None, None)], []),
2575 ('Module', [('FunctionDef', (1, 0, 1, 39), 'f', ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 12, 1, 13), 'c', None, None)], None, [('arg', (1, 18, 1, 19), 'd', None, None), ('arg', (1, 21, 1, 22), 'e', None, None)], [None, None], ('arg', (1, 26, 1, 32), 'kwargs', None, None), []), [('Pass', (1, 35, 1, 39))], [], None, None)], []),
2576 ('Module', [('FunctionDef', (1, 0, 1, 20), 'f', ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [], None, [], [], None, [('Constant', (1, 8, 1, 9), 1, None)]), [('Pass', (1, 16, 1, 20))], [], None, None)], []),
2577 ('Module', [('FunctionDef', (1, 0, 1, 29), 'f', ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 14, 1, 15), 'b', None, None), ('arg', (1, 19, 1, 20), 'c', None, None)], None, [], [], None, [('Constant', (1, 8, 1, 9), 1, None), ('Constant', (1, 16, 1, 17), 2, None), ('Constant', (1, 21, 1, 22), 4, None)]), [('Pass', (1, 25, 1, 29))], [], None, None)], []),
2578 ('Module', [('FunctionDef', (1, 0, 1, 32), 'f', ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 14, 1, 15), 'b', None, None)], None, [('arg', (1, 22, 1, 23), 'c', None, None)], [('Constant', (1, 24, 1, 25), 4, None)], None, [('Constant', (1, 8, 1, 9), 1, None), ('Constant', (1, 16, 1, 17), 2, None)]), [('Pass', (1, 28, 1, 32))], [], None, None)], []),
2579 ('Module', [('FunctionDef', (1, 0, 1, 30), 'f', ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 14, 1, 15), 'b', None, None)], None, [('arg', (1, 22, 1, 23), 'c', None, None)], [None], None, [('Constant', (1, 8, 1, 9), 1, None), ('Constant', (1, 16, 1, 17), 2, None)]), [('Pass', (1, 26, 1, 30))], [], None, None)], []),
2580 ('Module', [('FunctionDef', (1, 0, 1, 42), 'f', ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 14, 1, 15), 'b', None, None)], None, [('arg', (1, 22, 1, 23), 'c', None, None)], [('Constant', (1, 24, 1, 25), 4, None)], ('arg', (1, 29, 1, 35), 'kwargs', None, None), [('Constant', (1, 8, 1, 9), 1, None), ('Constant', (1, 16, 1, 17), 2, None)]), [('Pass', (1, 38, 1, 42))], [], None, None)], []),
2581 ('Module', [('FunctionDef', (1, 0, 1, 40), 'f', ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 14, 1, 15), 'b', None, None)], None, [('arg', (1, 22, 1, 23), 'c', None, None)], [None], ('arg', (1, 27, 1, 33), 'kwargs', None, None), [('Constant', (1, 8, 1, 9), 1, None), ('Constant', (1, 16, 1, 17), 2, None)]), [('Pass', (1, 36, 1, 40))], [], None, None)], []),
2582 ]
2583 single_results = [
2584 ('Interactive', [('Expr', (1, 0, 1, 3), ('BinOp', (1, 0, 1, 3), ('Constant', (1, 0, 1, 1), 1, None), ('Add',), ('Constant', (1, 2, 1, 3), 2, None)))]),
2585 ]
2586 eval_results = [
2587 ('Expression', ('Constant', (1, 0, 1, 4), None, None)),
2588 ('Expression', ('BoolOp', (1, 0, 1, 7), ('And',), [('Name', (1, 0, 1, 1), 'a', ('Load',)), ('Name', (1, 6, 1, 7), 'b', ('Load',))])),
2589 ('Expression', ('BinOp', (1, 0, 1, 5), ('Name', (1, 0, 1, 1), 'a', ('Load',)), ('Add',), ('Name', (1, 4, 1, 5), 'b', ('Load',)))),
2590 ('Expression', ('UnaryOp', (1, 0, 1, 5), ('Not',), ('Name', (1, 4, 1, 5), 'v', ('Load',)))),
2591 ('Expression', ('Lambda', (1, 0, 1, 11), ('arguments', [], [], None, [], [], None, []), ('Constant', (1, 7, 1, 11), None, None))),
2592 ('Expression', ('Dict', (1, 0, 1, 7), [('Constant', (1, 2, 1, 3), 1, None)], [('Constant', (1, 4, 1, 5), 2, None)])),
2593 ('Expression', ('Dict', (1, 0, 1, 2), [], [])),
2594 ('Expression', ('Set', (1, 0, 1, 7), [('Constant', (1, 1, 1, 5), None, None)])),
2595 ('Expression', ('Dict', (1, 0, 5, 6), [('Constant', (2, 6, 2, 7), 1, None)], [('Constant', (4, 10, 4, 11), 2, None)])),
2596 ('Expression', ('ListComp', (1, 0, 1, 19), ('Name', (1, 1, 1, 2), 'a', ('Load',)), [('comprehension', ('Name', (1, 7, 1, 8), 'b', ('Store',)), ('Name', (1, 12, 1, 13), 'c', ('Load',)), [('Name', (1, 17, 1, 18), 'd', ('Load',))], 0)])),
2597 ('Expression', ('GeneratorExp', (1, 0, 1, 19), ('Name', (1, 1, 1, 2), 'a', ('Load',)), [('comprehension', ('Name', (1, 7, 1, 8), 'b', ('Store',)), ('Name', (1, 12, 1, 13), 'c', ('Load',)), [('Name', (1, 17, 1, 18), 'd', ('Load',))], 0)])),
2598 ('Expression', ('ListComp', (1, 0, 1, 20), ('Tuple', (1, 1, 1, 6), [('Name', (1, 2, 1, 3), 'a', ('Load',)), ('Name', (1, 4, 1, 5), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11, 1, 14), [('Name', (1, 11, 1, 12), 'a', ('Store',)), ('Name', (1, 13, 1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 18, 1, 19), 'c', ('Load',)), [], 0)])),
2599 ('Expression', ('ListComp', (1, 0, 1, 22), ('Tuple', (1, 1, 1, 6), [('Name', (1, 2, 1, 3), 'a', ('Load',)), ('Name', (1, 4, 1, 5), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11, 1, 16), [('Name', (1, 12, 1, 13), 'a', ('Store',)), ('Name', (1, 14, 1, 15), 'b', ('Store',))], ('Store',)), ('Name', (1, 20, 1, 21), 'c', ('Load',)), [], 0)])),
2600 ('Expression', ('ListComp', (1, 0, 1, 22), ('Tuple', (1, 1, 1, 6), [('Name', (1, 2, 1, 3), 'a', ('Load',)), ('Name', (1, 4, 1, 5), 'b', ('Load',))], ('Load',)), [('comprehension', ('List', (1, 11, 1, 16), [('Name', (1, 12, 1, 13), 'a', ('Store',)), ('Name', (1, 14, 1, 15), 'b', ('Store',))], ('Store',)), ('Name', (1, 20, 1, 21), 'c', ('Load',)), [], 0)])),
2601 ('Expression', ('SetComp', (1, 0, 1, 20), ('Tuple', (1, 1, 1, 6), [('Name', (1, 2, 1, 3), 'a', ('Load',)), ('Name', (1, 4, 1, 5), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11, 1, 14), [('Name', (1, 11, 1, 12), 'a', ('Store',)), ('Name', (1, 13, 1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 18, 1, 19), 'c', ('Load',)), [], 0)])),
2602 ('Expression', ('SetComp', (1, 0, 1, 22), ('Tuple', (1, 1, 1, 6), [('Name', (1, 2, 1, 3), 'a', ('Load',)), ('Name', (1, 4, 1, 5), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11, 1, 16), [('Name', (1, 12, 1, 13), 'a', ('Store',)), ('Name', (1, 14, 1, 15), 'b', ('Store',))], ('Store',)), ('Name', (1, 20, 1, 21), 'c', ('Load',)), [], 0)])),
2603 ('Expression', ('SetComp', (1, 0, 1, 22), ('Tuple', (1, 1, 1, 6), [('Name', (1, 2, 1, 3), 'a', ('Load',)), ('Name', (1, 4, 1, 5), 'b', ('Load',))], ('Load',)), [('comprehension', ('List', (1, 11, 1, 16), [('Name', (1, 12, 1, 13), 'a', ('Store',)), ('Name', (1, 14, 1, 15), 'b', ('Store',))], ('Store',)), ('Name', (1, 20, 1, 21), 'c', ('Load',)), [], 0)])),
2604 ('Expression', ('GeneratorExp', (1, 0, 1, 20), ('Tuple', (1, 1, 1, 6), [('Name', (1, 2, 1, 3), 'a', ('Load',)), ('Name', (1, 4, 1, 5), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11, 1, 14), [('Name', (1, 11, 1, 12), 'a', ('Store',)), ('Name', (1, 13, 1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 18, 1, 19), 'c', ('Load',)), [], 0)])),
2605 ('Expression', ('GeneratorExp', (1, 0, 1, 22), ('Tuple', (1, 1, 1, 6), [('Name', (1, 2, 1, 3), 'a', ('Load',)), ('Name', (1, 4, 1, 5), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11, 1, 16), [('Name', (1, 12, 1, 13), 'a', ('Store',)), ('Name', (1, 14, 1, 15), 'b', ('Store',))], ('Store',)), ('Name', (1, 20, 1, 21), 'c', ('Load',)), [], 0)])),
2606 ('Expression', ('GeneratorExp', (1, 0, 1, 22), ('Tuple', (1, 1, 1, 6), [('Name', (1, 2, 1, 3), 'a', ('Load',)), ('Name', (1, 4, 1, 5), 'b', ('Load',))], ('Load',)), [('comprehension', ('List', (1, 11, 1, 16), [('Name', (1, 12, 1, 13), 'a', ('Store',)), ('Name', (1, 14, 1, 15), 'b', ('Store',))], ('Store',)), ('Name', (1, 20, 1, 21), 'c', ('Load',)), [], 0)])),
2607 ('Expression', ('Compare', (1, 0, 1, 9), ('Constant', (1, 0, 1, 1), 1, None), [('Lt',), ('Lt',)], [('Constant', (1, 4, 1, 5), 2, None), ('Constant', (1, 8, 1, 9), 3, None)])),
2608 ('Expression', ('Call', (1, 0, 1, 17), ('Name', (1, 0, 1, 1), 'f', ('Load',)), [('Constant', (1, 2, 1, 3), 1, None), ('Constant', (1, 4, 1, 5), 2, None), ('Starred', (1, 10, 1, 12), ('Name', (1, 11, 1, 12), 'd', ('Load',)), ('Load',))], [('keyword', (1, 6, 1, 9), 'c', ('Constant', (1, 8, 1, 9), 3, None)), ('keyword', (1, 13, 1, 16), None, ('Name', (1, 15, 1, 16), 'e', ('Load',)))])),
2609 ('Expression', ('Call', (1, 0, 1, 10), ('Name', (1, 0, 1, 1), 'f', ('Load',)), [('Starred', (1, 2, 1, 9), ('List', (1, 3, 1, 9), [('Constant', (1, 4, 1, 5), 0, None), ('Constant', (1, 7, 1, 8), 1, None)], ('Load',)), ('Load',))], [])),
2610 ('Expression', ('Call', (1, 0, 1, 15), ('Name', (1, 0, 1, 1), 'f', ('Load',)), [('GeneratorExp', (1, 1, 1, 15), ('Name', (1, 2, 1, 3), 'a', ('Load',)), [('comprehension', ('Name', (1, 8, 1, 9), 'a', ('Store',)), ('Name', (1, 13, 1, 14), 'b', ('Load',)), [], 0)])], [])),
2611 ('Expression', ('Constant', (1, 0, 1, 2), 10, None)),
2612 ('Expression', ('Constant', (1, 0, 1, 8), 'string', None)),
2613 ('Expression', ('Attribute', (1, 0, 1, 3), ('Name', (1, 0, 1, 1), 'a', ('Load',)), 'b', ('Load',))),
2614 ('Expression', ('Subscript', (1, 0, 1, 6), ('Name', (1, 0, 1, 1), 'a', ('Load',)), ('Slice', (1, 2, 1, 5), ('Name', (1, 2, 1, 3), 'b', ('Load',)), ('Name', (1, 4, 1, 5), 'c', ('Load',)), None), ('Load',))),
2615 ('Expression', ('Name', (1, 0, 1, 1), 'v', ('Load',))),
2616 ('Expression', ('List', (1, 0, 1, 7), [('Constant', (1, 1, 1, 2), 1, None), ('Constant', (1, 3, 1, 4), 2, None), ('Constant', (1, 5, 1, 6), 3, None)], ('Load',))),
2617 ('Expression', ('List', (1, 0, 1, 2), [], ('Load',))),
2618 ('Expression', ('Tuple', (1, 0, 1, 5), [('Constant', (1, 0, 1, 1), 1, None), ('Constant', (1, 2, 1, 3), 2, None), ('Constant', (1, 4, 1, 5), 3, None)], ('Load',))),
2619 ('Expression', ('Tuple', (1, 0, 1, 7), [('Constant', (1, 1, 1, 2), 1, None), ('Constant', (1, 3, 1, 4), 2, None), ('Constant', (1, 5, 1, 6), 3, None)], ('Load',))),
2620 ('Expression', ('Tuple', (1, 0, 1, 2), [], ('Load',))),
2621 ('Expression', ('Call', (1, 0, 1, 17), ('Attribute', (1, 0, 1, 7), ('Attribute', (1, 0, 1, 5), ('Attribute', (1, 0, 1, 3), ('Name', (1, 0, 1, 1), 'a', ('Load',)), 'b', ('Load',)), 'c', ('Load',)), 'd', ('Load',)), [('Subscript', (1, 8, 1, 16), ('Attribute', (1, 8, 1, 11), ('Name', (1, 8, 1, 9), 'a', ('Load',)), 'b', ('Load',)), ('Slice', (1, 12, 1, 15), ('Constant', (1, 12, 1, 13), 1, None), ('Constant', (1, 14, 1, 15), 2, None), None), ('Load',))], [])),
2622 ]
2623 main()