blob: cd35f96a146632b7849a8078bb0232dc4c89ba5b [file] [log] [blame]
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001import ast
2import dis
Benjamin Peterson832bfe22011-08-09 16:15:04 -05003import os
4import sys
5import unittest
Serhiy Storchakac3ea41e2019-08-26 10:13:19 +03006import warnings
Benjamin Peterson9ed37432012-07-08 11:13:36 -07007import weakref
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00008from textwrap import dedent
Benjamin Peterson9ed37432012-07-08 11:13:36 -07009
10from test import support
Tim Peters400cbc32006-02-28 18:44:41 +000011
12def to_tuple(t):
Guido van Rossum3172c5d2007-10-16 18:12:55 +000013 if t is None or isinstance(t, (str, int, complex)):
Tim Peters400cbc32006-02-28 18:44:41 +000014 return t
15 elif isinstance(t, list):
16 return [to_tuple(e) for e in t]
17 result = [t.__class__.__name__]
Martin v. Löwis49c5da12006-03-01 22:49:05 +000018 if hasattr(t, 'lineno') and hasattr(t, 'col_offset'):
19 result.append((t.lineno, t.col_offset))
Tim Peters400cbc32006-02-28 18:44:41 +000020 if t._fields is None:
21 return tuple(result)
22 for f in t._fields:
23 result.append(to_tuple(getattr(t, f)))
24 return tuple(result)
25
Neal Norwitzee9b10a2008-03-31 05:29:39 +000026
Tim Peters400cbc32006-02-28 18:44:41 +000027# These tests are compiled through "exec"
Ezio Melotti85a86292013-08-17 16:57:41 +030028# There should be at least one test per statement
Tim Peters400cbc32006-02-28 18:44:41 +000029exec_tests = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050030 # None
31 "None",
INADA Naokicb41b272017-02-23 00:31:59 +090032 # Module docstring
33 "'module docstring'",
Tim Peters400cbc32006-02-28 18:44:41 +000034 # FunctionDef
35 "def f(): pass",
INADA Naokicb41b272017-02-23 00:31:59 +090036 # FunctionDef with docstring
37 "def f(): 'function docstring'",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050038 # FunctionDef with arg
39 "def f(a): pass",
40 # FunctionDef with arg and default value
41 "def f(a=0): pass",
42 # FunctionDef with varargs
43 "def f(*args): pass",
44 # FunctionDef with kwargs
45 "def f(**kwargs): pass",
INADA Naokicb41b272017-02-23 00:31:59 +090046 # FunctionDef with all kind of args and docstring
47 "def f(a, b=1, c=None, d=[], e={}, *args, f=42, **kwargs): 'doc for f()'",
Tim Peters400cbc32006-02-28 18:44:41 +000048 # ClassDef
49 "class C:pass",
INADA Naokicb41b272017-02-23 00:31:59 +090050 # ClassDef with docstring
51 "class C: 'docstring for class C'",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050052 # ClassDef, new style class
53 "class C(object): pass",
Tim Peters400cbc32006-02-28 18:44:41 +000054 # Return
55 "def f():return 1",
56 # Delete
57 "del v",
58 # Assign
59 "v = 1",
Serhiy Storchakab619b092018-11-27 09:40:29 +020060 "a,b = c",
61 "(a,b) = c",
62 "[a,b] = c",
Tim Peters400cbc32006-02-28 18:44:41 +000063 # AugAssign
64 "v += 1",
Tim Peters400cbc32006-02-28 18:44:41 +000065 # For
66 "for v in v:pass",
67 # While
68 "while v:pass",
69 # If
70 "if v:pass",
Lysandros Nikolaou025a6022019-12-12 22:40:21 +010071 # If-Elif
72 "if a:\n pass\nelif b:\n pass",
Lysandros Nikolaou5936a4c2019-12-14 11:24:57 +010073 # If-Elif-Else
74 "if a:\n pass\nelif b:\n pass\nelse:\n pass",
Benjamin Petersonaeabd5f2011-05-27 15:02:03 -050075 # With
76 "with x as y: pass",
77 "with x as y, z as q: pass",
Tim Peters400cbc32006-02-28 18:44:41 +000078 # Raise
Collin Winter828f04a2007-08-31 00:04:24 +000079 "raise Exception('string')",
Tim Peters400cbc32006-02-28 18:44:41 +000080 # TryExcept
81 "try:\n pass\nexcept Exception:\n pass",
82 # TryFinally
83 "try:\n pass\nfinally:\n pass",
84 # Assert
85 "assert v",
86 # Import
87 "import sys",
88 # ImportFrom
89 "from sys import v",
Tim Peters400cbc32006-02-28 18:44:41 +000090 # Global
91 "global v",
92 # Expr
93 "1",
94 # Pass,
95 "pass",
96 # Break
Yury Selivanovb3d53132015-09-01 16:10:49 -040097 "for v in v:break",
Tim Peters400cbc32006-02-28 18:44:41 +000098 # Continue
Yury Selivanovb3d53132015-09-01 16:10:49 -040099 "for v in v:continue",
Benjamin Peterson2e4b0e12009-09-11 22:36:20 +0000100 # for statements with naked tuples (see http://bugs.python.org/issue6704)
101 "for a,b in c: pass",
Serhiy Storchakab619b092018-11-27 09:40:29 +0200102 "for (a,b) in c: pass",
103 "for [a,b] in c: pass",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500104 # Multiline generator expression (test for .lineno & .col_offset)
105 """(
106 (
107 Aa
108 ,
109 Bb
110 )
111 for
112 Aa
113 ,
114 Bb in Cc
115 )""",
116 # dictcomp
117 "{a : b for w in x for m in p if g}",
118 # dictcomp with naked tuple
119 "{a : b for v,w in x}",
120 # setcomp
121 "{r for l in x if g}",
122 # setcomp with naked tuple
123 "{r for l,m in x}",
Yury Selivanov75445082015-05-11 22:57:16 -0400124 # AsyncFunctionDef
INADA Naokicb41b272017-02-23 00:31:59 +0900125 "async def f():\n 'async function'\n await something()",
Yury Selivanov75445082015-05-11 22:57:16 -0400126 # AsyncFor
127 "async def f():\n async for e in i: 1\n else: 2",
128 # AsyncWith
129 "async def f():\n async with a as b: 1",
Yury Selivanovb3d53132015-09-01 16:10:49 -0400130 # PEP 448: Additional Unpacking Generalizations
131 "{**{1:2}, 2:3}",
132 "{*{1, 2}, 3}",
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700133 # Asynchronous comprehensions
134 "async def f():\n [i async for b in c]",
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200135 # Decorated FunctionDef
Serhiy Storchaka26ae9f62019-10-26 16:46:05 +0300136 "@deco1\n@deco2()\n@deco3(1)\ndef f(): pass",
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200137 # Decorated AsyncFunctionDef
Serhiy Storchaka26ae9f62019-10-26 16:46:05 +0300138 "@deco1\n@deco2()\n@deco3(1)\nasync def f(): pass",
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200139 # Decorated ClassDef
Serhiy Storchaka26ae9f62019-10-26 16:46:05 +0300140 "@deco1\n@deco2()\n@deco3(1)\nclass C: pass",
Serhiy Storchakab619b092018-11-27 09:40:29 +0200141 # Decorator with generator argument
142 "@deco(a for a in b)\ndef f(): pass",
Pablo Galindo0c9258a2019-03-18 13:51:53 +0000143 # Simple assignment expression
144 "(a := 1)",
Pablo Galindo2f58a842019-05-31 14:09:49 +0100145 # Positional-only arguments
146 "def f(a, /,): pass",
147 "def f(a, /, c, d, e): pass",
148 "def f(a, /, c, *, d, e): pass",
149 "def f(a, /, c, *, d, e, **kwargs): pass",
150 # Positional-only arguments with defaults
151 "def f(a=1, /,): pass",
152 "def f(a=1, /, b=2, c=4): pass",
153 "def f(a=1, /, b=2, *, c=4): pass",
154 "def f(a=1, /, b=2, *, c): pass",
155 "def f(a=1, /, b=2, *, c=4, **kwargs): pass",
156 "def f(a=1, /, b=2, *, c, **kwargs): pass",
Pablo Galindo0c9258a2019-03-18 13:51:53 +0000157
Tim Peters400cbc32006-02-28 18:44:41 +0000158]
159
160# These are compiled through "single"
161# because of overlap with "eval", it just tests what
162# can't be tested with "eval"
163single_tests = [
164 "1+2"
165]
166
167# These are compiled through "eval"
168# It should test all expressions
169eval_tests = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500170 # None
171 "None",
Tim Peters400cbc32006-02-28 18:44:41 +0000172 # BoolOp
173 "a and b",
174 # BinOp
175 "a + b",
176 # UnaryOp
177 "not v",
178 # Lambda
179 "lambda:None",
180 # Dict
181 "{ 1:2 }",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500182 # Empty dict
183 "{}",
184 # Set
185 "{None,}",
186 # Multiline dict (test for .lineno & .col_offset)
187 """{
188 1
189 :
190 2
191 }""",
Tim Peters400cbc32006-02-28 18:44:41 +0000192 # ListComp
193 "[a for b in c if d]",
194 # GeneratorExp
195 "(a for b in c if d)",
Serhiy Storchakab619b092018-11-27 09:40:29 +0200196 # Comprehensions with multiple for targets
197 "[(a,b) for a,b in c]",
198 "[(a,b) for (a,b) in c]",
199 "[(a,b) for [a,b] in c]",
200 "{(a,b) for a,b in c}",
201 "{(a,b) for (a,b) in c}",
202 "{(a,b) for [a,b] in c}",
203 "((a,b) for a,b in c)",
204 "((a,b) for (a,b) in c)",
205 "((a,b) for [a,b] in c)",
Tim Peters400cbc32006-02-28 18:44:41 +0000206 # Yield - yield expressions can't work outside a function
207 #
208 # Compare
209 "1 < 2 < 3",
210 # Call
211 "f(1,2,c=3,*d,**e)",
Serhiy Storchakab619b092018-11-27 09:40:29 +0200212 # Call with a generator argument
213 "f(a for a in b)",
Tim Peters400cbc32006-02-28 18:44:41 +0000214 # Num
Guido van Rossume2a383d2007-01-15 16:59:06 +0000215 "10",
Tim Peters400cbc32006-02-28 18:44:41 +0000216 # Str
217 "'string'",
218 # Attribute
219 "a.b",
220 # Subscript
221 "a[b:c]",
222 # Name
223 "v",
224 # List
225 "[1,2,3]",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500226 # Empty list
227 "[]",
Tim Peters400cbc32006-02-28 18:44:41 +0000228 # Tuple
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000229 "1,2,3",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500230 # Tuple
231 "(1,2,3)",
232 # Empty tuple
233 "()",
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000234 # Combination
235 "a.b.c.d(a.b[1:2])",
236
Tim Peters400cbc32006-02-28 18:44:41 +0000237]
238
239# TODO: expr_context, slice, boolop, operator, unaryop, cmpop, comprehension
240# excepthandler, arguments, keywords, alias
241
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000242class AST_Tests(unittest.TestCase):
Tim Peters400cbc32006-02-28 18:44:41 +0000243
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500244 def _assertTrueorder(self, ast_node, parent_pos):
Georg Brandl0c77a822008-06-10 16:37:50 +0000245 if not isinstance(ast_node, ast.AST) or ast_node._fields is None:
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000246 return
Georg Brandl0c77a822008-06-10 16:37:50 +0000247 if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000248 node_pos = (ast_node.lineno, ast_node.col_offset)
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200249 self.assertGreaterEqual(node_pos, parent_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000250 parent_pos = (ast_node.lineno, ast_node.col_offset)
251 for name in ast_node._fields:
252 value = getattr(ast_node, name)
253 if isinstance(value, list):
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200254 first_pos = parent_pos
255 if value and name == 'decorator_list':
256 first_pos = (value[0].lineno, value[0].col_offset)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000257 for child in value:
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200258 self._assertTrueorder(child, first_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000259 elif value is not None:
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500260 self._assertTrueorder(value, parent_pos)
Tim Peters5ddfe412006-03-01 23:02:57 +0000261
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500262 def test_AST_objects(self):
263 x = ast.AST()
264 self.assertEqual(x._fields, ())
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700265 x.foobar = 42
266 self.assertEqual(x.foobar, 42)
267 self.assertEqual(x.__dict__["foobar"], 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500268
269 with self.assertRaises(AttributeError):
270 x.vararg
271
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500272 with self.assertRaises(TypeError):
273 # "_ast.AST constructor takes 0 positional arguments"
274 ast.AST(2)
275
Benjamin Peterson9ed37432012-07-08 11:13:36 -0700276 def test_AST_garbage_collection(self):
277 class X:
278 pass
279 a = ast.AST()
280 a.x = X()
281 a.x.a = a
282 ref = weakref.ref(a.x)
283 del a
284 support.gc_collect()
285 self.assertIsNone(ref())
286
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000287 def test_snippets(self):
288 for input, output, kind in ((exec_tests, exec_results, "exec"),
289 (single_tests, single_results, "single"),
290 (eval_tests, eval_results, "eval")):
291 for i, o in zip(input, output):
Yury Selivanovb3d53132015-09-01 16:10:49 -0400292 with self.subTest(action="parsing", input=i):
293 ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST)
294 self.assertEqual(to_tuple(ast_tree), o)
295 self._assertTrueorder(ast_tree, (0, 0))
Victor Stinner15a30952016-02-08 22:45:06 +0100296 with self.subTest(action="compiling", input=i, kind=kind):
297 compile(ast_tree, "?", kind)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000298
Pablo Galindo0c9258a2019-03-18 13:51:53 +0000299 def test_ast_validation(self):
300 # compile() is the only function that calls PyAST_Validate
301 snippets_to_validate = exec_tests + single_tests + eval_tests
302 for snippet in snippets_to_validate:
303 tree = ast.parse(snippet)
304 compile(tree, '<string>', 'exec')
305
Benjamin Peterson78565b22009-06-28 19:19:51 +0000306 def test_slice(self):
307 slc = ast.parse("x[::]").body[0].value.slice
308 self.assertIsNone(slc.upper)
309 self.assertIsNone(slc.lower)
310 self.assertIsNone(slc.step)
311
312 def test_from_import(self):
313 im = ast.parse("from . import y").body[0]
314 self.assertIsNone(im.module)
315
Benjamin Petersona4e4e352012-03-22 08:19:04 -0400316 def test_non_interned_future_from_ast(self):
317 mod = ast.parse("from __future__ import division")
318 self.assertIsInstance(mod.body[0], ast.ImportFrom)
319 mod.body[0].module = " __future__ ".strip()
320 compile(mod, "<test>", "exec")
321
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000322 def test_base_classes(self):
323 self.assertTrue(issubclass(ast.For, ast.stmt))
324 self.assertTrue(issubclass(ast.Name, ast.expr))
325 self.assertTrue(issubclass(ast.stmt, ast.AST))
326 self.assertTrue(issubclass(ast.expr, ast.AST))
327 self.assertTrue(issubclass(ast.comprehension, ast.AST))
328 self.assertTrue(issubclass(ast.Gt, ast.AST))
329
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500330 def test_field_attr_existence(self):
331 for name, item in ast.__dict__.items():
332 if isinstance(item, type) and name != 'AST' and name[0].isupper():
333 x = item()
334 if isinstance(x, ast.AST):
335 self.assertEqual(type(x._fields), tuple)
336
337 def test_arguments(self):
338 x = ast.arguments()
Pablo Galindocd6e83b2019-07-15 01:32:18 +0200339 self.assertEqual(x._fields, ('posonlyargs', 'args', 'vararg', 'kwonlyargs',
340 'kw_defaults', 'kwarg', 'defaults'))
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500341
342 with self.assertRaises(AttributeError):
343 x.vararg
344
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100345 x = ast.arguments(*range(1, 8))
346 self.assertEqual(x.vararg, 3)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500347
348 def test_field_attr_writable(self):
349 x = ast.Num()
350 # We can assign to _fields
351 x._fields = 666
352 self.assertEqual(x._fields, 666)
353
354 def test_classattrs(self):
355 x = ast.Num()
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700356 self.assertEqual(x._fields, ('value', 'kind'))
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300357
358 with self.assertRaises(AttributeError):
359 x.value
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500360
361 with self.assertRaises(AttributeError):
362 x.n
363
364 x = ast.Num(42)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300365 self.assertEqual(x.value, 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500366 self.assertEqual(x.n, 42)
367
368 with self.assertRaises(AttributeError):
369 x.lineno
370
371 with self.assertRaises(AttributeError):
372 x.foobar
373
374 x = ast.Num(lineno=2)
375 self.assertEqual(x.lineno, 2)
376
377 x = ast.Num(42, lineno=0)
378 self.assertEqual(x.lineno, 0)
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700379 self.assertEqual(x._fields, ('value', 'kind'))
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300380 self.assertEqual(x.value, 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500381 self.assertEqual(x.n, 42)
382
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700383 self.assertRaises(TypeError, ast.Num, 1, None, 2)
384 self.assertRaises(TypeError, ast.Num, 1, None, 2, lineno=0)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500385
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300386 self.assertEqual(ast.Num(42).n, 42)
387 self.assertEqual(ast.Num(4.25).n, 4.25)
388 self.assertEqual(ast.Num(4.25j).n, 4.25j)
389 self.assertEqual(ast.Str('42').s, '42')
390 self.assertEqual(ast.Bytes(b'42').s, b'42')
391 self.assertIs(ast.NameConstant(True).value, True)
392 self.assertIs(ast.NameConstant(False).value, False)
393 self.assertIs(ast.NameConstant(None).value, None)
394
395 self.assertEqual(ast.Constant(42).value, 42)
396 self.assertEqual(ast.Constant(4.25).value, 4.25)
397 self.assertEqual(ast.Constant(4.25j).value, 4.25j)
398 self.assertEqual(ast.Constant('42').value, '42')
399 self.assertEqual(ast.Constant(b'42').value, b'42')
400 self.assertIs(ast.Constant(True).value, True)
401 self.assertIs(ast.Constant(False).value, False)
402 self.assertIs(ast.Constant(None).value, None)
403 self.assertIs(ast.Constant(...).value, ...)
404
405 def test_realtype(self):
406 self.assertEqual(type(ast.Num(42)), ast.Constant)
407 self.assertEqual(type(ast.Num(4.25)), ast.Constant)
408 self.assertEqual(type(ast.Num(4.25j)), ast.Constant)
409 self.assertEqual(type(ast.Str('42')), ast.Constant)
410 self.assertEqual(type(ast.Bytes(b'42')), ast.Constant)
411 self.assertEqual(type(ast.NameConstant(True)), ast.Constant)
412 self.assertEqual(type(ast.NameConstant(False)), ast.Constant)
413 self.assertEqual(type(ast.NameConstant(None)), ast.Constant)
414 self.assertEqual(type(ast.Ellipsis()), ast.Constant)
415
416 def test_isinstance(self):
417 self.assertTrue(isinstance(ast.Num(42), ast.Num))
418 self.assertTrue(isinstance(ast.Num(4.2), ast.Num))
419 self.assertTrue(isinstance(ast.Num(4.2j), ast.Num))
420 self.assertTrue(isinstance(ast.Str('42'), ast.Str))
421 self.assertTrue(isinstance(ast.Bytes(b'42'), ast.Bytes))
422 self.assertTrue(isinstance(ast.NameConstant(True), ast.NameConstant))
423 self.assertTrue(isinstance(ast.NameConstant(False), ast.NameConstant))
424 self.assertTrue(isinstance(ast.NameConstant(None), ast.NameConstant))
425 self.assertTrue(isinstance(ast.Ellipsis(), ast.Ellipsis))
426
427 self.assertTrue(isinstance(ast.Constant(42), ast.Num))
428 self.assertTrue(isinstance(ast.Constant(4.2), ast.Num))
429 self.assertTrue(isinstance(ast.Constant(4.2j), ast.Num))
430 self.assertTrue(isinstance(ast.Constant('42'), ast.Str))
431 self.assertTrue(isinstance(ast.Constant(b'42'), ast.Bytes))
432 self.assertTrue(isinstance(ast.Constant(True), ast.NameConstant))
433 self.assertTrue(isinstance(ast.Constant(False), ast.NameConstant))
434 self.assertTrue(isinstance(ast.Constant(None), ast.NameConstant))
435 self.assertTrue(isinstance(ast.Constant(...), ast.Ellipsis))
436
437 self.assertFalse(isinstance(ast.Str('42'), ast.Num))
438 self.assertFalse(isinstance(ast.Num(42), ast.Str))
439 self.assertFalse(isinstance(ast.Str('42'), ast.Bytes))
440 self.assertFalse(isinstance(ast.Num(42), ast.NameConstant))
441 self.assertFalse(isinstance(ast.Num(42), ast.Ellipsis))
Anthony Sottile74176222019-01-18 11:30:28 -0800442 self.assertFalse(isinstance(ast.NameConstant(True), ast.Num))
443 self.assertFalse(isinstance(ast.NameConstant(False), ast.Num))
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300444
445 self.assertFalse(isinstance(ast.Constant('42'), ast.Num))
446 self.assertFalse(isinstance(ast.Constant(42), ast.Str))
447 self.assertFalse(isinstance(ast.Constant('42'), ast.Bytes))
448 self.assertFalse(isinstance(ast.Constant(42), ast.NameConstant))
449 self.assertFalse(isinstance(ast.Constant(42), ast.Ellipsis))
Anthony Sottile74176222019-01-18 11:30:28 -0800450 self.assertFalse(isinstance(ast.Constant(True), ast.Num))
451 self.assertFalse(isinstance(ast.Constant(False), ast.Num))
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300452
453 self.assertFalse(isinstance(ast.Constant(), ast.Num))
454 self.assertFalse(isinstance(ast.Constant(), ast.Str))
455 self.assertFalse(isinstance(ast.Constant(), ast.Bytes))
456 self.assertFalse(isinstance(ast.Constant(), ast.NameConstant))
457 self.assertFalse(isinstance(ast.Constant(), ast.Ellipsis))
458
Serhiy Storchaka6015cc52018-10-28 13:43:03 +0200459 class S(str): pass
460 self.assertTrue(isinstance(ast.Constant(S('42')), ast.Str))
461 self.assertFalse(isinstance(ast.Constant(S('42')), ast.Num))
462
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300463 def test_subclasses(self):
464 class N(ast.Num):
465 def __init__(self, *args, **kwargs):
466 super().__init__(*args, **kwargs)
467 self.z = 'spam'
468 class N2(ast.Num):
469 pass
470
471 n = N(42)
472 self.assertEqual(n.n, 42)
473 self.assertEqual(n.z, 'spam')
474 self.assertEqual(type(n), N)
475 self.assertTrue(isinstance(n, N))
476 self.assertTrue(isinstance(n, ast.Num))
477 self.assertFalse(isinstance(n, N2))
478 self.assertFalse(isinstance(ast.Num(42), N))
479 n = N(n=42)
480 self.assertEqual(n.n, 42)
481 self.assertEqual(type(n), N)
482
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500483 def test_module(self):
484 body = [ast.Num(42)]
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800485 x = ast.Module(body, [])
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500486 self.assertEqual(x.body, body)
487
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000488 def test_nodeclasses(self):
Florent Xicluna992d9e02011-11-11 19:35:42 +0100489 # Zero arguments constructor explicitly allowed
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500490 x = ast.BinOp()
491 self.assertEqual(x._fields, ('left', 'op', 'right'))
492
493 # Random attribute allowed too
494 x.foobarbaz = 5
495 self.assertEqual(x.foobarbaz, 5)
496
497 n1 = ast.Num(1)
498 n3 = ast.Num(3)
499 addop = ast.Add()
500 x = ast.BinOp(n1, addop, n3)
501 self.assertEqual(x.left, n1)
502 self.assertEqual(x.op, addop)
503 self.assertEqual(x.right, n3)
Benjamin Peterson68b543a2011-06-27 17:51:18 -0500504
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500505 x = ast.BinOp(1, 2, 3)
506 self.assertEqual(x.left, 1)
507 self.assertEqual(x.op, 2)
508 self.assertEqual(x.right, 3)
509
Georg Brandl0c77a822008-06-10 16:37:50 +0000510 x = ast.BinOp(1, 2, 3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000511 self.assertEqual(x.left, 1)
512 self.assertEqual(x.op, 2)
513 self.assertEqual(x.right, 3)
514 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000515
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500516 # node raises exception when given too many arguments
517 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500518 # node raises exception when given too many arguments
519 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4, lineno=0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000520
521 # can set attributes through kwargs too
Georg Brandl0c77a822008-06-10 16:37:50 +0000522 x = ast.BinOp(left=1, op=2, right=3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000523 self.assertEqual(x.left, 1)
524 self.assertEqual(x.op, 2)
525 self.assertEqual(x.right, 3)
526 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000527
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500528 # Random kwargs also allowed
529 x = ast.BinOp(1, 2, 3, foobarbaz=42)
530 self.assertEqual(x.foobarbaz, 42)
531
532 def test_no_fields(self):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000533 # this used to fail because Sub._fields was None
Georg Brandl0c77a822008-06-10 16:37:50 +0000534 x = ast.Sub()
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500535 self.assertEqual(x._fields, ())
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000536
537 def test_pickling(self):
538 import pickle
539 mods = [pickle]
540 try:
541 import cPickle
542 mods.append(cPickle)
543 except ImportError:
544 pass
545 protocols = [0, 1, 2]
546 for mod in mods:
547 for protocol in protocols:
548 for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests):
549 ast2 = mod.loads(mod.dumps(ast, protocol))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000550 self.assertEqual(to_tuple(ast2), to_tuple(ast))
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000551
Benjamin Peterson5b066812010-11-20 01:38:49 +0000552 def test_invalid_sum(self):
553 pos = dict(lineno=2, col_offset=3)
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800554 m = ast.Module([ast.Expr(ast.expr(**pos), **pos)], [])
Benjamin Peterson5b066812010-11-20 01:38:49 +0000555 with self.assertRaises(TypeError) as cm:
556 compile(m, "<test>", "exec")
557 self.assertIn("but got <_ast.expr", str(cm.exception))
558
Min ho Kimc4cacc82019-07-31 08:16:13 +1000559 def test_invalid_identifier(self):
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800560 m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))], [])
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500561 ast.fix_missing_locations(m)
562 with self.assertRaises(TypeError) as cm:
563 compile(m, "<test>", "exec")
564 self.assertIn("identifier must be of type str", str(cm.exception))
565
Mark Dickinsonded35ae2012-11-25 14:36:26 +0000566 def test_empty_yield_from(self):
567 # Issue 16546: yield from value is not optional.
568 empty_yield_from = ast.parse("def f():\n yield from g()")
569 empty_yield_from.body[0].body[0].value.value = None
570 with self.assertRaises(ValueError) as cm:
571 compile(empty_yield_from, "<test>", "exec")
572 self.assertIn("field value is required", str(cm.exception))
573
Oren Milman7dc46d82017-09-30 20:16:24 +0300574 @support.cpython_only
575 def test_issue31592(self):
576 # There shouldn't be an assertion failure in case of a bad
577 # unicodedata.normalize().
578 import unicodedata
579 def bad_normalize(*args):
580 return None
581 with support.swap_attr(unicodedata, 'normalize', bad_normalize):
582 self.assertRaises(TypeError, ast.parse, '\u03D5')
583
Carl Friedrich Bolz-Tereick110a47c2019-07-08 23:17:56 +0200584 def test_issue18374_binop_col_offset(self):
585 tree = ast.parse('4+5+6+7')
586 parent_binop = tree.body[0].value
587 child_binop = parent_binop.left
588 grandchild_binop = child_binop.left
589 self.assertEqual(parent_binop.col_offset, 0)
590 self.assertEqual(parent_binop.end_col_offset, 7)
591 self.assertEqual(child_binop.col_offset, 0)
592 self.assertEqual(child_binop.end_col_offset, 5)
593 self.assertEqual(grandchild_binop.col_offset, 0)
594 self.assertEqual(grandchild_binop.end_col_offset, 3)
595
596 tree = ast.parse('4+5-\\\n 6-7')
597 parent_binop = tree.body[0].value
598 child_binop = parent_binop.left
599 grandchild_binop = child_binop.left
600 self.assertEqual(parent_binop.col_offset, 0)
601 self.assertEqual(parent_binop.lineno, 1)
602 self.assertEqual(parent_binop.end_col_offset, 4)
603 self.assertEqual(parent_binop.end_lineno, 2)
604
605 self.assertEqual(child_binop.col_offset, 0)
Carl Friedrich Bolz-Tereick430a9f42019-07-09 14:20:01 +0200606 self.assertEqual(child_binop.lineno, 1)
Carl Friedrich Bolz-Tereick110a47c2019-07-08 23:17:56 +0200607 self.assertEqual(child_binop.end_col_offset, 2)
Carl Friedrich Bolz-Tereick430a9f42019-07-09 14:20:01 +0200608 self.assertEqual(child_binop.end_lineno, 2)
Carl Friedrich Bolz-Tereick110a47c2019-07-08 23:17:56 +0200609
610 self.assertEqual(grandchild_binop.col_offset, 0)
Carl Friedrich Bolz-Tereick430a9f42019-07-09 14:20:01 +0200611 self.assertEqual(grandchild_binop.lineno, 1)
Carl Friedrich Bolz-Tereick110a47c2019-07-08 23:17:56 +0200612 self.assertEqual(grandchild_binop.end_col_offset, 3)
Carl Friedrich Bolz-Tereick430a9f42019-07-09 14:20:01 +0200613 self.assertEqual(grandchild_binop.end_lineno, 1)
Georg Brandl0c77a822008-06-10 16:37:50 +0000614
615class ASTHelpers_Test(unittest.TestCase):
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700616 maxDiff = None
Georg Brandl0c77a822008-06-10 16:37:50 +0000617
618 def test_parse(self):
619 a = ast.parse('foo(1 + 1)')
620 b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST)
621 self.assertEqual(ast.dump(a), ast.dump(b))
622
Benjamin Peterson2e2c9032012-09-02 14:23:15 -0400623 def test_parse_in_error(self):
624 try:
625 1/0
626 except Exception:
Benjamin Petersonbd0df502012-09-02 15:04:51 -0400627 with self.assertRaises(SyntaxError) as e:
628 ast.literal_eval(r"'\U'")
629 self.assertIsNotNone(e.exception.__context__)
Benjamin Peterson2e2c9032012-09-02 14:23:15 -0400630
Georg Brandl0c77a822008-06-10 16:37:50 +0000631 def test_dump(self):
632 node = ast.parse('spam(eggs, "and cheese")')
633 self.assertEqual(ast.dump(node),
634 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700635 "args=[Name(id='eggs', ctx=Load()), Constant(value='and cheese', kind=None)], "
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800636 "keywords=[]))], type_ignores=[])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000637 )
638 self.assertEqual(ast.dump(node, annotate_fields=False),
639 "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700640 "Constant('and cheese', None)], []))], [])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000641 )
642 self.assertEqual(ast.dump(node, include_attributes=True),
643 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000644 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=4), "
645 "args=[Name(id='eggs', ctx=Load(), lineno=1, col_offset=5, "
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700646 "end_lineno=1, end_col_offset=9), Constant(value='and cheese', kind=None, "
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000647 "lineno=1, col_offset=11, end_lineno=1, end_col_offset=23)], keywords=[], "
648 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=24), "
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800649 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=24)], type_ignores=[])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000650 )
651
Serhiy Storchaka850573b2019-09-09 19:33:13 +0300652 def test_dump_indent(self):
653 node = ast.parse('spam(eggs, "and cheese")')
654 self.assertEqual(ast.dump(node, indent=3), """\
655Module(
656 body=[
657 Expr(
658 value=Call(
659 func=Name(id='spam', ctx=Load()),
660 args=[
661 Name(id='eggs', ctx=Load()),
662 Constant(value='and cheese', kind=None)],
663 keywords=[]))],
664 type_ignores=[])""")
665 self.assertEqual(ast.dump(node, annotate_fields=False, indent='\t'), """\
666Module(
667\t[
668\t\tExpr(
669\t\t\tCall(
670\t\t\t\tName('spam', Load()),
671\t\t\t\t[
672\t\t\t\t\tName('eggs', Load()),
673\t\t\t\t\tConstant('and cheese', None)],
674\t\t\t\t[]))],
675\t[])""")
676 self.assertEqual(ast.dump(node, include_attributes=True, indent=3), """\
677Module(
678 body=[
679 Expr(
680 value=Call(
681 func=Name(
682 id='spam',
683 ctx=Load(),
684 lineno=1,
685 col_offset=0,
686 end_lineno=1,
687 end_col_offset=4),
688 args=[
689 Name(
690 id='eggs',
691 ctx=Load(),
692 lineno=1,
693 col_offset=5,
694 end_lineno=1,
695 end_col_offset=9),
696 Constant(
697 value='and cheese',
698 kind=None,
699 lineno=1,
700 col_offset=11,
701 end_lineno=1,
702 end_col_offset=23)],
703 keywords=[],
704 lineno=1,
705 col_offset=0,
706 end_lineno=1,
707 end_col_offset=24),
708 lineno=1,
709 col_offset=0,
710 end_lineno=1,
711 end_col_offset=24)],
712 type_ignores=[])""")
713
Serhiy Storchakae64f9482019-08-29 09:30:23 +0300714 def test_dump_incomplete(self):
715 node = ast.Raise(lineno=3, col_offset=4)
716 self.assertEqual(ast.dump(node),
717 "Raise()"
718 )
719 self.assertEqual(ast.dump(node, include_attributes=True),
720 "Raise(lineno=3, col_offset=4)"
721 )
722 node = ast.Raise(exc=ast.Name(id='e', ctx=ast.Load()), lineno=3, col_offset=4)
723 self.assertEqual(ast.dump(node),
724 "Raise(exc=Name(id='e', ctx=Load()))"
725 )
726 self.assertEqual(ast.dump(node, annotate_fields=False),
727 "Raise(Name('e', Load()))"
728 )
729 self.assertEqual(ast.dump(node, include_attributes=True),
730 "Raise(exc=Name(id='e', ctx=Load()), lineno=3, col_offset=4)"
731 )
732 self.assertEqual(ast.dump(node, annotate_fields=False, include_attributes=True),
733 "Raise(Name('e', Load()), lineno=3, col_offset=4)"
734 )
735 node = ast.Raise(cause=ast.Name(id='e', ctx=ast.Load()))
736 self.assertEqual(ast.dump(node),
737 "Raise(cause=Name(id='e', ctx=Load()))"
738 )
739 self.assertEqual(ast.dump(node, annotate_fields=False),
740 "Raise(cause=Name('e', Load()))"
741 )
742
Georg Brandl0c77a822008-06-10 16:37:50 +0000743 def test_copy_location(self):
744 src = ast.parse('1 + 1', mode='eval')
745 src.body.right = ast.copy_location(ast.Num(2), src.body.right)
746 self.assertEqual(ast.dump(src, include_attributes=True),
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700747 'Expression(body=BinOp(left=Constant(value=1, kind=None, lineno=1, col_offset=0, '
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000748 'end_lineno=1, end_col_offset=1), op=Add(), right=Constant(value=2, '
749 'lineno=1, col_offset=4, end_lineno=1, end_col_offset=5), lineno=1, '
750 'col_offset=0, end_lineno=1, end_col_offset=5))'
Georg Brandl0c77a822008-06-10 16:37:50 +0000751 )
752
753 def test_fix_missing_locations(self):
754 src = ast.parse('write("spam")')
755 src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()),
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400756 [ast.Str('eggs')], [])))
Georg Brandl0c77a822008-06-10 16:37:50 +0000757 self.assertEqual(src, ast.fix_missing_locations(src))
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000758 self.maxDiff = None
Georg Brandl0c77a822008-06-10 16:37:50 +0000759 self.assertEqual(ast.dump(src, include_attributes=True),
760 "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), "
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000761 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=5), "
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700762 "args=[Constant(value='spam', kind=None, lineno=1, col_offset=6, end_lineno=1, "
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000763 "end_col_offset=12)], keywords=[], lineno=1, col_offset=0, end_lineno=1, "
764 "end_col_offset=13), lineno=1, col_offset=0, end_lineno=1, "
765 "end_col_offset=13), Expr(value=Call(func=Name(id='spam', ctx=Load(), "
766 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=0), "
767 "args=[Constant(value='eggs', lineno=1, col_offset=0, end_lineno=1, "
768 "end_col_offset=0)], keywords=[], lineno=1, col_offset=0, end_lineno=1, "
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800769 "end_col_offset=0), lineno=1, col_offset=0, end_lineno=1, end_col_offset=0)], "
770 "type_ignores=[])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000771 )
772
773 def test_increment_lineno(self):
774 src = ast.parse('1 + 1', mode='eval')
775 self.assertEqual(ast.increment_lineno(src, n=3), src)
776 self.assertEqual(ast.dump(src, include_attributes=True),
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700777 'Expression(body=BinOp(left=Constant(value=1, kind=None, lineno=4, col_offset=0, '
778 'end_lineno=4, end_col_offset=1), op=Add(), right=Constant(value=1, kind=None, '
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000779 'lineno=4, col_offset=4, end_lineno=4, end_col_offset=5), lineno=4, '
780 'col_offset=0, end_lineno=4, end_col_offset=5))'
Georg Brandl0c77a822008-06-10 16:37:50 +0000781 )
Georg Brandl619e7ba2011-01-09 07:38:51 +0000782 # issue10869: do not increment lineno of root twice
Georg Brandlefb69022011-01-09 07:50:48 +0000783 src = ast.parse('1 + 1', mode='eval')
Georg Brandl619e7ba2011-01-09 07:38:51 +0000784 self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
785 self.assertEqual(ast.dump(src, include_attributes=True),
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700786 'Expression(body=BinOp(left=Constant(value=1, kind=None, lineno=4, col_offset=0, '
787 'end_lineno=4, end_col_offset=1), op=Add(), right=Constant(value=1, kind=None, '
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000788 'lineno=4, col_offset=4, end_lineno=4, end_col_offset=5), lineno=4, '
789 'col_offset=0, end_lineno=4, end_col_offset=5))'
Georg Brandl619e7ba2011-01-09 07:38:51 +0000790 )
Georg Brandl0c77a822008-06-10 16:37:50 +0000791
792 def test_iter_fields(self):
793 node = ast.parse('foo()', mode='eval')
794 d = dict(ast.iter_fields(node.body))
795 self.assertEqual(d.pop('func').id, 'foo')
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400796 self.assertEqual(d, {'keywords': [], 'args': []})
Georg Brandl0c77a822008-06-10 16:37:50 +0000797
798 def test_iter_child_nodes(self):
799 node = ast.parse("spam(23, 42, eggs='leek')", mode='eval')
800 self.assertEqual(len(list(ast.iter_child_nodes(node.body))), 4)
801 iterator = ast.iter_child_nodes(node.body)
802 self.assertEqual(next(iterator).id, 'spam')
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300803 self.assertEqual(next(iterator).value, 23)
804 self.assertEqual(next(iterator).value, 42)
Georg Brandl0c77a822008-06-10 16:37:50 +0000805 self.assertEqual(ast.dump(next(iterator)),
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700806 "keyword(arg='eggs', value=Constant(value='leek', kind=None))"
Georg Brandl0c77a822008-06-10 16:37:50 +0000807 )
808
809 def test_get_docstring(self):
Serhiy Storchaka08f127a2018-06-15 11:05:15 +0300810 node = ast.parse('"""line one\n line two"""')
811 self.assertEqual(ast.get_docstring(node),
812 'line one\nline two')
813
814 node = ast.parse('class foo:\n """line one\n line two"""')
815 self.assertEqual(ast.get_docstring(node.body[0]),
816 'line one\nline two')
817
Georg Brandl0c77a822008-06-10 16:37:50 +0000818 node = ast.parse('def foo():\n """line one\n line two"""')
819 self.assertEqual(ast.get_docstring(node.body[0]),
820 'line one\nline two')
821
Yury Selivanov2f07a662015-07-23 08:54:35 +0300822 node = ast.parse('async def foo():\n """spam\n ham"""')
823 self.assertEqual(ast.get_docstring(node.body[0]), 'spam\nham')
Serhiy Storchaka08f127a2018-06-15 11:05:15 +0300824
825 def test_get_docstring_none(self):
Matthias Bussonnier41cea702017-02-23 22:44:19 -0800826 self.assertIsNone(ast.get_docstring(ast.parse('')))
Serhiy Storchaka08f127a2018-06-15 11:05:15 +0300827 node = ast.parse('x = "not docstring"')
828 self.assertIsNone(ast.get_docstring(node))
829 node = ast.parse('def foo():\n pass')
830 self.assertIsNone(ast.get_docstring(node))
831
832 node = ast.parse('class foo:\n pass')
833 self.assertIsNone(ast.get_docstring(node.body[0]))
834 node = ast.parse('class foo:\n x = "not docstring"')
835 self.assertIsNone(ast.get_docstring(node.body[0]))
836 node = ast.parse('class foo:\n def bar(self): pass')
837 self.assertIsNone(ast.get_docstring(node.body[0]))
838
839 node = ast.parse('def foo():\n pass')
840 self.assertIsNone(ast.get_docstring(node.body[0]))
841 node = ast.parse('def foo():\n x = "not docstring"')
842 self.assertIsNone(ast.get_docstring(node.body[0]))
843
844 node = ast.parse('async def foo():\n pass')
845 self.assertIsNone(ast.get_docstring(node.body[0]))
846 node = ast.parse('async def foo():\n x = "not docstring"')
847 self.assertIsNone(ast.get_docstring(node.body[0]))
Yury Selivanov2f07a662015-07-23 08:54:35 +0300848
Anthony Sottile995d9b92019-01-12 20:05:13 -0800849 def test_multi_line_docstring_col_offset_and_lineno_issue16806(self):
850 node = ast.parse(
851 '"""line one\nline two"""\n\n'
852 'def foo():\n """line one\n line two"""\n\n'
853 ' def bar():\n """line one\n line two"""\n'
854 ' """line one\n line two"""\n'
855 '"""line one\nline two"""\n\n'
856 )
857 self.assertEqual(node.body[0].col_offset, 0)
858 self.assertEqual(node.body[0].lineno, 1)
859 self.assertEqual(node.body[1].body[0].col_offset, 2)
860 self.assertEqual(node.body[1].body[0].lineno, 5)
861 self.assertEqual(node.body[1].body[1].body[0].col_offset, 4)
862 self.assertEqual(node.body[1].body[1].body[0].lineno, 9)
863 self.assertEqual(node.body[1].body[2].col_offset, 2)
864 self.assertEqual(node.body[1].body[2].lineno, 11)
865 self.assertEqual(node.body[2].col_offset, 0)
866 self.assertEqual(node.body[2].lineno, 13)
867
Lysandros Nikolaou025a6022019-12-12 22:40:21 +0100868 def test_elif_stmt_start_position(self):
869 node = ast.parse('if a:\n pass\nelif b:\n pass\n')
870 elif_stmt = node.body[0].orelse[0]
871 self.assertEqual(elif_stmt.lineno, 3)
872 self.assertEqual(elif_stmt.col_offset, 0)
873
Lysandros Nikolaou5936a4c2019-12-14 11:24:57 +0100874 def test_elif_stmt_start_position_with_else(self):
875 node = ast.parse('if a:\n pass\nelif b:\n pass\nelse:\n pass\n')
876 elif_stmt = node.body[0].orelse[0]
877 self.assertEqual(elif_stmt.lineno, 3)
878 self.assertEqual(elif_stmt.col_offset, 0)
879
Georg Brandl0c77a822008-06-10 16:37:50 +0000880 def test_literal_eval(self):
881 self.assertEqual(ast.literal_eval('[1, 2, 3]'), [1, 2, 3])
882 self.assertEqual(ast.literal_eval('{"foo": 42}'), {"foo": 42})
883 self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None))
Benjamin Peterson3e742892010-07-11 12:59:24 +0000884 self.assertEqual(ast.literal_eval('{1, 2, 3}'), {1, 2, 3})
Benjamin Peterson5ef96e52010-07-11 23:06:06 +0000885 self.assertEqual(ast.literal_eval('b"hi"'), b"hi")
Georg Brandl0c77a822008-06-10 16:37:50 +0000886 self.assertRaises(ValueError, ast.literal_eval, 'foo()')
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +0200887 self.assertEqual(ast.literal_eval('6'), 6)
888 self.assertEqual(ast.literal_eval('+6'), 6)
Raymond Hettingerbc959732010-10-08 00:47:45 +0000889 self.assertEqual(ast.literal_eval('-6'), -6)
Raymond Hettingerbc959732010-10-08 00:47:45 +0000890 self.assertEqual(ast.literal_eval('3.25'), 3.25)
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +0200891 self.assertEqual(ast.literal_eval('+3.25'), 3.25)
892 self.assertEqual(ast.literal_eval('-3.25'), -3.25)
893 self.assertEqual(repr(ast.literal_eval('-0.0')), '-0.0')
894 self.assertRaises(ValueError, ast.literal_eval, '++6')
895 self.assertRaises(ValueError, ast.literal_eval, '+True')
896 self.assertRaises(ValueError, ast.literal_eval, '2+3')
Georg Brandl0c77a822008-06-10 16:37:50 +0000897
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +0200898 def test_literal_eval_complex(self):
899 # Issue #4907
900 self.assertEqual(ast.literal_eval('6j'), 6j)
901 self.assertEqual(ast.literal_eval('-6j'), -6j)
902 self.assertEqual(ast.literal_eval('6.75j'), 6.75j)
903 self.assertEqual(ast.literal_eval('-6.75j'), -6.75j)
904 self.assertEqual(ast.literal_eval('3+6j'), 3+6j)
905 self.assertEqual(ast.literal_eval('-3+6j'), -3+6j)
906 self.assertEqual(ast.literal_eval('3-6j'), 3-6j)
907 self.assertEqual(ast.literal_eval('-3-6j'), -3-6j)
908 self.assertEqual(ast.literal_eval('3.25+6.75j'), 3.25+6.75j)
909 self.assertEqual(ast.literal_eval('-3.25+6.75j'), -3.25+6.75j)
910 self.assertEqual(ast.literal_eval('3.25-6.75j'), 3.25-6.75j)
911 self.assertEqual(ast.literal_eval('-3.25-6.75j'), -3.25-6.75j)
912 self.assertEqual(ast.literal_eval('(3+6j)'), 3+6j)
913 self.assertRaises(ValueError, ast.literal_eval, '-6j+3')
914 self.assertRaises(ValueError, ast.literal_eval, '-6j+3j')
915 self.assertRaises(ValueError, ast.literal_eval, '3+-6j')
916 self.assertRaises(ValueError, ast.literal_eval, '3+(0+6j)')
917 self.assertRaises(ValueError, ast.literal_eval, '-(3+6j)')
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000918
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100919 def test_bad_integer(self):
920 # issue13436: Bad error message with invalid numeric values
921 body = [ast.ImportFrom(module='time',
922 names=[ast.alias(name='sleep')],
923 level=None,
924 lineno=None, col_offset=None)]
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800925 mod = ast.Module(body, [])
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100926 with self.assertRaises(ValueError) as cm:
927 compile(mod, 'test', 'exec')
928 self.assertIn("invalid integer value: None", str(cm.exception))
929
Berker Peksag0a5bd512016-04-29 19:50:02 +0300930 def test_level_as_none(self):
931 body = [ast.ImportFrom(module='time',
932 names=[ast.alias(name='sleep')],
933 level=None,
934 lineno=0, col_offset=0)]
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800935 mod = ast.Module(body, [])
Berker Peksag0a5bd512016-04-29 19:50:02 +0300936 code = compile(mod, 'test', 'exec')
937 ns = {}
938 exec(code, ns)
939 self.assertIn('sleep', ns)
940
Georg Brandl0c77a822008-06-10 16:37:50 +0000941
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500942class ASTValidatorTests(unittest.TestCase):
943
944 def mod(self, mod, msg=None, mode="exec", *, exc=ValueError):
945 mod.lineno = mod.col_offset = 0
946 ast.fix_missing_locations(mod)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300947 if msg is None:
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500948 compile(mod, "<test>", mode)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300949 else:
950 with self.assertRaises(exc) as cm:
951 compile(mod, "<test>", mode)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500952 self.assertIn(msg, str(cm.exception))
953
954 def expr(self, node, msg=None, *, exc=ValueError):
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800955 mod = ast.Module([ast.Expr(node)], [])
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500956 self.mod(mod, msg, exc=exc)
957
958 def stmt(self, stmt, msg=None):
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800959 mod = ast.Module([stmt], [])
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500960 self.mod(mod, msg)
961
962 def test_module(self):
963 m = ast.Interactive([ast.Expr(ast.Name("x", ast.Store()))])
964 self.mod(m, "must have Load context", "single")
965 m = ast.Expression(ast.Name("x", ast.Store()))
966 self.mod(m, "must have Load context", "eval")
967
968 def _check_arguments(self, fac, check):
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100969 def arguments(args=None, posonlyargs=None, vararg=None,
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700970 kwonlyargs=None, kwarg=None,
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500971 defaults=None, kw_defaults=None):
972 if args is None:
973 args = []
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100974 if posonlyargs is None:
975 posonlyargs = []
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500976 if kwonlyargs is None:
977 kwonlyargs = []
978 if defaults is None:
979 defaults = []
980 if kw_defaults is None:
981 kw_defaults = []
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100982 args = ast.arguments(args, posonlyargs, vararg, kwonlyargs,
983 kw_defaults, kwarg, defaults)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500984 return fac(args)
985 args = [ast.arg("x", ast.Name("x", ast.Store()))]
986 check(arguments(args=args), "must have Load context")
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100987 check(arguments(posonlyargs=args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500988 check(arguments(kwonlyargs=args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500989 check(arguments(defaults=[ast.Num(3)]),
990 "more positional defaults than args")
991 check(arguments(kw_defaults=[ast.Num(4)]),
992 "length of kwonlyargs is not the same as kw_defaults")
993 args = [ast.arg("x", ast.Name("x", ast.Load()))]
994 check(arguments(args=args, defaults=[ast.Name("x", ast.Store())]),
995 "must have Load context")
996 args = [ast.arg("a", ast.Name("x", ast.Load())),
997 ast.arg("b", ast.Name("y", ast.Load()))]
998 check(arguments(kwonlyargs=args,
999 kw_defaults=[None, ast.Name("x", ast.Store())]),
1000 "must have Load context")
1001
1002 def test_funcdef(self):
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001003 a = ast.arguments([], [], None, [], [], None, [])
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001004 f = ast.FunctionDef("x", a, [], [], None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001005 self.stmt(f, "empty body on FunctionDef")
1006 f = ast.FunctionDef("x", a, [ast.Pass()], [ast.Name("x", ast.Store())],
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001007 None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001008 self.stmt(f, "must have Load context")
1009 f = ast.FunctionDef("x", a, [ast.Pass()], [],
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001010 ast.Name("x", ast.Store()))
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001011 self.stmt(f, "must have Load context")
1012 def fac(args):
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001013 return ast.FunctionDef("x", args, [ast.Pass()], [], None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001014 self._check_arguments(fac, self.stmt)
1015
1016 def test_classdef(self):
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001017 def cls(bases=None, keywords=None, body=None, decorator_list=None):
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001018 if bases is None:
1019 bases = []
1020 if keywords is None:
1021 keywords = []
1022 if body is None:
1023 body = [ast.Pass()]
1024 if decorator_list is None:
1025 decorator_list = []
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001026 return ast.ClassDef("myclass", bases, keywords,
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001027 body, decorator_list)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001028 self.stmt(cls(bases=[ast.Name("x", ast.Store())]),
1029 "must have Load context")
1030 self.stmt(cls(keywords=[ast.keyword("x", ast.Name("x", ast.Store()))]),
1031 "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001032 self.stmt(cls(body=[]), "empty body on ClassDef")
1033 self.stmt(cls(body=[None]), "None disallowed")
1034 self.stmt(cls(decorator_list=[ast.Name("x", ast.Store())]),
1035 "must have Load context")
1036
1037 def test_delete(self):
1038 self.stmt(ast.Delete([]), "empty targets on Delete")
1039 self.stmt(ast.Delete([None]), "None disallowed")
1040 self.stmt(ast.Delete([ast.Name("x", ast.Load())]),
1041 "must have Del context")
1042
1043 def test_assign(self):
1044 self.stmt(ast.Assign([], ast.Num(3)), "empty targets on Assign")
1045 self.stmt(ast.Assign([None], ast.Num(3)), "None disallowed")
1046 self.stmt(ast.Assign([ast.Name("x", ast.Load())], ast.Num(3)),
1047 "must have Store context")
1048 self.stmt(ast.Assign([ast.Name("x", ast.Store())],
1049 ast.Name("y", ast.Store())),
1050 "must have Load context")
1051
1052 def test_augassign(self):
1053 aug = ast.AugAssign(ast.Name("x", ast.Load()), ast.Add(),
1054 ast.Name("y", ast.Load()))
1055 self.stmt(aug, "must have Store context")
1056 aug = ast.AugAssign(ast.Name("x", ast.Store()), ast.Add(),
1057 ast.Name("y", ast.Store()))
1058 self.stmt(aug, "must have Load context")
1059
1060 def test_for(self):
1061 x = ast.Name("x", ast.Store())
1062 y = ast.Name("y", ast.Load())
1063 p = ast.Pass()
1064 self.stmt(ast.For(x, y, [], []), "empty body on For")
1065 self.stmt(ast.For(ast.Name("x", ast.Load()), y, [p], []),
1066 "must have Store context")
1067 self.stmt(ast.For(x, ast.Name("y", ast.Store()), [p], []),
1068 "must have Load context")
1069 e = ast.Expr(ast.Name("x", ast.Store()))
1070 self.stmt(ast.For(x, y, [e], []), "must have Load context")
1071 self.stmt(ast.For(x, y, [p], [e]), "must have Load context")
1072
1073 def test_while(self):
1074 self.stmt(ast.While(ast.Num(3), [], []), "empty body on While")
1075 self.stmt(ast.While(ast.Name("x", ast.Store()), [ast.Pass()], []),
1076 "must have Load context")
1077 self.stmt(ast.While(ast.Num(3), [ast.Pass()],
1078 [ast.Expr(ast.Name("x", ast.Store()))]),
1079 "must have Load context")
1080
1081 def test_if(self):
1082 self.stmt(ast.If(ast.Num(3), [], []), "empty body on If")
1083 i = ast.If(ast.Name("x", ast.Store()), [ast.Pass()], [])
1084 self.stmt(i, "must have Load context")
1085 i = ast.If(ast.Num(3), [ast.Expr(ast.Name("x", ast.Store()))], [])
1086 self.stmt(i, "must have Load context")
1087 i = ast.If(ast.Num(3), [ast.Pass()],
1088 [ast.Expr(ast.Name("x", ast.Store()))])
1089 self.stmt(i, "must have Load context")
1090
1091 def test_with(self):
1092 p = ast.Pass()
1093 self.stmt(ast.With([], [p]), "empty items on With")
1094 i = ast.withitem(ast.Num(3), None)
1095 self.stmt(ast.With([i], []), "empty body on With")
1096 i = ast.withitem(ast.Name("x", ast.Store()), None)
1097 self.stmt(ast.With([i], [p]), "must have Load context")
1098 i = ast.withitem(ast.Num(3), ast.Name("x", ast.Load()))
1099 self.stmt(ast.With([i], [p]), "must have Store context")
1100
1101 def test_raise(self):
1102 r = ast.Raise(None, ast.Num(3))
1103 self.stmt(r, "Raise with cause but no exception")
1104 r = ast.Raise(ast.Name("x", ast.Store()), None)
1105 self.stmt(r, "must have Load context")
1106 r = ast.Raise(ast.Num(4), ast.Name("x", ast.Store()))
1107 self.stmt(r, "must have Load context")
1108
1109 def test_try(self):
1110 p = ast.Pass()
1111 t = ast.Try([], [], [], [p])
1112 self.stmt(t, "empty body on Try")
1113 t = ast.Try([ast.Expr(ast.Name("x", ast.Store()))], [], [], [p])
1114 self.stmt(t, "must have Load context")
1115 t = ast.Try([p], [], [], [])
1116 self.stmt(t, "Try has neither except handlers nor finalbody")
1117 t = ast.Try([p], [], [p], [p])
1118 self.stmt(t, "Try has orelse but no except handlers")
1119 t = ast.Try([p], [ast.ExceptHandler(None, "x", [])], [], [])
1120 self.stmt(t, "empty body on ExceptHandler")
1121 e = [ast.ExceptHandler(ast.Name("x", ast.Store()), "y", [p])]
1122 self.stmt(ast.Try([p], e, [], []), "must have Load context")
1123 e = [ast.ExceptHandler(None, "x", [p])]
1124 t = ast.Try([p], e, [ast.Expr(ast.Name("x", ast.Store()))], [p])
1125 self.stmt(t, "must have Load context")
1126 t = ast.Try([p], e, [p], [ast.Expr(ast.Name("x", ast.Store()))])
1127 self.stmt(t, "must have Load context")
1128
1129 def test_assert(self):
1130 self.stmt(ast.Assert(ast.Name("x", ast.Store()), None),
1131 "must have Load context")
1132 assrt = ast.Assert(ast.Name("x", ast.Load()),
1133 ast.Name("y", ast.Store()))
1134 self.stmt(assrt, "must have Load context")
1135
1136 def test_import(self):
1137 self.stmt(ast.Import([]), "empty names on Import")
1138
1139 def test_importfrom(self):
1140 imp = ast.ImportFrom(None, [ast.alias("x", None)], -42)
Serhiy Storchaka7de28402016-06-27 23:40:43 +03001141 self.stmt(imp, "Negative ImportFrom level")
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001142 self.stmt(ast.ImportFrom(None, [], 0), "empty names on ImportFrom")
1143
1144 def test_global(self):
1145 self.stmt(ast.Global([]), "empty names on Global")
1146
1147 def test_nonlocal(self):
1148 self.stmt(ast.Nonlocal([]), "empty names on Nonlocal")
1149
1150 def test_expr(self):
1151 e = ast.Expr(ast.Name("x", ast.Store()))
1152 self.stmt(e, "must have Load context")
1153
1154 def test_boolop(self):
1155 b = ast.BoolOp(ast.And(), [])
1156 self.expr(b, "less than 2 values")
1157 b = ast.BoolOp(ast.And(), [ast.Num(3)])
1158 self.expr(b, "less than 2 values")
1159 b = ast.BoolOp(ast.And(), [ast.Num(4), None])
1160 self.expr(b, "None disallowed")
1161 b = ast.BoolOp(ast.And(), [ast.Num(4), ast.Name("x", ast.Store())])
1162 self.expr(b, "must have Load context")
1163
1164 def test_unaryop(self):
1165 u = ast.UnaryOp(ast.Not(), ast.Name("x", ast.Store()))
1166 self.expr(u, "must have Load context")
1167
1168 def test_lambda(self):
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001169 a = ast.arguments([], [], None, [], [], None, [])
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001170 self.expr(ast.Lambda(a, ast.Name("x", ast.Store())),
1171 "must have Load context")
1172 def fac(args):
1173 return ast.Lambda(args, ast.Name("x", ast.Load()))
1174 self._check_arguments(fac, self.expr)
1175
1176 def test_ifexp(self):
1177 l = ast.Name("x", ast.Load())
1178 s = ast.Name("y", ast.Store())
1179 for args in (s, l, l), (l, s, l), (l, l, s):
Benjamin Peterson71ce8972011-08-09 16:17:12 -05001180 self.expr(ast.IfExp(*args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001181
1182 def test_dict(self):
1183 d = ast.Dict([], [ast.Name("x", ast.Load())])
1184 self.expr(d, "same number of keys as values")
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001185 d = ast.Dict([ast.Name("x", ast.Load())], [None])
1186 self.expr(d, "None disallowed")
1187
1188 def test_set(self):
1189 self.expr(ast.Set([None]), "None disallowed")
1190 s = ast.Set([ast.Name("x", ast.Store())])
1191 self.expr(s, "must have Load context")
1192
1193 def _check_comprehension(self, fac):
1194 self.expr(fac([]), "comprehension with no generators")
1195 g = ast.comprehension(ast.Name("x", ast.Load()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001196 ast.Name("x", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001197 self.expr(fac([g]), "must have Store context")
1198 g = ast.comprehension(ast.Name("x", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001199 ast.Name("x", ast.Store()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001200 self.expr(fac([g]), "must have Load context")
1201 x = ast.Name("x", ast.Store())
1202 y = ast.Name("y", ast.Load())
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001203 g = ast.comprehension(x, y, [None], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001204 self.expr(fac([g]), "None disallowed")
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001205 g = ast.comprehension(x, y, [ast.Name("x", ast.Store())], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001206 self.expr(fac([g]), "must have Load context")
1207
1208 def _simple_comp(self, fac):
1209 g = ast.comprehension(ast.Name("x", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001210 ast.Name("x", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001211 self.expr(fac(ast.Name("x", ast.Store()), [g]),
1212 "must have Load context")
1213 def wrap(gens):
1214 return fac(ast.Name("x", ast.Store()), gens)
1215 self._check_comprehension(wrap)
1216
1217 def test_listcomp(self):
1218 self._simple_comp(ast.ListComp)
1219
1220 def test_setcomp(self):
1221 self._simple_comp(ast.SetComp)
1222
1223 def test_generatorexp(self):
1224 self._simple_comp(ast.GeneratorExp)
1225
1226 def test_dictcomp(self):
1227 g = ast.comprehension(ast.Name("y", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001228 ast.Name("p", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001229 c = ast.DictComp(ast.Name("x", ast.Store()),
1230 ast.Name("y", ast.Load()), [g])
1231 self.expr(c, "must have Load context")
1232 c = ast.DictComp(ast.Name("x", ast.Load()),
1233 ast.Name("y", ast.Store()), [g])
1234 self.expr(c, "must have Load context")
1235 def factory(comps):
1236 k = ast.Name("x", ast.Load())
1237 v = ast.Name("y", ast.Load())
1238 return ast.DictComp(k, v, comps)
1239 self._check_comprehension(factory)
1240
1241 def test_yield(self):
Benjamin Peterson527c6222012-01-14 08:58:23 -05001242 self.expr(ast.Yield(ast.Name("x", ast.Store())), "must have Load")
1243 self.expr(ast.YieldFrom(ast.Name("x", ast.Store())), "must have Load")
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001244
1245 def test_compare(self):
1246 left = ast.Name("x", ast.Load())
1247 comp = ast.Compare(left, [ast.In()], [])
1248 self.expr(comp, "no comparators")
1249 comp = ast.Compare(left, [ast.In()], [ast.Num(4), ast.Num(5)])
1250 self.expr(comp, "different number of comparators and operands")
1251 comp = ast.Compare(ast.Num("blah"), [ast.In()], [left])
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001252 self.expr(comp)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001253 comp = ast.Compare(left, [ast.In()], [ast.Num("blah")])
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001254 self.expr(comp)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001255
1256 def test_call(self):
1257 func = ast.Name("x", ast.Load())
1258 args = [ast.Name("y", ast.Load())]
1259 keywords = [ast.keyword("w", ast.Name("z", ast.Load()))]
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001260 call = ast.Call(ast.Name("x", ast.Store()), args, keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001261 self.expr(call, "must have Load context")
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001262 call = ast.Call(func, [None], keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001263 self.expr(call, "None disallowed")
1264 bad_keywords = [ast.keyword("w", ast.Name("z", ast.Store()))]
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001265 call = ast.Call(func, args, bad_keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001266 self.expr(call, "must have Load context")
1267
1268 def test_num(self):
1269 class subint(int):
1270 pass
1271 class subfloat(float):
1272 pass
1273 class subcomplex(complex):
1274 pass
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001275 for obj in "0", "hello":
1276 self.expr(ast.Num(obj))
1277 for obj in subint(), subfloat(), subcomplex():
1278 self.expr(ast.Num(obj), "invalid type", exc=TypeError)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001279
1280 def test_attribute(self):
1281 attr = ast.Attribute(ast.Name("x", ast.Store()), "y", ast.Load())
1282 self.expr(attr, "must have Load context")
1283
1284 def test_subscript(self):
1285 sub = ast.Subscript(ast.Name("x", ast.Store()), ast.Index(ast.Num(3)),
1286 ast.Load())
1287 self.expr(sub, "must have Load context")
1288 x = ast.Name("x", ast.Load())
1289 sub = ast.Subscript(x, ast.Index(ast.Name("y", ast.Store())),
1290 ast.Load())
1291 self.expr(sub, "must have Load context")
1292 s = ast.Name("x", ast.Store())
1293 for args in (s, None, None), (None, s, None), (None, None, s):
1294 sl = ast.Slice(*args)
1295 self.expr(ast.Subscript(x, sl, ast.Load()),
1296 "must have Load context")
1297 sl = ast.ExtSlice([])
1298 self.expr(ast.Subscript(x, sl, ast.Load()), "empty dims on ExtSlice")
1299 sl = ast.ExtSlice([ast.Index(s)])
1300 self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context")
1301
1302 def test_starred(self):
1303 left = ast.List([ast.Starred(ast.Name("x", ast.Load()), ast.Store())],
1304 ast.Store())
1305 assign = ast.Assign([left], ast.Num(4))
1306 self.stmt(assign, "must have Store context")
1307
1308 def _sequence(self, fac):
1309 self.expr(fac([None], ast.Load()), "None disallowed")
1310 self.expr(fac([ast.Name("x", ast.Store())], ast.Load()),
1311 "must have Load context")
1312
1313 def test_list(self):
1314 self._sequence(ast.List)
1315
1316 def test_tuple(self):
1317 self._sequence(ast.Tuple)
1318
Benjamin Peterson442f2092012-12-06 17:41:04 -05001319 def test_nameconstant(self):
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001320 self.expr(ast.NameConstant(4))
Benjamin Peterson442f2092012-12-06 17:41:04 -05001321
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001322 def test_stdlib_validates(self):
1323 stdlib = os.path.dirname(ast.__file__)
1324 tests = [fn for fn in os.listdir(stdlib) if fn.endswith(".py")]
1325 tests.extend(["test/test_grammar.py", "test/test_unpack_ex.py"])
1326 for module in tests:
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001327 with self.subTest(module):
1328 fn = os.path.join(stdlib, module)
1329 with open(fn, "r", encoding="utf-8") as fp:
1330 source = fp.read()
1331 mod = ast.parse(source, fn)
1332 compile(mod, fn, "exec")
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001333
1334
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001335class ConstantTests(unittest.TestCase):
1336 """Tests on the ast.Constant node type."""
1337
1338 def compile_constant(self, value):
1339 tree = ast.parse("x = 123")
1340
1341 node = tree.body[0].value
1342 new_node = ast.Constant(value=value)
1343 ast.copy_location(new_node, node)
1344 tree.body[0].value = new_node
1345
1346 code = compile(tree, "<string>", "exec")
1347
1348 ns = {}
1349 exec(code, ns)
1350 return ns['x']
1351
Victor Stinnerbe59d142016-01-27 00:39:12 +01001352 def test_validation(self):
1353 with self.assertRaises(TypeError) as cm:
1354 self.compile_constant([1, 2, 3])
1355 self.assertEqual(str(cm.exception),
1356 "got an invalid type in Constant: list")
1357
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001358 def test_singletons(self):
1359 for const in (None, False, True, Ellipsis, b'', frozenset()):
1360 with self.subTest(const=const):
1361 value = self.compile_constant(const)
1362 self.assertIs(value, const)
1363
1364 def test_values(self):
1365 nested_tuple = (1,)
1366 nested_frozenset = frozenset({1})
1367 for level in range(3):
1368 nested_tuple = (nested_tuple, 2)
1369 nested_frozenset = frozenset({nested_frozenset, 2})
1370 values = (123, 123.0, 123j,
1371 "unicode", b'bytes',
1372 tuple("tuple"), frozenset("frozenset"),
1373 nested_tuple, nested_frozenset)
1374 for value in values:
1375 with self.subTest(value=value):
1376 result = self.compile_constant(value)
1377 self.assertEqual(result, value)
1378
1379 def test_assign_to_constant(self):
1380 tree = ast.parse("x = 1")
1381
1382 target = tree.body[0].targets[0]
1383 new_target = ast.Constant(value=1)
1384 ast.copy_location(new_target, target)
1385 tree.body[0].targets[0] = new_target
1386
1387 with self.assertRaises(ValueError) as cm:
1388 compile(tree, "string", "exec")
1389 self.assertEqual(str(cm.exception),
1390 "expression which can't be assigned "
1391 "to in Store context")
1392
1393 def test_get_docstring(self):
1394 tree = ast.parse("'docstring'\nx = 1")
1395 self.assertEqual(ast.get_docstring(tree), 'docstring')
1396
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001397 def get_load_const(self, tree):
1398 # Compile to bytecode, disassemble and get parameter of LOAD_CONST
1399 # instructions
1400 co = compile(tree, '<string>', 'exec')
1401 consts = []
1402 for instr in dis.get_instructions(co):
1403 if instr.opname == 'LOAD_CONST':
1404 consts.append(instr.argval)
1405 return consts
1406
1407 @support.cpython_only
1408 def test_load_const(self):
1409 consts = [None,
1410 True, False,
1411 124,
1412 2.0,
1413 3j,
1414 "unicode",
1415 b'bytes',
1416 (1, 2, 3)]
1417
Victor Stinnera2724092016-02-08 18:17:58 +01001418 code = '\n'.join(['x={!r}'.format(const) for const in consts])
1419 code += '\nx = ...'
1420 consts.extend((Ellipsis, None))
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001421
1422 tree = ast.parse(code)
Victor Stinnera2724092016-02-08 18:17:58 +01001423 self.assertEqual(self.get_load_const(tree),
1424 consts)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001425
1426 # Replace expression nodes with constants
Victor Stinnera2724092016-02-08 18:17:58 +01001427 for assign, const in zip(tree.body, consts):
1428 assert isinstance(assign, ast.Assign), ast.dump(assign)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001429 new_node = ast.Constant(value=const)
Victor Stinnera2724092016-02-08 18:17:58 +01001430 ast.copy_location(new_node, assign.value)
1431 assign.value = new_node
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001432
Victor Stinnera2724092016-02-08 18:17:58 +01001433 self.assertEqual(self.get_load_const(tree),
1434 consts)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001435
1436 def test_literal_eval(self):
1437 tree = ast.parse("1 + 2")
1438 binop = tree.body[0].value
1439
1440 new_left = ast.Constant(value=10)
1441 ast.copy_location(new_left, binop.left)
1442 binop.left = new_left
1443
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +02001444 new_right = ast.Constant(value=20j)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001445 ast.copy_location(new_right, binop.right)
1446 binop.right = new_right
1447
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +02001448 self.assertEqual(ast.literal_eval(binop), 10+20j)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001449
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001450 def test_string_kind(self):
1451 c = ast.parse('"x"', mode='eval').body
1452 self.assertEqual(c.value, "x")
1453 self.assertEqual(c.kind, None)
1454
1455 c = ast.parse('u"x"', mode='eval').body
1456 self.assertEqual(c.value, "x")
1457 self.assertEqual(c.kind, "u")
1458
1459 c = ast.parse('r"x"', mode='eval').body
1460 self.assertEqual(c.value, "x")
1461 self.assertEqual(c.kind, None)
1462
1463 c = ast.parse('b"x"', mode='eval').body
1464 self.assertEqual(c.value, b"x")
1465 self.assertEqual(c.kind, None)
1466
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001467
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00001468class EndPositionTests(unittest.TestCase):
1469 """Tests for end position of AST nodes.
1470
1471 Testing end positions of nodes requires a bit of extra care
1472 because of how LL parsers work.
1473 """
1474 def _check_end_pos(self, ast_node, end_lineno, end_col_offset):
1475 self.assertEqual(ast_node.end_lineno, end_lineno)
1476 self.assertEqual(ast_node.end_col_offset, end_col_offset)
1477
1478 def _check_content(self, source, ast_node, content):
1479 self.assertEqual(ast.get_source_segment(source, ast_node), content)
1480
1481 def _parse_value(self, s):
1482 # Use duck-typing to support both single expression
1483 # and a right hand side of an assignment statement.
1484 return ast.parse(s).body[0].value
1485
1486 def test_lambda(self):
1487 s = 'lambda x, *y: None'
1488 lam = self._parse_value(s)
1489 self._check_content(s, lam.body, 'None')
1490 self._check_content(s, lam.args.args[0], 'x')
1491 self._check_content(s, lam.args.vararg, 'y')
1492
1493 def test_func_def(self):
1494 s = dedent('''
1495 def func(x: int,
1496 *args: str,
1497 z: float = 0,
1498 **kwargs: Any) -> bool:
1499 return True
1500 ''').strip()
1501 fdef = ast.parse(s).body[0]
1502 self._check_end_pos(fdef, 5, 15)
1503 self._check_content(s, fdef.body[0], 'return True')
1504 self._check_content(s, fdef.args.args[0], 'x: int')
1505 self._check_content(s, fdef.args.args[0].annotation, 'int')
1506 self._check_content(s, fdef.args.kwarg, 'kwargs: Any')
1507 self._check_content(s, fdef.args.kwarg.annotation, 'Any')
1508
1509 def test_call(self):
1510 s = 'func(x, y=2, **kw)'
1511 call = self._parse_value(s)
1512 self._check_content(s, call.func, 'func')
1513 self._check_content(s, call.keywords[0].value, '2')
1514 self._check_content(s, call.keywords[1].value, 'kw')
1515
1516 def test_call_noargs(self):
1517 s = 'x[0]()'
1518 call = self._parse_value(s)
1519 self._check_content(s, call.func, 'x[0]')
1520 self._check_end_pos(call, 1, 6)
1521
1522 def test_class_def(self):
1523 s = dedent('''
1524 class C(A, B):
1525 x: int = 0
1526 ''').strip()
1527 cdef = ast.parse(s).body[0]
1528 self._check_end_pos(cdef, 2, 14)
1529 self._check_content(s, cdef.bases[1], 'B')
1530 self._check_content(s, cdef.body[0], 'x: int = 0')
1531
1532 def test_class_kw(self):
1533 s = 'class S(metaclass=abc.ABCMeta): pass'
1534 cdef = ast.parse(s).body[0]
1535 self._check_content(s, cdef.keywords[0].value, 'abc.ABCMeta')
1536
1537 def test_multi_line_str(self):
1538 s = dedent('''
1539 x = """Some multi-line text.
1540
1541 It goes on starting from same indent."""
1542 ''').strip()
1543 assign = ast.parse(s).body[0]
1544 self._check_end_pos(assign, 3, 40)
1545 self._check_end_pos(assign.value, 3, 40)
1546
1547 def test_continued_str(self):
1548 s = dedent('''
1549 x = "first part" \\
1550 "second part"
1551 ''').strip()
1552 assign = ast.parse(s).body[0]
1553 self._check_end_pos(assign, 2, 13)
1554 self._check_end_pos(assign.value, 2, 13)
1555
1556 def test_suites(self):
1557 # We intentionally put these into the same string to check
1558 # that empty lines are not part of the suite.
1559 s = dedent('''
1560 while True:
1561 pass
1562
1563 if one():
1564 x = None
1565 elif other():
1566 y = None
1567 else:
1568 z = None
1569
1570 for x, y in stuff:
1571 assert True
1572
1573 try:
1574 raise RuntimeError
1575 except TypeError as e:
1576 pass
1577
1578 pass
1579 ''').strip()
1580 mod = ast.parse(s)
1581 while_loop = mod.body[0]
1582 if_stmt = mod.body[1]
1583 for_loop = mod.body[2]
1584 try_stmt = mod.body[3]
1585 pass_stmt = mod.body[4]
1586
1587 self._check_end_pos(while_loop, 2, 8)
1588 self._check_end_pos(if_stmt, 9, 12)
1589 self._check_end_pos(for_loop, 12, 15)
1590 self._check_end_pos(try_stmt, 17, 8)
1591 self._check_end_pos(pass_stmt, 19, 4)
1592
1593 self._check_content(s, while_loop.test, 'True')
1594 self._check_content(s, if_stmt.body[0], 'x = None')
1595 self._check_content(s, if_stmt.orelse[0].test, 'other()')
1596 self._check_content(s, for_loop.target, 'x, y')
1597 self._check_content(s, try_stmt.body[0], 'raise RuntimeError')
1598 self._check_content(s, try_stmt.handlers[0].type, 'TypeError')
1599
1600 def test_fstring(self):
1601 s = 'x = f"abc {x + y} abc"'
1602 fstr = self._parse_value(s)
1603 binop = fstr.values[1].value
1604 self._check_content(s, binop, 'x + y')
1605
1606 def test_fstring_multi_line(self):
1607 s = dedent('''
1608 f"""Some multi-line text.
1609 {
1610 arg_one
1611 +
1612 arg_two
1613 }
1614 It goes on..."""
1615 ''').strip()
1616 fstr = self._parse_value(s)
1617 binop = fstr.values[1].value
1618 self._check_end_pos(binop, 5, 7)
1619 self._check_content(s, binop.left, 'arg_one')
1620 self._check_content(s, binop.right, 'arg_two')
1621
1622 def test_import_from_multi_line(self):
1623 s = dedent('''
1624 from x.y.z import (
1625 a, b, c as c
1626 )
1627 ''').strip()
1628 imp = ast.parse(s).body[0]
1629 self._check_end_pos(imp, 3, 1)
1630
1631 def test_slices(self):
1632 s1 = 'f()[1, 2] [0]'
1633 s2 = 'x[ a.b: c.d]'
1634 sm = dedent('''
1635 x[ a.b: f () ,
1636 g () : c.d
1637 ]
1638 ''').strip()
1639 i1, i2, im = map(self._parse_value, (s1, s2, sm))
1640 self._check_content(s1, i1.value, 'f()[1, 2]')
1641 self._check_content(s1, i1.value.slice.value, '1, 2')
1642 self._check_content(s2, i2.slice.lower, 'a.b')
1643 self._check_content(s2, i2.slice.upper, 'c.d')
1644 self._check_content(sm, im.slice.dims[0].upper, 'f ()')
1645 self._check_content(sm, im.slice.dims[1].lower, 'g ()')
1646 self._check_end_pos(im, 3, 3)
1647
1648 def test_binop(self):
1649 s = dedent('''
1650 (1 * 2 + (3 ) +
1651 4
1652 )
1653 ''').strip()
1654 binop = self._parse_value(s)
1655 self._check_end_pos(binop, 2, 6)
1656 self._check_content(s, binop.right, '4')
1657 self._check_content(s, binop.left, '1 * 2 + (3 )')
1658 self._check_content(s, binop.left.right, '3')
1659
1660 def test_boolop(self):
1661 s = dedent('''
1662 if (one_condition and
1663 (other_condition or yet_another_one)):
1664 pass
1665 ''').strip()
1666 bop = ast.parse(s).body[0].test
1667 self._check_end_pos(bop, 2, 44)
1668 self._check_content(s, bop.values[1],
1669 'other_condition or yet_another_one')
1670
1671 def test_tuples(self):
1672 s1 = 'x = () ;'
1673 s2 = 'x = 1 , ;'
1674 s3 = 'x = (1 , 2 ) ;'
1675 sm = dedent('''
1676 x = (
1677 a, b,
1678 )
1679 ''').strip()
1680 t1, t2, t3, tm = map(self._parse_value, (s1, s2, s3, sm))
1681 self._check_content(s1, t1, '()')
1682 self._check_content(s2, t2, '1 ,')
1683 self._check_content(s3, t3, '(1 , 2 )')
1684 self._check_end_pos(tm, 3, 1)
1685
1686 def test_attribute_spaces(self):
1687 s = 'func(x. y .z)'
1688 call = self._parse_value(s)
1689 self._check_content(s, call, s)
1690 self._check_content(s, call.args[0], 'x. y .z')
1691
1692 def test_displays(self):
1693 s1 = '[{}, {1, }, {1, 2,} ]'
1694 s2 = '{a: b, f (): g () ,}'
1695 c1 = self._parse_value(s1)
1696 c2 = self._parse_value(s2)
1697 self._check_content(s1, c1.elts[0], '{}')
1698 self._check_content(s1, c1.elts[1], '{1, }')
1699 self._check_content(s1, c1.elts[2], '{1, 2,}')
1700 self._check_content(s2, c2.keys[1], 'f ()')
1701 self._check_content(s2, c2.values[1], 'g ()')
1702
1703 def test_comprehensions(self):
1704 s = dedent('''
1705 x = [{x for x, y in stuff
1706 if cond.x} for stuff in things]
1707 ''').strip()
1708 cmp = self._parse_value(s)
1709 self._check_end_pos(cmp, 2, 37)
1710 self._check_content(s, cmp.generators[0].iter, 'things')
1711 self._check_content(s, cmp.elt.generators[0].iter, 'stuff')
1712 self._check_content(s, cmp.elt.generators[0].ifs[0], 'cond.x')
1713 self._check_content(s, cmp.elt.generators[0].target, 'x, y')
1714
1715 def test_yield_await(self):
1716 s = dedent('''
1717 async def f():
1718 yield x
1719 await y
1720 ''').strip()
1721 fdef = ast.parse(s).body[0]
1722 self._check_content(s, fdef.body[0].value, 'yield x')
1723 self._check_content(s, fdef.body[1].value, 'await y')
1724
1725 def test_source_segment_multi(self):
1726 s_orig = dedent('''
1727 x = (
1728 a, b,
1729 ) + ()
1730 ''').strip()
1731 s_tuple = dedent('''
1732 (
1733 a, b,
1734 )
1735 ''').strip()
1736 binop = self._parse_value(s_orig)
1737 self.assertEqual(ast.get_source_segment(s_orig, binop.left), s_tuple)
1738
1739 def test_source_segment_padded(self):
1740 s_orig = dedent('''
1741 class C:
1742 def fun(self) -> None:
1743 "ЖЖЖЖЖ"
1744 ''').strip()
1745 s_method = ' def fun(self) -> None:\n' \
1746 ' "ЖЖЖЖЖ"'
1747 cdef = ast.parse(s_orig).body[0]
1748 self.assertEqual(ast.get_source_segment(s_orig, cdef.body[0], padded=True),
1749 s_method)
1750
1751 def test_source_segment_endings(self):
1752 s = 'v = 1\r\nw = 1\nx = 1\n\ry = 1\rz = 1\r\n'
1753 v, w, x, y, z = ast.parse(s).body
1754 self._check_content(s, v, 'v = 1')
1755 self._check_content(s, w, 'w = 1')
1756 self._check_content(s, x, 'x = 1')
1757 self._check_content(s, y, 'y = 1')
1758 self._check_content(s, z, 'z = 1')
1759
1760 def test_source_segment_tabs(self):
1761 s = dedent('''
1762 class C:
1763 \t\f def fun(self) -> None:
1764 \t\f pass
1765 ''').strip()
1766 s_method = ' \t\f def fun(self) -> None:\n' \
1767 ' \t\f pass'
1768
1769 cdef = ast.parse(s).body[0]
1770 self.assertEqual(ast.get_source_segment(s, cdef.body[0], padded=True), s_method)
1771
1772
Serhiy Storchakac3ea41e2019-08-26 10:13:19 +03001773class NodeVisitorTests(unittest.TestCase):
1774 def test_old_constant_nodes(self):
1775 class Visitor(ast.NodeVisitor):
1776 def visit_Num(self, node):
1777 log.append((node.lineno, 'Num', node.n))
1778 def visit_Str(self, node):
1779 log.append((node.lineno, 'Str', node.s))
1780 def visit_Bytes(self, node):
1781 log.append((node.lineno, 'Bytes', node.s))
1782 def visit_NameConstant(self, node):
1783 log.append((node.lineno, 'NameConstant', node.value))
1784 def visit_Ellipsis(self, node):
1785 log.append((node.lineno, 'Ellipsis', ...))
1786 mod = ast.parse(dedent('''\
1787 i = 42
1788 f = 4.25
1789 c = 4.25j
1790 s = 'string'
1791 b = b'bytes'
1792 t = True
1793 n = None
1794 e = ...
1795 '''))
1796 visitor = Visitor()
1797 log = []
1798 with warnings.catch_warnings(record=True) as wlog:
1799 warnings.filterwarnings('always', '', DeprecationWarning)
1800 visitor.visit(mod)
1801 self.assertEqual(log, [
1802 (1, 'Num', 42),
1803 (2, 'Num', 4.25),
1804 (3, 'Num', 4.25j),
1805 (4, 'Str', 'string'),
1806 (5, 'Bytes', b'bytes'),
1807 (6, 'NameConstant', True),
1808 (7, 'NameConstant', None),
1809 (8, 'Ellipsis', ...),
1810 ])
1811 self.assertEqual([str(w.message) for w in wlog], [
1812 'visit_Num is deprecated; add visit_Constant',
1813 'visit_Num is deprecated; add visit_Constant',
1814 'visit_Num is deprecated; add visit_Constant',
1815 'visit_Str is deprecated; add visit_Constant',
1816 'visit_Bytes is deprecated; add visit_Constant',
1817 'visit_NameConstant is deprecated; add visit_Constant',
1818 'visit_NameConstant is deprecated; add visit_Constant',
1819 'visit_Ellipsis is deprecated; add visit_Constant',
1820 ])
1821
1822
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001823def main():
1824 if __name__ != '__main__':
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001825 return
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001826 if sys.argv[1:] == ['-g']:
1827 for statements, kind in ((exec_tests, "exec"), (single_tests, "single"),
1828 (eval_tests, "eval")):
1829 print(kind+"_results = [")
Victor Stinnerf0891962016-02-08 17:15:21 +01001830 for statement in statements:
1831 tree = ast.parse(statement, "?", kind)
1832 print("%r," % (to_tuple(tree),))
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001833 print("]")
1834 print("main()")
1835 raise SystemExit
Brett Cannon3e9a9ae2013-06-12 21:25:59 -04001836 unittest.main()
Tim Peters400cbc32006-02-28 18:44:41 +00001837
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001838#### EVERYTHING BELOW IS GENERATED BY python Lib/test/test_ast.py -g #####
Tim Peters400cbc32006-02-28 18:44:41 +00001839exec_results = [
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001840('Module', [('Expr', (1, 0), ('Constant', (1, 0), None, None))], []),
1841('Module', [('Expr', (1, 0), ('Constant', (1, 0), 'module docstring', None))], []),
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001842('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (1, 9))], [], None, None)], []),
1843('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], [], None, [], [], None, []), [('Expr', (1, 9), ('Constant', (1, 9), 'function docstring', None))], [], None, None)], []),
Pablo Galindocd6e83b2019-07-15 01:32:18 +02001844('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], [('arg', (1, 6), 'a', None, None)], None, [], [], None, []), [('Pass', (1, 10))], [], None, None)], []),
1845('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], [('arg', (1, 6), 'a', None, None)], None, [], [], None, [('Constant', (1, 8), 0, None)]), [('Pass', (1, 12))], [], None, None)], []),
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001846('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], [], ('arg', (1, 7), 'args', None, None), [], [], None, []), [('Pass', (1, 14))], [], None, None)], []),
1847('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], [], None, [], [], ('arg', (1, 8), 'kwargs', None, None), []), [('Pass', (1, 17))], [], None, None)], []),
Pablo Galindocd6e83b2019-07-15 01:32:18 +02001848('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], [('arg', (1, 6), 'a', None, None), ('arg', (1, 9), 'b', None, None), ('arg', (1, 14), 'c', None, None), ('arg', (1, 22), 'd', None, None), ('arg', (1, 28), 'e', None, None)], ('arg', (1, 35), 'args', None, None), [('arg', (1, 41), 'f', None, None)], [('Constant', (1, 43), 42, None)], ('arg', (1, 49), 'kwargs', None, None), [('Constant', (1, 11), 1, None), ('Constant', (1, 16), None, None), ('List', (1, 24), [], ('Load',)), ('Dict', (1, 30), [], [])]), [('Expr', (1, 58), ('Constant', (1, 58), 'doc for f()', None))], [], None, None)], []),
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001849('Module', [('ClassDef', (1, 0), 'C', [], [], [('Pass', (1, 8))], [])], []),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001850('Module', [('ClassDef', (1, 0), 'C', [], [], [('Expr', (1, 9), ('Constant', (1, 9), 'docstring for class C', None))], [])], []),
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001851('Module', [('ClassDef', (1, 0), 'C', [('Name', (1, 8), 'object', ('Load',))], [], [('Pass', (1, 17))], [])], []),
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001852('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], [], None, [], [], None, []), [('Return', (1, 8), ('Constant', (1, 15), 1, None))], [], None, None)], []),
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001853('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])], []),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001854('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Constant', (1, 4), 1, None), None)], []),
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001855('Module', [('Assign', (1, 0), [('Tuple', (1, 0), [('Name', (1, 0), 'a', ('Store',)), ('Name', (1, 2), 'b', ('Store',))], ('Store',))], ('Name', (1, 6), 'c', ('Load',)), None)], []),
1856('Module', [('Assign', (1, 0), [('Tuple', (1, 0), [('Name', (1, 1), 'a', ('Store',)), ('Name', (1, 3), 'b', ('Store',))], ('Store',))], ('Name', (1, 8), 'c', ('Load',)), None)], []),
1857('Module', [('Assign', (1, 0), [('List', (1, 0), [('Name', (1, 1), 'a', ('Store',)), ('Name', (1, 3), 'b', ('Store',))], ('Store',))], ('Name', (1, 8), 'c', ('Load',)), None)], []),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001858('Module', [('AugAssign', (1, 0), ('Name', (1, 0), 'v', ('Store',)), ('Add',), ('Constant', (1, 5), 1, None))], []),
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001859('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Pass', (1, 11))], [], None)], []),
1860('Module', [('While', (1, 0), ('Name', (1, 6), 'v', ('Load',)), [('Pass', (1, 8))], [])], []),
1861('Module', [('If', (1, 0), ('Name', (1, 3), 'v', ('Load',)), [('Pass', (1, 5))], [])], []),
Lysandros Nikolaou025a6022019-12-12 22:40:21 +01001862('Module', [('If', (1, 0), ('Name', (1, 3), 'a', ('Load',)), [('Pass', (2, 2))], [('If', (3, 0), ('Name', (3, 5), 'b', ('Load',)), [('Pass', (4, 2))], [])])], []),
Lysandros Nikolaou5936a4c2019-12-14 11:24:57 +01001863('Module', [('If', (1, 0), ('Name', (1, 3), 'a', ('Load',)), [('Pass', (2, 2))], [('If', (3, 0), ('Name', (3, 5), 'b', ('Load',)), [('Pass', (4, 2))], [('Pass', (6, 2))])])], []),
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001864('Module', [('With', (1, 0), [('withitem', ('Name', (1, 5), 'x', ('Load',)), ('Name', (1, 10), 'y', ('Store',)))], [('Pass', (1, 13))], None)], []),
1865('Module', [('With', (1, 0), [('withitem', ('Name', (1, 5), 'x', ('Load',)), ('Name', (1, 10), 'y', ('Store',))), ('withitem', ('Name', (1, 13), 'z', ('Load',)), ('Name', (1, 18), 'q', ('Store',)))], [('Pass', (1, 21))], None)], []),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001866('Module', [('Raise', (1, 0), ('Call', (1, 6), ('Name', (1, 6), 'Exception', ('Load',)), [('Constant', (1, 16), 'string', None)], []), None)], []),
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001867('Module', [('Try', (1, 0), [('Pass', (2, 2))], [('ExceptHandler', (3, 0), ('Name', (3, 7), 'Exception', ('Load',)), None, [('Pass', (4, 2))])], [], [])], []),
1868('Module', [('Try', (1, 0), [('Pass', (2, 2))], [], [], [('Pass', (4, 2))])], []),
1869('Module', [('Assert', (1, 0), ('Name', (1, 7), 'v', ('Load',)), None)], []),
1870('Module', [('Import', (1, 0), [('alias', 'sys', None)])], []),
1871('Module', [('ImportFrom', (1, 0), 'sys', [('alias', 'v', None)], 0)], []),
1872('Module', [('Global', (1, 0), ['v'])], []),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001873('Module', [('Expr', (1, 0), ('Constant', (1, 0), 1, None))], []),
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001874('Module', [('Pass', (1, 0))], []),
1875('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Break', (1, 11))], [], None)], []),
1876('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Continue', (1, 11))], [], None)], []),
1877('Module', [('For', (1, 0), ('Tuple', (1, 4), [('Name', (1, 4), 'a', ('Store',)), ('Name', (1, 6), 'b', ('Store',))], ('Store',)), ('Name', (1, 11), 'c', ('Load',)), [('Pass', (1, 14))], [], None)], []),
1878('Module', [('For', (1, 0), ('Tuple', (1, 4), [('Name', (1, 5), 'a', ('Store',)), ('Name', (1, 7), 'b', ('Store',))], ('Store',)), ('Name', (1, 13), 'c', ('Load',)), [('Pass', (1, 16))], [], None)], []),
1879('Module', [('For', (1, 0), ('List', (1, 4), [('Name', (1, 5), 'a', ('Store',)), ('Name', (1, 7), 'b', ('Store',))], ('Store',)), ('Name', (1, 13), 'c', ('Load',)), [('Pass', (1, 16))], [], None)], []),
1880('Module', [('Expr', (1, 0), ('GeneratorExp', (1, 0), ('Tuple', (2, 4), [('Name', (3, 4), 'Aa', ('Load',)), ('Name', (5, 7), 'Bb', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (8, 4), [('Name', (8, 4), 'Aa', ('Store',)), ('Name', (10, 4), 'Bb', ('Store',))], ('Store',)), ('Name', (10, 10), 'Cc', ('Load',)), [], 0)]))], []),
1881('Module', [('Expr', (1, 0), ('DictComp', (1, 0), ('Name', (1, 1), 'a', ('Load',)), ('Name', (1, 5), 'b', ('Load',)), [('comprehension', ('Name', (1, 11), 'w', ('Store',)), ('Name', (1, 16), 'x', ('Load',)), [], 0), ('comprehension', ('Name', (1, 22), 'm', ('Store',)), ('Name', (1, 27), 'p', ('Load',)), [('Name', (1, 32), 'g', ('Load',))], 0)]))], []),
1882('Module', [('Expr', (1, 0), ('DictComp', (1, 0), ('Name', (1, 1), 'a', ('Load',)), ('Name', (1, 5), 'b', ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'v', ('Store',)), ('Name', (1, 13), 'w', ('Store',))], ('Store',)), ('Name', (1, 18), 'x', ('Load',)), [], 0)]))], []),
1883('Module', [('Expr', (1, 0), ('SetComp', (1, 0), ('Name', (1, 1), 'r', ('Load',)), [('comprehension', ('Name', (1, 7), 'l', ('Store',)), ('Name', (1, 12), 'x', ('Load',)), [('Name', (1, 17), 'g', ('Load',))], 0)]))], []),
1884('Module', [('Expr', (1, 0), ('SetComp', (1, 0), ('Name', (1, 1), 'r', ('Load',)), [('comprehension', ('Tuple', (1, 7), [('Name', (1, 7), 'l', ('Store',)), ('Name', (1, 9), 'm', ('Store',))], ('Store',)), ('Name', (1, 14), 'x', ('Load',)), [], 0)]))], []),
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001885('Module', [('AsyncFunctionDef', (1, 0), 'f', ('arguments', [], [], None, [], [], None, []), [('Expr', (2, 1), ('Constant', (2, 1), 'async function', None)), ('Expr', (3, 1), ('Await', (3, 1), ('Call', (3, 7), ('Name', (3, 7), 'something', ('Load',)), [], [])))], [], None, None)], []),
1886('Module', [('AsyncFunctionDef', (1, 0), 'f', ('arguments', [], [], None, [], [], None, []), [('AsyncFor', (2, 1), ('Name', (2, 11), 'e', ('Store',)), ('Name', (2, 16), 'i', ('Load',)), [('Expr', (2, 19), ('Constant', (2, 19), 1, None))], [('Expr', (3, 7), ('Constant', (3, 7), 2, None))], None)], [], None, None)], []),
1887('Module', [('AsyncFunctionDef', (1, 0), 'f', ('arguments', [], [], None, [], [], None, []), [('AsyncWith', (2, 1), [('withitem', ('Name', (2, 12), 'a', ('Load',)), ('Name', (2, 17), 'b', ('Store',)))], [('Expr', (2, 20), ('Constant', (2, 20), 1, None))], None)], [], None, None)], []),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001888('Module', [('Expr', (1, 0), ('Dict', (1, 0), [None, ('Constant', (1, 10), 2, None)], [('Dict', (1, 3), [('Constant', (1, 4), 1, None)], [('Constant', (1, 6), 2, None)]), ('Constant', (1, 12), 3, None)]))], []),
1889('Module', [('Expr', (1, 0), ('Set', (1, 0), [('Starred', (1, 1), ('Set', (1, 2), [('Constant', (1, 3), 1, None), ('Constant', (1, 6), 2, None)]), ('Load',)), ('Constant', (1, 10), 3, None)]))], []),
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001890('Module', [('AsyncFunctionDef', (1, 0), 'f', ('arguments', [], [], None, [], [], None, []), [('Expr', (2, 1), ('ListComp', (2, 1), ('Name', (2, 2), 'i', ('Load',)), [('comprehension', ('Name', (2, 14), 'b', ('Store',)), ('Name', (2, 19), 'c', ('Load',)), [], 1)]))], [], None, None)], []),
Serhiy Storchaka26ae9f62019-10-26 16:46:05 +03001891('Module', [('FunctionDef', (4, 0), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (4, 9))], [('Name', (1, 1), 'deco1', ('Load',)), ('Call', (2, 1), ('Name', (2, 1), 'deco2', ('Load',)), [], []), ('Call', (3, 1), ('Name', (3, 1), 'deco3', ('Load',)), [('Constant', (3, 7), 1, None)], [])], None, None)], []),
1892('Module', [('AsyncFunctionDef', (4, 0), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (4, 15))], [('Name', (1, 1), 'deco1', ('Load',)), ('Call', (2, 1), ('Name', (2, 1), 'deco2', ('Load',)), [], []), ('Call', (3, 1), ('Name', (3, 1), 'deco3', ('Load',)), [('Constant', (3, 7), 1, None)], [])], None, None)], []),
1893('Module', [('ClassDef', (4, 0), 'C', [], [], [('Pass', (4, 9))], [('Name', (1, 1), 'deco1', ('Load',)), ('Call', (2, 1), ('Name', (2, 1), 'deco2', ('Load',)), [], []), ('Call', (3, 1), ('Name', (3, 1), 'deco3', ('Load',)), [('Constant', (3, 7), 1, None)], [])])], []),
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001894('Module', [('FunctionDef', (2, 0), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (2, 9))], [('Call', (1, 1), ('Name', (1, 1), 'deco', ('Load',)), [('GeneratorExp', (1, 5), ('Name', (1, 6), 'a', ('Load',)), [('comprehension', ('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 17), 'b', ('Load',)), [], 0)])], [])], None, None)], []),
Pablo Galindo0c9258a2019-03-18 13:51:53 +00001895('Module', [('Expr', (1, 0), ('NamedExpr', (1, 1), ('Name', (1, 1), 'a', ('Store',)), ('Constant', (1, 6), 1, None)))], []),
Pablo Galindocd6e83b2019-07-15 01:32:18 +02001896('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None, None)], [], None, [], [], None, []), [('Pass', (1, 14))], [], None, None)], []),
1897('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None, None)], [('arg', (1, 12), 'c', None, None), ('arg', (1, 15), 'd', None, None), ('arg', (1, 18), 'e', None, None)], None, [], [], None, []), [('Pass', (1, 22))], [], None, None)], []),
1898('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None, None)], [('arg', (1, 12), 'c', None, None)], None, [('arg', (1, 18), 'd', None, None), ('arg', (1, 21), 'e', None, None)], [None, None], None, []), [('Pass', (1, 25))], [], None, None)], []),
1899('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None, None)], [('arg', (1, 12), 'c', None, None)], None, [('arg', (1, 18), 'd', None, None), ('arg', (1, 21), 'e', None, None)], [None, None], ('arg', (1, 26), 'kwargs', None, None), []), [('Pass', (1, 35))], [], None, None)], []),
1900('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None, None)], [], None, [], [], None, [('Constant', (1, 8), 1, None)]), [('Pass', (1, 16))], [], None, None)], []),
1901('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None, None)], [('arg', (1, 14), 'b', None, None), ('arg', (1, 19), 'c', None, None)], None, [], [], None, [('Constant', (1, 8), 1, None), ('Constant', (1, 16), 2, None), ('Constant', (1, 21), 4, None)]), [('Pass', (1, 25))], [], None, None)], []),
1902('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None, None)], [('arg', (1, 14), 'b', None, None)], None, [('arg', (1, 22), 'c', None, None)], [('Constant', (1, 24), 4, None)], None, [('Constant', (1, 8), 1, None), ('Constant', (1, 16), 2, None)]), [('Pass', (1, 28))], [], None, None)], []),
1903('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None, None)], [('arg', (1, 14), 'b', None, None)], None, [('arg', (1, 22), 'c', None, None)], [None], None, [('Constant', (1, 8), 1, None), ('Constant', (1, 16), 2, None)]), [('Pass', (1, 26))], [], None, None)], []),
1904('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None, None)], [('arg', (1, 14), 'b', None, None)], None, [('arg', (1, 22), 'c', None, None)], [('Constant', (1, 24), 4, None)], ('arg', (1, 29), 'kwargs', None, None), [('Constant', (1, 8), 1, None), ('Constant', (1, 16), 2, None)]), [('Pass', (1, 38))], [], None, None)], []),
1905('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None, None)], [('arg', (1, 14), 'b', None, None)], None, [('arg', (1, 22), 'c', None, None)], [None], ('arg', (1, 27), 'kwargs', None, None), [('Constant', (1, 8), 1, None), ('Constant', (1, 16), 2, None)]), [('Pass', (1, 36))], [], None, None)], []),
Tim Peters400cbc32006-02-28 18:44:41 +00001906]
1907single_results = [
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001908('Interactive', [('Expr', (1, 0), ('BinOp', (1, 0), ('Constant', (1, 0), 1, None), ('Add',), ('Constant', (1, 2), 2, None)))]),
Tim Peters400cbc32006-02-28 18:44:41 +00001909]
1910eval_results = [
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001911('Expression', ('Constant', (1, 0), None, None)),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001912('Expression', ('BoolOp', (1, 0), ('And',), [('Name', (1, 0), 'a', ('Load',)), ('Name', (1, 6), 'b', ('Load',))])),
1913('Expression', ('BinOp', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Add',), ('Name', (1, 4), 'b', ('Load',)))),
1914('Expression', ('UnaryOp', (1, 0), ('Not',), ('Name', (1, 4), 'v', ('Load',)))),
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001915('Expression', ('Lambda', (1, 0), ('arguments', [], [], None, [], [], None, []), ('Constant', (1, 7), None, None))),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001916('Expression', ('Dict', (1, 0), [('Constant', (1, 2), 1, None)], [('Constant', (1, 4), 2, None)])),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001917('Expression', ('Dict', (1, 0), [], [])),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001918('Expression', ('Set', (1, 0), [('Constant', (1, 1), None, None)])),
1919('Expression', ('Dict', (1, 0), [('Constant', (2, 6), 1, None)], [('Constant', (4, 10), 2, None)])),
Serhiy Storchakab619b092018-11-27 09:40:29 +02001920('Expression', ('ListComp', (1, 0), ('Name', (1, 1), 'a', ('Load',)), [('comprehension', ('Name', (1, 7), 'b', ('Store',)), ('Name', (1, 12), 'c', ('Load',)), [('Name', (1, 17), 'd', ('Load',))], 0)])),
1921('Expression', ('GeneratorExp', (1, 0), ('Name', (1, 1), 'a', ('Load',)), [('comprehension', ('Name', (1, 7), 'b', ('Store',)), ('Name', (1, 12), 'c', ('Load',)), [('Name', (1, 17), 'd', ('Load',))], 0)])),
1922('Expression', ('ListComp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'a', ('Store',)), ('Name', (1, 13), 'b', ('Store',))], ('Store',)), ('Name', (1, 18), 'c', ('Load',)), [], 0)])),
1923('Expression', ('ListComp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [], 0)])),
1924('Expression', ('ListComp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('List', (1, 11), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [], 0)])),
1925('Expression', ('SetComp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'a', ('Store',)), ('Name', (1, 13), 'b', ('Store',))], ('Store',)), ('Name', (1, 18), 'c', ('Load',)), [], 0)])),
1926('Expression', ('SetComp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [], 0)])),
1927('Expression', ('SetComp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('List', (1, 11), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [], 0)])),
1928('Expression', ('GeneratorExp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'a', ('Store',)), ('Name', (1, 13), 'b', ('Store',))], ('Store',)), ('Name', (1, 18), 'c', ('Load',)), [], 0)])),
1929('Expression', ('GeneratorExp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [], 0)])),
1930('Expression', ('GeneratorExp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('List', (1, 11), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [], 0)])),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001931('Expression', ('Compare', (1, 0), ('Constant', (1, 0), 1, None), [('Lt',), ('Lt',)], [('Constant', (1, 4), 2, None), ('Constant', (1, 8), 3, None)])),
1932('Expression', ('Call', (1, 0), ('Name', (1, 0), 'f', ('Load',)), [('Constant', (1, 2), 1, None), ('Constant', (1, 4), 2, None), ('Starred', (1, 10), ('Name', (1, 11), 'd', ('Load',)), ('Load',))], [('keyword', 'c', ('Constant', (1, 8), 3, None)), ('keyword', None, ('Name', (1, 15), 'e', ('Load',)))])),
Serhiy Storchakab619b092018-11-27 09:40:29 +02001933('Expression', ('Call', (1, 0), ('Name', (1, 0), 'f', ('Load',)), [('GeneratorExp', (1, 1), ('Name', (1, 2), 'a', ('Load',)), [('comprehension', ('Name', (1, 8), 'a', ('Store',)), ('Name', (1, 13), 'b', ('Load',)), [], 0)])], [])),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001934('Expression', ('Constant', (1, 0), 10, None)),
1935('Expression', ('Constant', (1, 0), 'string', None)),
Benjamin Peterson7a66fc22015-02-02 10:51:20 -05001936('Expression', ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',))),
1937('Expression', ('Subscript', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Slice', ('Name', (1, 2), 'b', ('Load',)), ('Name', (1, 4), 'c', ('Load',)), None), ('Load',))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001938('Expression', ('Name', (1, 0), 'v', ('Load',))),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001939('Expression', ('List', (1, 0), [('Constant', (1, 1), 1, None), ('Constant', (1, 3), 2, None), ('Constant', (1, 5), 3, None)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001940('Expression', ('List', (1, 0), [], ('Load',))),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001941('Expression', ('Tuple', (1, 0), [('Constant', (1, 0), 1, None), ('Constant', (1, 2), 2, None), ('Constant', (1, 4), 3, None)], ('Load',))),
1942('Expression', ('Tuple', (1, 0), [('Constant', (1, 1), 1, None), ('Constant', (1, 3), 2, None), ('Constant', (1, 5), 3, None)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001943('Expression', ('Tuple', (1, 0), [], ('Load',))),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001944('Expression', ('Call', (1, 0), ('Attribute', (1, 0), ('Attribute', (1, 0), ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',)), 'c', ('Load',)), 'd', ('Load',)), [('Subscript', (1, 8), ('Attribute', (1, 8), ('Name', (1, 8), 'a', ('Load',)), 'b', ('Load',)), ('Slice', ('Constant', (1, 12), 1, None), ('Constant', (1, 14), 2, None), None), ('Load',))], [])),
Tim Peters400cbc32006-02-28 18:44:41 +00001945]
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001946main()