blob: 09e425de2c30e3b0fde8dacaffb992410b60bf9a [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
Benjamin Peterson9ed37432012-07-08 11:13:36 -07006import weakref
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00007from textwrap import dedent
Benjamin Peterson9ed37432012-07-08 11:13:36 -07008
9from test import support
Tim Peters400cbc32006-02-28 18:44:41 +000010
11def to_tuple(t):
Guido van Rossum3172c5d2007-10-16 18:12:55 +000012 if t is None or isinstance(t, (str, int, complex)):
Tim Peters400cbc32006-02-28 18:44:41 +000013 return t
14 elif isinstance(t, list):
15 return [to_tuple(e) for e in t]
16 result = [t.__class__.__name__]
Martin v. Löwis49c5da12006-03-01 22:49:05 +000017 if hasattr(t, 'lineno') and hasattr(t, 'col_offset'):
18 result.append((t.lineno, t.col_offset))
Tim Peters400cbc32006-02-28 18:44:41 +000019 if t._fields is None:
20 return tuple(result)
21 for f in t._fields:
22 result.append(to_tuple(getattr(t, f)))
23 return tuple(result)
24
Neal Norwitzee9b10a2008-03-31 05:29:39 +000025
Tim Peters400cbc32006-02-28 18:44:41 +000026# These tests are compiled through "exec"
Ezio Melotti85a86292013-08-17 16:57:41 +030027# There should be at least one test per statement
Tim Peters400cbc32006-02-28 18:44:41 +000028exec_tests = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050029 # None
30 "None",
INADA Naokicb41b272017-02-23 00:31:59 +090031 # Module docstring
32 "'module docstring'",
Tim Peters400cbc32006-02-28 18:44:41 +000033 # FunctionDef
34 "def f(): pass",
INADA Naokicb41b272017-02-23 00:31:59 +090035 # FunctionDef with docstring
36 "def f(): 'function docstring'",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050037 # FunctionDef with arg
38 "def f(a): pass",
39 # FunctionDef with arg and default value
40 "def f(a=0): pass",
41 # FunctionDef with varargs
42 "def f(*args): pass",
43 # FunctionDef with kwargs
44 "def f(**kwargs): pass",
INADA Naokicb41b272017-02-23 00:31:59 +090045 # FunctionDef with all kind of args and docstring
46 "def f(a, b=1, c=None, d=[], e={}, *args, f=42, **kwargs): 'doc for f()'",
Tim Peters400cbc32006-02-28 18:44:41 +000047 # ClassDef
48 "class C:pass",
INADA Naokicb41b272017-02-23 00:31:59 +090049 # ClassDef with docstring
50 "class C: 'docstring for class C'",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050051 # ClassDef, new style class
52 "class C(object): pass",
Tim Peters400cbc32006-02-28 18:44:41 +000053 # Return
54 "def f():return 1",
55 # Delete
56 "del v",
57 # Assign
58 "v = 1",
Serhiy Storchakab619b092018-11-27 09:40:29 +020059 "a,b = c",
60 "(a,b) = c",
61 "[a,b] = c",
Tim Peters400cbc32006-02-28 18:44:41 +000062 # AugAssign
63 "v += 1",
Tim Peters400cbc32006-02-28 18:44:41 +000064 # For
65 "for v in v:pass",
66 # While
67 "while v:pass",
68 # If
69 "if v:pass",
Benjamin Petersonaeabd5f2011-05-27 15:02:03 -050070 # With
71 "with x as y: pass",
72 "with x as y, z as q: pass",
Tim Peters400cbc32006-02-28 18:44:41 +000073 # Raise
Collin Winter828f04a2007-08-31 00:04:24 +000074 "raise Exception('string')",
Tim Peters400cbc32006-02-28 18:44:41 +000075 # TryExcept
76 "try:\n pass\nexcept Exception:\n pass",
77 # TryFinally
78 "try:\n pass\nfinally:\n pass",
79 # Assert
80 "assert v",
81 # Import
82 "import sys",
83 # ImportFrom
84 "from sys import v",
Tim Peters400cbc32006-02-28 18:44:41 +000085 # Global
86 "global v",
87 # Expr
88 "1",
89 # Pass,
90 "pass",
91 # Break
Yury Selivanovb3d53132015-09-01 16:10:49 -040092 "for v in v:break",
Tim Peters400cbc32006-02-28 18:44:41 +000093 # Continue
Yury Selivanovb3d53132015-09-01 16:10:49 -040094 "for v in v:continue",
Benjamin Peterson2e4b0e12009-09-11 22:36:20 +000095 # for statements with naked tuples (see http://bugs.python.org/issue6704)
96 "for a,b in c: pass",
Serhiy Storchakab619b092018-11-27 09:40:29 +020097 "for (a,b) in c: pass",
98 "for [a,b] in c: pass",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050099 # Multiline generator expression (test for .lineno & .col_offset)
100 """(
101 (
102 Aa
103 ,
104 Bb
105 )
106 for
107 Aa
108 ,
109 Bb in Cc
110 )""",
111 # dictcomp
112 "{a : b for w in x for m in p if g}",
113 # dictcomp with naked tuple
114 "{a : b for v,w in x}",
115 # setcomp
116 "{r for l in x if g}",
117 # setcomp with naked tuple
118 "{r for l,m in x}",
Yury Selivanov75445082015-05-11 22:57:16 -0400119 # AsyncFunctionDef
INADA Naokicb41b272017-02-23 00:31:59 +0900120 "async def f():\n 'async function'\n await something()",
Yury Selivanov75445082015-05-11 22:57:16 -0400121 # AsyncFor
122 "async def f():\n async for e in i: 1\n else: 2",
123 # AsyncWith
124 "async def f():\n async with a as b: 1",
Yury Selivanovb3d53132015-09-01 16:10:49 -0400125 # PEP 448: Additional Unpacking Generalizations
126 "{**{1:2}, 2:3}",
127 "{*{1, 2}, 3}",
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700128 # Asynchronous comprehensions
129 "async def f():\n [i async for b in c]",
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200130 # Decorated FunctionDef
131 "@deco1\n@deco2()\ndef f(): pass",
132 # Decorated AsyncFunctionDef
133 "@deco1\n@deco2()\nasync def f(): pass",
134 # Decorated ClassDef
135 "@deco1\n@deco2()\nclass C: pass",
Serhiy Storchakab619b092018-11-27 09:40:29 +0200136 # Decorator with generator argument
137 "@deco(a for a in b)\ndef f(): pass",
Tim Peters400cbc32006-02-28 18:44:41 +0000138]
139
140# These are compiled through "single"
141# because of overlap with "eval", it just tests what
142# can't be tested with "eval"
143single_tests = [
144 "1+2"
145]
146
147# These are compiled through "eval"
148# It should test all expressions
149eval_tests = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500150 # None
151 "None",
Tim Peters400cbc32006-02-28 18:44:41 +0000152 # BoolOp
153 "a and b",
154 # BinOp
155 "a + b",
156 # UnaryOp
157 "not v",
158 # Lambda
159 "lambda:None",
160 # Dict
161 "{ 1:2 }",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500162 # Empty dict
163 "{}",
164 # Set
165 "{None,}",
166 # Multiline dict (test for .lineno & .col_offset)
167 """{
168 1
169 :
170 2
171 }""",
Tim Peters400cbc32006-02-28 18:44:41 +0000172 # ListComp
173 "[a for b in c if d]",
174 # GeneratorExp
175 "(a for b in c if d)",
Serhiy Storchakab619b092018-11-27 09:40:29 +0200176 # Comprehensions with multiple for targets
177 "[(a,b) for a,b in c]",
178 "[(a,b) for (a,b) in c]",
179 "[(a,b) for [a,b] in c]",
180 "{(a,b) for a,b in c}",
181 "{(a,b) for (a,b) in c}",
182 "{(a,b) for [a,b] in c}",
183 "((a,b) for a,b in c)",
184 "((a,b) for (a,b) in c)",
185 "((a,b) for [a,b] in c)",
Tim Peters400cbc32006-02-28 18:44:41 +0000186 # Yield - yield expressions can't work outside a function
187 #
188 # Compare
189 "1 < 2 < 3",
190 # Call
191 "f(1,2,c=3,*d,**e)",
Serhiy Storchakab619b092018-11-27 09:40:29 +0200192 # Call with a generator argument
193 "f(a for a in b)",
Tim Peters400cbc32006-02-28 18:44:41 +0000194 # Num
Guido van Rossume2a383d2007-01-15 16:59:06 +0000195 "10",
Tim Peters400cbc32006-02-28 18:44:41 +0000196 # Str
197 "'string'",
198 # Attribute
199 "a.b",
200 # Subscript
201 "a[b:c]",
202 # Name
203 "v",
204 # List
205 "[1,2,3]",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500206 # Empty list
207 "[]",
Tim Peters400cbc32006-02-28 18:44:41 +0000208 # Tuple
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000209 "1,2,3",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500210 # Tuple
211 "(1,2,3)",
212 # Empty tuple
213 "()",
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000214 # Combination
215 "a.b.c.d(a.b[1:2])",
216
Tim Peters400cbc32006-02-28 18:44:41 +0000217]
218
219# TODO: expr_context, slice, boolop, operator, unaryop, cmpop, comprehension
220# excepthandler, arguments, keywords, alias
221
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000222class AST_Tests(unittest.TestCase):
Tim Peters400cbc32006-02-28 18:44:41 +0000223
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500224 def _assertTrueorder(self, ast_node, parent_pos):
Georg Brandl0c77a822008-06-10 16:37:50 +0000225 if not isinstance(ast_node, ast.AST) or ast_node._fields is None:
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000226 return
Georg Brandl0c77a822008-06-10 16:37:50 +0000227 if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000228 node_pos = (ast_node.lineno, ast_node.col_offset)
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200229 self.assertGreaterEqual(node_pos, parent_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000230 parent_pos = (ast_node.lineno, ast_node.col_offset)
231 for name in ast_node._fields:
232 value = getattr(ast_node, name)
233 if isinstance(value, list):
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200234 first_pos = parent_pos
235 if value and name == 'decorator_list':
236 first_pos = (value[0].lineno, value[0].col_offset)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000237 for child in value:
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200238 self._assertTrueorder(child, first_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000239 elif value is not None:
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500240 self._assertTrueorder(value, parent_pos)
Tim Peters5ddfe412006-03-01 23:02:57 +0000241
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500242 def test_AST_objects(self):
243 x = ast.AST()
244 self.assertEqual(x._fields, ())
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700245 x.foobar = 42
246 self.assertEqual(x.foobar, 42)
247 self.assertEqual(x.__dict__["foobar"], 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500248
249 with self.assertRaises(AttributeError):
250 x.vararg
251
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500252 with self.assertRaises(TypeError):
253 # "_ast.AST constructor takes 0 positional arguments"
254 ast.AST(2)
255
Benjamin Peterson9ed37432012-07-08 11:13:36 -0700256 def test_AST_garbage_collection(self):
257 class X:
258 pass
259 a = ast.AST()
260 a.x = X()
261 a.x.a = a
262 ref = weakref.ref(a.x)
263 del a
264 support.gc_collect()
265 self.assertIsNone(ref())
266
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000267 def test_snippets(self):
268 for input, output, kind in ((exec_tests, exec_results, "exec"),
269 (single_tests, single_results, "single"),
270 (eval_tests, eval_results, "eval")):
271 for i, o in zip(input, output):
Yury Selivanovb3d53132015-09-01 16:10:49 -0400272 with self.subTest(action="parsing", input=i):
273 ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST)
274 self.assertEqual(to_tuple(ast_tree), o)
275 self._assertTrueorder(ast_tree, (0, 0))
Victor Stinner15a30952016-02-08 22:45:06 +0100276 with self.subTest(action="compiling", input=i, kind=kind):
277 compile(ast_tree, "?", kind)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000278
Benjamin Peterson78565b22009-06-28 19:19:51 +0000279 def test_slice(self):
280 slc = ast.parse("x[::]").body[0].value.slice
281 self.assertIsNone(slc.upper)
282 self.assertIsNone(slc.lower)
283 self.assertIsNone(slc.step)
284
285 def test_from_import(self):
286 im = ast.parse("from . import y").body[0]
287 self.assertIsNone(im.module)
288
Benjamin Petersona4e4e352012-03-22 08:19:04 -0400289 def test_non_interned_future_from_ast(self):
290 mod = ast.parse("from __future__ import division")
291 self.assertIsInstance(mod.body[0], ast.ImportFrom)
292 mod.body[0].module = " __future__ ".strip()
293 compile(mod, "<test>", "exec")
294
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000295 def test_base_classes(self):
296 self.assertTrue(issubclass(ast.For, ast.stmt))
297 self.assertTrue(issubclass(ast.Name, ast.expr))
298 self.assertTrue(issubclass(ast.stmt, ast.AST))
299 self.assertTrue(issubclass(ast.expr, ast.AST))
300 self.assertTrue(issubclass(ast.comprehension, ast.AST))
301 self.assertTrue(issubclass(ast.Gt, ast.AST))
302
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500303 def test_field_attr_existence(self):
304 for name, item in ast.__dict__.items():
305 if isinstance(item, type) and name != 'AST' and name[0].isupper():
306 x = item()
307 if isinstance(x, ast.AST):
308 self.assertEqual(type(x._fields), tuple)
309
310 def test_arguments(self):
311 x = ast.arguments()
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500312 self.assertEqual(x._fields, ('args', 'vararg', 'kwonlyargs',
313 'kw_defaults', 'kwarg', 'defaults'))
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500314
315 with self.assertRaises(AttributeError):
316 x.vararg
317
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700318 x = ast.arguments(*range(1, 7))
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500319 self.assertEqual(x.vararg, 2)
320
321 def test_field_attr_writable(self):
322 x = ast.Num()
323 # We can assign to _fields
324 x._fields = 666
325 self.assertEqual(x._fields, 666)
326
327 def test_classattrs(self):
328 x = ast.Num()
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300329 self.assertEqual(x._fields, ('value',))
330
331 with self.assertRaises(AttributeError):
332 x.value
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500333
334 with self.assertRaises(AttributeError):
335 x.n
336
337 x = ast.Num(42)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300338 self.assertEqual(x.value, 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500339 self.assertEqual(x.n, 42)
340
341 with self.assertRaises(AttributeError):
342 x.lineno
343
344 with self.assertRaises(AttributeError):
345 x.foobar
346
347 x = ast.Num(lineno=2)
348 self.assertEqual(x.lineno, 2)
349
350 x = ast.Num(42, lineno=0)
351 self.assertEqual(x.lineno, 0)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300352 self.assertEqual(x._fields, ('value',))
353 self.assertEqual(x.value, 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500354 self.assertEqual(x.n, 42)
355
356 self.assertRaises(TypeError, ast.Num, 1, 2)
357 self.assertRaises(TypeError, ast.Num, 1, 2, lineno=0)
358
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300359 self.assertEqual(ast.Num(42).n, 42)
360 self.assertEqual(ast.Num(4.25).n, 4.25)
361 self.assertEqual(ast.Num(4.25j).n, 4.25j)
362 self.assertEqual(ast.Str('42').s, '42')
363 self.assertEqual(ast.Bytes(b'42').s, b'42')
364 self.assertIs(ast.NameConstant(True).value, True)
365 self.assertIs(ast.NameConstant(False).value, False)
366 self.assertIs(ast.NameConstant(None).value, None)
367
368 self.assertEqual(ast.Constant(42).value, 42)
369 self.assertEqual(ast.Constant(4.25).value, 4.25)
370 self.assertEqual(ast.Constant(4.25j).value, 4.25j)
371 self.assertEqual(ast.Constant('42').value, '42')
372 self.assertEqual(ast.Constant(b'42').value, b'42')
373 self.assertIs(ast.Constant(True).value, True)
374 self.assertIs(ast.Constant(False).value, False)
375 self.assertIs(ast.Constant(None).value, None)
376 self.assertIs(ast.Constant(...).value, ...)
377
378 def test_realtype(self):
379 self.assertEqual(type(ast.Num(42)), ast.Constant)
380 self.assertEqual(type(ast.Num(4.25)), ast.Constant)
381 self.assertEqual(type(ast.Num(4.25j)), ast.Constant)
382 self.assertEqual(type(ast.Str('42')), ast.Constant)
383 self.assertEqual(type(ast.Bytes(b'42')), ast.Constant)
384 self.assertEqual(type(ast.NameConstant(True)), ast.Constant)
385 self.assertEqual(type(ast.NameConstant(False)), ast.Constant)
386 self.assertEqual(type(ast.NameConstant(None)), ast.Constant)
387 self.assertEqual(type(ast.Ellipsis()), ast.Constant)
388
389 def test_isinstance(self):
390 self.assertTrue(isinstance(ast.Num(42), ast.Num))
391 self.assertTrue(isinstance(ast.Num(4.2), ast.Num))
392 self.assertTrue(isinstance(ast.Num(4.2j), ast.Num))
393 self.assertTrue(isinstance(ast.Str('42'), ast.Str))
394 self.assertTrue(isinstance(ast.Bytes(b'42'), ast.Bytes))
395 self.assertTrue(isinstance(ast.NameConstant(True), ast.NameConstant))
396 self.assertTrue(isinstance(ast.NameConstant(False), ast.NameConstant))
397 self.assertTrue(isinstance(ast.NameConstant(None), ast.NameConstant))
398 self.assertTrue(isinstance(ast.Ellipsis(), ast.Ellipsis))
399
400 self.assertTrue(isinstance(ast.Constant(42), ast.Num))
401 self.assertTrue(isinstance(ast.Constant(4.2), ast.Num))
402 self.assertTrue(isinstance(ast.Constant(4.2j), ast.Num))
403 self.assertTrue(isinstance(ast.Constant('42'), ast.Str))
404 self.assertTrue(isinstance(ast.Constant(b'42'), ast.Bytes))
405 self.assertTrue(isinstance(ast.Constant(True), ast.NameConstant))
406 self.assertTrue(isinstance(ast.Constant(False), ast.NameConstant))
407 self.assertTrue(isinstance(ast.Constant(None), ast.NameConstant))
408 self.assertTrue(isinstance(ast.Constant(...), ast.Ellipsis))
409
410 self.assertFalse(isinstance(ast.Str('42'), ast.Num))
411 self.assertFalse(isinstance(ast.Num(42), ast.Str))
412 self.assertFalse(isinstance(ast.Str('42'), ast.Bytes))
413 self.assertFalse(isinstance(ast.Num(42), ast.NameConstant))
414 self.assertFalse(isinstance(ast.Num(42), ast.Ellipsis))
Anthony Sottile74176222019-01-18 11:30:28 -0800415 self.assertFalse(isinstance(ast.NameConstant(True), ast.Num))
416 self.assertFalse(isinstance(ast.NameConstant(False), ast.Num))
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300417
418 self.assertFalse(isinstance(ast.Constant('42'), ast.Num))
419 self.assertFalse(isinstance(ast.Constant(42), ast.Str))
420 self.assertFalse(isinstance(ast.Constant('42'), ast.Bytes))
421 self.assertFalse(isinstance(ast.Constant(42), ast.NameConstant))
422 self.assertFalse(isinstance(ast.Constant(42), ast.Ellipsis))
Anthony Sottile74176222019-01-18 11:30:28 -0800423 self.assertFalse(isinstance(ast.Constant(True), ast.Num))
424 self.assertFalse(isinstance(ast.Constant(False), ast.Num))
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300425
426 self.assertFalse(isinstance(ast.Constant(), ast.Num))
427 self.assertFalse(isinstance(ast.Constant(), ast.Str))
428 self.assertFalse(isinstance(ast.Constant(), ast.Bytes))
429 self.assertFalse(isinstance(ast.Constant(), ast.NameConstant))
430 self.assertFalse(isinstance(ast.Constant(), ast.Ellipsis))
431
Serhiy Storchaka6015cc52018-10-28 13:43:03 +0200432 class S(str): pass
433 self.assertTrue(isinstance(ast.Constant(S('42')), ast.Str))
434 self.assertFalse(isinstance(ast.Constant(S('42')), ast.Num))
435
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300436 def test_subclasses(self):
437 class N(ast.Num):
438 def __init__(self, *args, **kwargs):
439 super().__init__(*args, **kwargs)
440 self.z = 'spam'
441 class N2(ast.Num):
442 pass
443
444 n = N(42)
445 self.assertEqual(n.n, 42)
446 self.assertEqual(n.z, 'spam')
447 self.assertEqual(type(n), N)
448 self.assertTrue(isinstance(n, N))
449 self.assertTrue(isinstance(n, ast.Num))
450 self.assertFalse(isinstance(n, N2))
451 self.assertFalse(isinstance(ast.Num(42), N))
452 n = N(n=42)
453 self.assertEqual(n.n, 42)
454 self.assertEqual(type(n), N)
455
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500456 def test_module(self):
457 body = [ast.Num(42)]
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300458 x = ast.Module(body)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500459 self.assertEqual(x.body, body)
460
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000461 def test_nodeclasses(self):
Florent Xicluna992d9e02011-11-11 19:35:42 +0100462 # Zero arguments constructor explicitly allowed
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500463 x = ast.BinOp()
464 self.assertEqual(x._fields, ('left', 'op', 'right'))
465
466 # Random attribute allowed too
467 x.foobarbaz = 5
468 self.assertEqual(x.foobarbaz, 5)
469
470 n1 = ast.Num(1)
471 n3 = ast.Num(3)
472 addop = ast.Add()
473 x = ast.BinOp(n1, addop, n3)
474 self.assertEqual(x.left, n1)
475 self.assertEqual(x.op, addop)
476 self.assertEqual(x.right, n3)
Benjamin Peterson68b543a2011-06-27 17:51:18 -0500477
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500478 x = ast.BinOp(1, 2, 3)
479 self.assertEqual(x.left, 1)
480 self.assertEqual(x.op, 2)
481 self.assertEqual(x.right, 3)
482
Georg Brandl0c77a822008-06-10 16:37:50 +0000483 x = ast.BinOp(1, 2, 3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000484 self.assertEqual(x.left, 1)
485 self.assertEqual(x.op, 2)
486 self.assertEqual(x.right, 3)
487 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000488
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500489 # node raises exception when given too many arguments
490 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500491 # node raises exception when given too many arguments
492 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4, lineno=0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000493
494 # can set attributes through kwargs too
Georg Brandl0c77a822008-06-10 16:37:50 +0000495 x = ast.BinOp(left=1, op=2, right=3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000496 self.assertEqual(x.left, 1)
497 self.assertEqual(x.op, 2)
498 self.assertEqual(x.right, 3)
499 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000500
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500501 # Random kwargs also allowed
502 x = ast.BinOp(1, 2, 3, foobarbaz=42)
503 self.assertEqual(x.foobarbaz, 42)
504
505 def test_no_fields(self):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000506 # this used to fail because Sub._fields was None
Georg Brandl0c77a822008-06-10 16:37:50 +0000507 x = ast.Sub()
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500508 self.assertEqual(x._fields, ())
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000509
510 def test_pickling(self):
511 import pickle
512 mods = [pickle]
513 try:
514 import cPickle
515 mods.append(cPickle)
516 except ImportError:
517 pass
518 protocols = [0, 1, 2]
519 for mod in mods:
520 for protocol in protocols:
521 for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests):
522 ast2 = mod.loads(mod.dumps(ast, protocol))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000523 self.assertEqual(to_tuple(ast2), to_tuple(ast))
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000524
Benjamin Peterson5b066812010-11-20 01:38:49 +0000525 def test_invalid_sum(self):
526 pos = dict(lineno=2, col_offset=3)
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300527 m = ast.Module([ast.Expr(ast.expr(**pos), **pos)])
Benjamin Peterson5b066812010-11-20 01:38:49 +0000528 with self.assertRaises(TypeError) as cm:
529 compile(m, "<test>", "exec")
530 self.assertIn("but got <_ast.expr", str(cm.exception))
531
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500532 def test_invalid_identitifer(self):
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300533 m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))])
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500534 ast.fix_missing_locations(m)
535 with self.assertRaises(TypeError) as cm:
536 compile(m, "<test>", "exec")
537 self.assertIn("identifier must be of type str", str(cm.exception))
538
Mark Dickinsonded35ae2012-11-25 14:36:26 +0000539 def test_empty_yield_from(self):
540 # Issue 16546: yield from value is not optional.
541 empty_yield_from = ast.parse("def f():\n yield from g()")
542 empty_yield_from.body[0].body[0].value.value = None
543 with self.assertRaises(ValueError) as cm:
544 compile(empty_yield_from, "<test>", "exec")
545 self.assertIn("field value is required", str(cm.exception))
546
Oren Milman7dc46d82017-09-30 20:16:24 +0300547 @support.cpython_only
548 def test_issue31592(self):
549 # There shouldn't be an assertion failure in case of a bad
550 # unicodedata.normalize().
551 import unicodedata
552 def bad_normalize(*args):
553 return None
554 with support.swap_attr(unicodedata, 'normalize', bad_normalize):
555 self.assertRaises(TypeError, ast.parse, '\u03D5')
556
Georg Brandl0c77a822008-06-10 16:37:50 +0000557
558class ASTHelpers_Test(unittest.TestCase):
559
560 def test_parse(self):
561 a = ast.parse('foo(1 + 1)')
562 b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST)
563 self.assertEqual(ast.dump(a), ast.dump(b))
564
Benjamin Peterson2e2c9032012-09-02 14:23:15 -0400565 def test_parse_in_error(self):
566 try:
567 1/0
568 except Exception:
Benjamin Petersonbd0df502012-09-02 15:04:51 -0400569 with self.assertRaises(SyntaxError) as e:
570 ast.literal_eval(r"'\U'")
571 self.assertIsNotNone(e.exception.__context__)
Benjamin Peterson2e2c9032012-09-02 14:23:15 -0400572
Georg Brandl0c77a822008-06-10 16:37:50 +0000573 def test_dump(self):
574 node = ast.parse('spam(eggs, "and cheese")')
575 self.assertEqual(ast.dump(node),
576 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300577 "args=[Name(id='eggs', ctx=Load()), Constant(value='and cheese')], "
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300578 "keywords=[]))])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000579 )
580 self.assertEqual(ast.dump(node, annotate_fields=False),
581 "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300582 "Constant('and cheese')], []))])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000583 )
584 self.assertEqual(ast.dump(node, include_attributes=True),
585 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000586 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=4), "
587 "args=[Name(id='eggs', ctx=Load(), lineno=1, col_offset=5, "
588 "end_lineno=1, end_col_offset=9), Constant(value='and cheese', "
589 "lineno=1, col_offset=11, end_lineno=1, end_col_offset=23)], keywords=[], "
590 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=24), "
591 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=24)])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000592 )
593
594 def test_copy_location(self):
595 src = ast.parse('1 + 1', mode='eval')
596 src.body.right = ast.copy_location(ast.Num(2), src.body.right)
597 self.assertEqual(ast.dump(src, include_attributes=True),
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000598 'Expression(body=BinOp(left=Constant(value=1, lineno=1, col_offset=0, '
599 'end_lineno=1, end_col_offset=1), op=Add(), right=Constant(value=2, '
600 'lineno=1, col_offset=4, end_lineno=1, end_col_offset=5), lineno=1, '
601 'col_offset=0, end_lineno=1, end_col_offset=5))'
Georg Brandl0c77a822008-06-10 16:37:50 +0000602 )
603
604 def test_fix_missing_locations(self):
605 src = ast.parse('write("spam")')
606 src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()),
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400607 [ast.Str('eggs')], [])))
Georg Brandl0c77a822008-06-10 16:37:50 +0000608 self.assertEqual(src, ast.fix_missing_locations(src))
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000609 self.maxDiff = None
Georg Brandl0c77a822008-06-10 16:37:50 +0000610 self.assertEqual(ast.dump(src, include_attributes=True),
611 "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), "
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000612 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=5), "
613 "args=[Constant(value='spam', lineno=1, col_offset=6, end_lineno=1, "
614 "end_col_offset=12)], keywords=[], lineno=1, col_offset=0, end_lineno=1, "
615 "end_col_offset=13), lineno=1, col_offset=0, end_lineno=1, "
616 "end_col_offset=13), Expr(value=Call(func=Name(id='spam', ctx=Load(), "
617 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=0), "
618 "args=[Constant(value='eggs', lineno=1, col_offset=0, end_lineno=1, "
619 "end_col_offset=0)], keywords=[], lineno=1, col_offset=0, end_lineno=1, "
620 "end_col_offset=0), lineno=1, col_offset=0, end_lineno=1, end_col_offset=0)])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000621 )
622
623 def test_increment_lineno(self):
624 src = ast.parse('1 + 1', mode='eval')
625 self.assertEqual(ast.increment_lineno(src, n=3), src)
626 self.assertEqual(ast.dump(src, include_attributes=True),
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000627 'Expression(body=BinOp(left=Constant(value=1, lineno=4, col_offset=0, '
628 'end_lineno=4, end_col_offset=1), op=Add(), right=Constant(value=1, '
629 'lineno=4, col_offset=4, end_lineno=4, end_col_offset=5), lineno=4, '
630 'col_offset=0, end_lineno=4, end_col_offset=5))'
Georg Brandl0c77a822008-06-10 16:37:50 +0000631 )
Georg Brandl619e7ba2011-01-09 07:38:51 +0000632 # issue10869: do not increment lineno of root twice
Georg Brandlefb69022011-01-09 07:50:48 +0000633 src = ast.parse('1 + 1', mode='eval')
Georg Brandl619e7ba2011-01-09 07:38:51 +0000634 self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
635 self.assertEqual(ast.dump(src, include_attributes=True),
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000636 'Expression(body=BinOp(left=Constant(value=1, lineno=4, col_offset=0, '
637 'end_lineno=4, end_col_offset=1), op=Add(), right=Constant(value=1, '
638 'lineno=4, col_offset=4, end_lineno=4, end_col_offset=5), lineno=4, '
639 'col_offset=0, end_lineno=4, end_col_offset=5))'
Georg Brandl619e7ba2011-01-09 07:38:51 +0000640 )
Georg Brandl0c77a822008-06-10 16:37:50 +0000641
642 def test_iter_fields(self):
643 node = ast.parse('foo()', mode='eval')
644 d = dict(ast.iter_fields(node.body))
645 self.assertEqual(d.pop('func').id, 'foo')
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400646 self.assertEqual(d, {'keywords': [], 'args': []})
Georg Brandl0c77a822008-06-10 16:37:50 +0000647
648 def test_iter_child_nodes(self):
649 node = ast.parse("spam(23, 42, eggs='leek')", mode='eval')
650 self.assertEqual(len(list(ast.iter_child_nodes(node.body))), 4)
651 iterator = ast.iter_child_nodes(node.body)
652 self.assertEqual(next(iterator).id, 'spam')
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300653 self.assertEqual(next(iterator).value, 23)
654 self.assertEqual(next(iterator).value, 42)
Georg Brandl0c77a822008-06-10 16:37:50 +0000655 self.assertEqual(ast.dump(next(iterator)),
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300656 "keyword(arg='eggs', value=Constant(value='leek'))"
Georg Brandl0c77a822008-06-10 16:37:50 +0000657 )
658
659 def test_get_docstring(self):
Serhiy Storchaka08f127a2018-06-15 11:05:15 +0300660 node = ast.parse('"""line one\n line two"""')
661 self.assertEqual(ast.get_docstring(node),
662 'line one\nline two')
663
664 node = ast.parse('class foo:\n """line one\n line two"""')
665 self.assertEqual(ast.get_docstring(node.body[0]),
666 'line one\nline two')
667
Georg Brandl0c77a822008-06-10 16:37:50 +0000668 node = ast.parse('def foo():\n """line one\n line two"""')
669 self.assertEqual(ast.get_docstring(node.body[0]),
670 'line one\nline two')
671
Yury Selivanov2f07a662015-07-23 08:54:35 +0300672 node = ast.parse('async def foo():\n """spam\n ham"""')
673 self.assertEqual(ast.get_docstring(node.body[0]), 'spam\nham')
Serhiy Storchaka08f127a2018-06-15 11:05:15 +0300674
675 def test_get_docstring_none(self):
Matthias Bussonnier41cea702017-02-23 22:44:19 -0800676 self.assertIsNone(ast.get_docstring(ast.parse('')))
Serhiy Storchaka08f127a2018-06-15 11:05:15 +0300677 node = ast.parse('x = "not docstring"')
678 self.assertIsNone(ast.get_docstring(node))
679 node = ast.parse('def foo():\n pass')
680 self.assertIsNone(ast.get_docstring(node))
681
682 node = ast.parse('class foo:\n pass')
683 self.assertIsNone(ast.get_docstring(node.body[0]))
684 node = ast.parse('class foo:\n x = "not docstring"')
685 self.assertIsNone(ast.get_docstring(node.body[0]))
686 node = ast.parse('class foo:\n def bar(self): pass')
687 self.assertIsNone(ast.get_docstring(node.body[0]))
688
689 node = ast.parse('def foo():\n pass')
690 self.assertIsNone(ast.get_docstring(node.body[0]))
691 node = ast.parse('def foo():\n x = "not docstring"')
692 self.assertIsNone(ast.get_docstring(node.body[0]))
693
694 node = ast.parse('async def foo():\n pass')
695 self.assertIsNone(ast.get_docstring(node.body[0]))
696 node = ast.parse('async def foo():\n x = "not docstring"')
697 self.assertIsNone(ast.get_docstring(node.body[0]))
Yury Selivanov2f07a662015-07-23 08:54:35 +0300698
Anthony Sottile995d9b92019-01-12 20:05:13 -0800699 def test_multi_line_docstring_col_offset_and_lineno_issue16806(self):
700 node = ast.parse(
701 '"""line one\nline two"""\n\n'
702 'def foo():\n """line one\n line two"""\n\n'
703 ' def bar():\n """line one\n line two"""\n'
704 ' """line one\n line two"""\n'
705 '"""line one\nline two"""\n\n'
706 )
707 self.assertEqual(node.body[0].col_offset, 0)
708 self.assertEqual(node.body[0].lineno, 1)
709 self.assertEqual(node.body[1].body[0].col_offset, 2)
710 self.assertEqual(node.body[1].body[0].lineno, 5)
711 self.assertEqual(node.body[1].body[1].body[0].col_offset, 4)
712 self.assertEqual(node.body[1].body[1].body[0].lineno, 9)
713 self.assertEqual(node.body[1].body[2].col_offset, 2)
714 self.assertEqual(node.body[1].body[2].lineno, 11)
715 self.assertEqual(node.body[2].col_offset, 0)
716 self.assertEqual(node.body[2].lineno, 13)
717
Georg Brandl0c77a822008-06-10 16:37:50 +0000718 def test_literal_eval(self):
719 self.assertEqual(ast.literal_eval('[1, 2, 3]'), [1, 2, 3])
720 self.assertEqual(ast.literal_eval('{"foo": 42}'), {"foo": 42})
721 self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None))
Benjamin Peterson3e742892010-07-11 12:59:24 +0000722 self.assertEqual(ast.literal_eval('{1, 2, 3}'), {1, 2, 3})
Benjamin Peterson5ef96e52010-07-11 23:06:06 +0000723 self.assertEqual(ast.literal_eval('b"hi"'), b"hi")
Georg Brandl0c77a822008-06-10 16:37:50 +0000724 self.assertRaises(ValueError, ast.literal_eval, 'foo()')
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +0200725 self.assertEqual(ast.literal_eval('6'), 6)
726 self.assertEqual(ast.literal_eval('+6'), 6)
Raymond Hettingerbc959732010-10-08 00:47:45 +0000727 self.assertEqual(ast.literal_eval('-6'), -6)
Raymond Hettingerbc959732010-10-08 00:47:45 +0000728 self.assertEqual(ast.literal_eval('3.25'), 3.25)
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +0200729 self.assertEqual(ast.literal_eval('+3.25'), 3.25)
730 self.assertEqual(ast.literal_eval('-3.25'), -3.25)
731 self.assertEqual(repr(ast.literal_eval('-0.0')), '-0.0')
732 self.assertRaises(ValueError, ast.literal_eval, '++6')
733 self.assertRaises(ValueError, ast.literal_eval, '+True')
734 self.assertRaises(ValueError, ast.literal_eval, '2+3')
Georg Brandl0c77a822008-06-10 16:37:50 +0000735
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +0200736 def test_literal_eval_complex(self):
737 # Issue #4907
738 self.assertEqual(ast.literal_eval('6j'), 6j)
739 self.assertEqual(ast.literal_eval('-6j'), -6j)
740 self.assertEqual(ast.literal_eval('6.75j'), 6.75j)
741 self.assertEqual(ast.literal_eval('-6.75j'), -6.75j)
742 self.assertEqual(ast.literal_eval('3+6j'), 3+6j)
743 self.assertEqual(ast.literal_eval('-3+6j'), -3+6j)
744 self.assertEqual(ast.literal_eval('3-6j'), 3-6j)
745 self.assertEqual(ast.literal_eval('-3-6j'), -3-6j)
746 self.assertEqual(ast.literal_eval('3.25+6.75j'), 3.25+6.75j)
747 self.assertEqual(ast.literal_eval('-3.25+6.75j'), -3.25+6.75j)
748 self.assertEqual(ast.literal_eval('3.25-6.75j'), 3.25-6.75j)
749 self.assertEqual(ast.literal_eval('-3.25-6.75j'), -3.25-6.75j)
750 self.assertEqual(ast.literal_eval('(3+6j)'), 3+6j)
751 self.assertRaises(ValueError, ast.literal_eval, '-6j+3')
752 self.assertRaises(ValueError, ast.literal_eval, '-6j+3j')
753 self.assertRaises(ValueError, ast.literal_eval, '3+-6j')
754 self.assertRaises(ValueError, ast.literal_eval, '3+(0+6j)')
755 self.assertRaises(ValueError, ast.literal_eval, '-(3+6j)')
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000756
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100757 def test_bad_integer(self):
758 # issue13436: Bad error message with invalid numeric values
759 body = [ast.ImportFrom(module='time',
760 names=[ast.alias(name='sleep')],
761 level=None,
762 lineno=None, col_offset=None)]
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300763 mod = ast.Module(body)
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100764 with self.assertRaises(ValueError) as cm:
765 compile(mod, 'test', 'exec')
766 self.assertIn("invalid integer value: None", str(cm.exception))
767
Berker Peksag0a5bd512016-04-29 19:50:02 +0300768 def test_level_as_none(self):
769 body = [ast.ImportFrom(module='time',
770 names=[ast.alias(name='sleep')],
771 level=None,
772 lineno=0, col_offset=0)]
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300773 mod = ast.Module(body)
Berker Peksag0a5bd512016-04-29 19:50:02 +0300774 code = compile(mod, 'test', 'exec')
775 ns = {}
776 exec(code, ns)
777 self.assertIn('sleep', ns)
778
Georg Brandl0c77a822008-06-10 16:37:50 +0000779
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500780class ASTValidatorTests(unittest.TestCase):
781
782 def mod(self, mod, msg=None, mode="exec", *, exc=ValueError):
783 mod.lineno = mod.col_offset = 0
784 ast.fix_missing_locations(mod)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300785 if msg is None:
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500786 compile(mod, "<test>", mode)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300787 else:
788 with self.assertRaises(exc) as cm:
789 compile(mod, "<test>", mode)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500790 self.assertIn(msg, str(cm.exception))
791
792 def expr(self, node, msg=None, *, exc=ValueError):
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300793 mod = ast.Module([ast.Expr(node)])
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500794 self.mod(mod, msg, exc=exc)
795
796 def stmt(self, stmt, msg=None):
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300797 mod = ast.Module([stmt])
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500798 self.mod(mod, msg)
799
800 def test_module(self):
801 m = ast.Interactive([ast.Expr(ast.Name("x", ast.Store()))])
802 self.mod(m, "must have Load context", "single")
803 m = ast.Expression(ast.Name("x", ast.Store()))
804 self.mod(m, "must have Load context", "eval")
805
806 def _check_arguments(self, fac, check):
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700807 def arguments(args=None, vararg=None,
808 kwonlyargs=None, kwarg=None,
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500809 defaults=None, kw_defaults=None):
810 if args is None:
811 args = []
812 if kwonlyargs is None:
813 kwonlyargs = []
814 if defaults is None:
815 defaults = []
816 if kw_defaults is None:
817 kw_defaults = []
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700818 args = ast.arguments(args, vararg, kwonlyargs, kw_defaults,
819 kwarg, defaults)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500820 return fac(args)
821 args = [ast.arg("x", ast.Name("x", ast.Store()))]
822 check(arguments(args=args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500823 check(arguments(kwonlyargs=args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500824 check(arguments(defaults=[ast.Num(3)]),
825 "more positional defaults than args")
826 check(arguments(kw_defaults=[ast.Num(4)]),
827 "length of kwonlyargs is not the same as kw_defaults")
828 args = [ast.arg("x", ast.Name("x", ast.Load()))]
829 check(arguments(args=args, defaults=[ast.Name("x", ast.Store())]),
830 "must have Load context")
831 args = [ast.arg("a", ast.Name("x", ast.Load())),
832 ast.arg("b", ast.Name("y", ast.Load()))]
833 check(arguments(kwonlyargs=args,
834 kw_defaults=[None, ast.Name("x", ast.Store())]),
835 "must have Load context")
836
837 def test_funcdef(self):
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700838 a = ast.arguments([], None, [], [], None, [])
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300839 f = ast.FunctionDef("x", a, [], [], None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500840 self.stmt(f, "empty body on FunctionDef")
841 f = ast.FunctionDef("x", a, [ast.Pass()], [ast.Name("x", ast.Store())],
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300842 None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500843 self.stmt(f, "must have Load context")
844 f = ast.FunctionDef("x", a, [ast.Pass()], [],
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300845 ast.Name("x", ast.Store()))
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500846 self.stmt(f, "must have Load context")
847 def fac(args):
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300848 return ast.FunctionDef("x", args, [ast.Pass()], [], None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500849 self._check_arguments(fac, self.stmt)
850
851 def test_classdef(self):
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400852 def cls(bases=None, keywords=None, body=None, decorator_list=None):
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500853 if bases is None:
854 bases = []
855 if keywords is None:
856 keywords = []
857 if body is None:
858 body = [ast.Pass()]
859 if decorator_list is None:
860 decorator_list = []
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400861 return ast.ClassDef("myclass", bases, keywords,
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300862 body, decorator_list)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500863 self.stmt(cls(bases=[ast.Name("x", ast.Store())]),
864 "must have Load context")
865 self.stmt(cls(keywords=[ast.keyword("x", ast.Name("x", ast.Store()))]),
866 "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500867 self.stmt(cls(body=[]), "empty body on ClassDef")
868 self.stmt(cls(body=[None]), "None disallowed")
869 self.stmt(cls(decorator_list=[ast.Name("x", ast.Store())]),
870 "must have Load context")
871
872 def test_delete(self):
873 self.stmt(ast.Delete([]), "empty targets on Delete")
874 self.stmt(ast.Delete([None]), "None disallowed")
875 self.stmt(ast.Delete([ast.Name("x", ast.Load())]),
876 "must have Del context")
877
878 def test_assign(self):
879 self.stmt(ast.Assign([], ast.Num(3)), "empty targets on Assign")
880 self.stmt(ast.Assign([None], ast.Num(3)), "None disallowed")
881 self.stmt(ast.Assign([ast.Name("x", ast.Load())], ast.Num(3)),
882 "must have Store context")
883 self.stmt(ast.Assign([ast.Name("x", ast.Store())],
884 ast.Name("y", ast.Store())),
885 "must have Load context")
886
887 def test_augassign(self):
888 aug = ast.AugAssign(ast.Name("x", ast.Load()), ast.Add(),
889 ast.Name("y", ast.Load()))
890 self.stmt(aug, "must have Store context")
891 aug = ast.AugAssign(ast.Name("x", ast.Store()), ast.Add(),
892 ast.Name("y", ast.Store()))
893 self.stmt(aug, "must have Load context")
894
895 def test_for(self):
896 x = ast.Name("x", ast.Store())
897 y = ast.Name("y", ast.Load())
898 p = ast.Pass()
899 self.stmt(ast.For(x, y, [], []), "empty body on For")
900 self.stmt(ast.For(ast.Name("x", ast.Load()), y, [p], []),
901 "must have Store context")
902 self.stmt(ast.For(x, ast.Name("y", ast.Store()), [p], []),
903 "must have Load context")
904 e = ast.Expr(ast.Name("x", ast.Store()))
905 self.stmt(ast.For(x, y, [e], []), "must have Load context")
906 self.stmt(ast.For(x, y, [p], [e]), "must have Load context")
907
908 def test_while(self):
909 self.stmt(ast.While(ast.Num(3), [], []), "empty body on While")
910 self.stmt(ast.While(ast.Name("x", ast.Store()), [ast.Pass()], []),
911 "must have Load context")
912 self.stmt(ast.While(ast.Num(3), [ast.Pass()],
913 [ast.Expr(ast.Name("x", ast.Store()))]),
914 "must have Load context")
915
916 def test_if(self):
917 self.stmt(ast.If(ast.Num(3), [], []), "empty body on If")
918 i = ast.If(ast.Name("x", ast.Store()), [ast.Pass()], [])
919 self.stmt(i, "must have Load context")
920 i = ast.If(ast.Num(3), [ast.Expr(ast.Name("x", ast.Store()))], [])
921 self.stmt(i, "must have Load context")
922 i = ast.If(ast.Num(3), [ast.Pass()],
923 [ast.Expr(ast.Name("x", ast.Store()))])
924 self.stmt(i, "must have Load context")
925
926 def test_with(self):
927 p = ast.Pass()
928 self.stmt(ast.With([], [p]), "empty items on With")
929 i = ast.withitem(ast.Num(3), None)
930 self.stmt(ast.With([i], []), "empty body on With")
931 i = ast.withitem(ast.Name("x", ast.Store()), None)
932 self.stmt(ast.With([i], [p]), "must have Load context")
933 i = ast.withitem(ast.Num(3), ast.Name("x", ast.Load()))
934 self.stmt(ast.With([i], [p]), "must have Store context")
935
936 def test_raise(self):
937 r = ast.Raise(None, ast.Num(3))
938 self.stmt(r, "Raise with cause but no exception")
939 r = ast.Raise(ast.Name("x", ast.Store()), None)
940 self.stmt(r, "must have Load context")
941 r = ast.Raise(ast.Num(4), ast.Name("x", ast.Store()))
942 self.stmt(r, "must have Load context")
943
944 def test_try(self):
945 p = ast.Pass()
946 t = ast.Try([], [], [], [p])
947 self.stmt(t, "empty body on Try")
948 t = ast.Try([ast.Expr(ast.Name("x", ast.Store()))], [], [], [p])
949 self.stmt(t, "must have Load context")
950 t = ast.Try([p], [], [], [])
951 self.stmt(t, "Try has neither except handlers nor finalbody")
952 t = ast.Try([p], [], [p], [p])
953 self.stmt(t, "Try has orelse but no except handlers")
954 t = ast.Try([p], [ast.ExceptHandler(None, "x", [])], [], [])
955 self.stmt(t, "empty body on ExceptHandler")
956 e = [ast.ExceptHandler(ast.Name("x", ast.Store()), "y", [p])]
957 self.stmt(ast.Try([p], e, [], []), "must have Load context")
958 e = [ast.ExceptHandler(None, "x", [p])]
959 t = ast.Try([p], e, [ast.Expr(ast.Name("x", ast.Store()))], [p])
960 self.stmt(t, "must have Load context")
961 t = ast.Try([p], e, [p], [ast.Expr(ast.Name("x", ast.Store()))])
962 self.stmt(t, "must have Load context")
963
964 def test_assert(self):
965 self.stmt(ast.Assert(ast.Name("x", ast.Store()), None),
966 "must have Load context")
967 assrt = ast.Assert(ast.Name("x", ast.Load()),
968 ast.Name("y", ast.Store()))
969 self.stmt(assrt, "must have Load context")
970
971 def test_import(self):
972 self.stmt(ast.Import([]), "empty names on Import")
973
974 def test_importfrom(self):
975 imp = ast.ImportFrom(None, [ast.alias("x", None)], -42)
Serhiy Storchaka7de28402016-06-27 23:40:43 +0300976 self.stmt(imp, "Negative ImportFrom level")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500977 self.stmt(ast.ImportFrom(None, [], 0), "empty names on ImportFrom")
978
979 def test_global(self):
980 self.stmt(ast.Global([]), "empty names on Global")
981
982 def test_nonlocal(self):
983 self.stmt(ast.Nonlocal([]), "empty names on Nonlocal")
984
985 def test_expr(self):
986 e = ast.Expr(ast.Name("x", ast.Store()))
987 self.stmt(e, "must have Load context")
988
989 def test_boolop(self):
990 b = ast.BoolOp(ast.And(), [])
991 self.expr(b, "less than 2 values")
992 b = ast.BoolOp(ast.And(), [ast.Num(3)])
993 self.expr(b, "less than 2 values")
994 b = ast.BoolOp(ast.And(), [ast.Num(4), None])
995 self.expr(b, "None disallowed")
996 b = ast.BoolOp(ast.And(), [ast.Num(4), ast.Name("x", ast.Store())])
997 self.expr(b, "must have Load context")
998
999 def test_unaryop(self):
1000 u = ast.UnaryOp(ast.Not(), ast.Name("x", ast.Store()))
1001 self.expr(u, "must have Load context")
1002
1003 def test_lambda(self):
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001004 a = ast.arguments([], None, [], [], None, [])
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001005 self.expr(ast.Lambda(a, ast.Name("x", ast.Store())),
1006 "must have Load context")
1007 def fac(args):
1008 return ast.Lambda(args, ast.Name("x", ast.Load()))
1009 self._check_arguments(fac, self.expr)
1010
1011 def test_ifexp(self):
1012 l = ast.Name("x", ast.Load())
1013 s = ast.Name("y", ast.Store())
1014 for args in (s, l, l), (l, s, l), (l, l, s):
Benjamin Peterson71ce8972011-08-09 16:17:12 -05001015 self.expr(ast.IfExp(*args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001016
1017 def test_dict(self):
1018 d = ast.Dict([], [ast.Name("x", ast.Load())])
1019 self.expr(d, "same number of keys as values")
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001020 d = ast.Dict([ast.Name("x", ast.Load())], [None])
1021 self.expr(d, "None disallowed")
1022
1023 def test_set(self):
1024 self.expr(ast.Set([None]), "None disallowed")
1025 s = ast.Set([ast.Name("x", ast.Store())])
1026 self.expr(s, "must have Load context")
1027
1028 def _check_comprehension(self, fac):
1029 self.expr(fac([]), "comprehension with no generators")
1030 g = ast.comprehension(ast.Name("x", ast.Load()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001031 ast.Name("x", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001032 self.expr(fac([g]), "must have Store context")
1033 g = ast.comprehension(ast.Name("x", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001034 ast.Name("x", ast.Store()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001035 self.expr(fac([g]), "must have Load context")
1036 x = ast.Name("x", ast.Store())
1037 y = ast.Name("y", ast.Load())
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001038 g = ast.comprehension(x, y, [None], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001039 self.expr(fac([g]), "None disallowed")
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001040 g = ast.comprehension(x, y, [ast.Name("x", ast.Store())], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001041 self.expr(fac([g]), "must have Load context")
1042
1043 def _simple_comp(self, fac):
1044 g = ast.comprehension(ast.Name("x", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001045 ast.Name("x", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001046 self.expr(fac(ast.Name("x", ast.Store()), [g]),
1047 "must have Load context")
1048 def wrap(gens):
1049 return fac(ast.Name("x", ast.Store()), gens)
1050 self._check_comprehension(wrap)
1051
1052 def test_listcomp(self):
1053 self._simple_comp(ast.ListComp)
1054
1055 def test_setcomp(self):
1056 self._simple_comp(ast.SetComp)
1057
1058 def test_generatorexp(self):
1059 self._simple_comp(ast.GeneratorExp)
1060
1061 def test_dictcomp(self):
1062 g = ast.comprehension(ast.Name("y", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001063 ast.Name("p", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001064 c = ast.DictComp(ast.Name("x", ast.Store()),
1065 ast.Name("y", ast.Load()), [g])
1066 self.expr(c, "must have Load context")
1067 c = ast.DictComp(ast.Name("x", ast.Load()),
1068 ast.Name("y", ast.Store()), [g])
1069 self.expr(c, "must have Load context")
1070 def factory(comps):
1071 k = ast.Name("x", ast.Load())
1072 v = ast.Name("y", ast.Load())
1073 return ast.DictComp(k, v, comps)
1074 self._check_comprehension(factory)
1075
1076 def test_yield(self):
Benjamin Peterson527c6222012-01-14 08:58:23 -05001077 self.expr(ast.Yield(ast.Name("x", ast.Store())), "must have Load")
1078 self.expr(ast.YieldFrom(ast.Name("x", ast.Store())), "must have Load")
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001079
1080 def test_compare(self):
1081 left = ast.Name("x", ast.Load())
1082 comp = ast.Compare(left, [ast.In()], [])
1083 self.expr(comp, "no comparators")
1084 comp = ast.Compare(left, [ast.In()], [ast.Num(4), ast.Num(5)])
1085 self.expr(comp, "different number of comparators and operands")
1086 comp = ast.Compare(ast.Num("blah"), [ast.In()], [left])
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001087 self.expr(comp)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001088 comp = ast.Compare(left, [ast.In()], [ast.Num("blah")])
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001089 self.expr(comp)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001090
1091 def test_call(self):
1092 func = ast.Name("x", ast.Load())
1093 args = [ast.Name("y", ast.Load())]
1094 keywords = [ast.keyword("w", ast.Name("z", ast.Load()))]
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001095 call = ast.Call(ast.Name("x", ast.Store()), args, keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001096 self.expr(call, "must have Load context")
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001097 call = ast.Call(func, [None], keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001098 self.expr(call, "None disallowed")
1099 bad_keywords = [ast.keyword("w", ast.Name("z", ast.Store()))]
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001100 call = ast.Call(func, args, bad_keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001101 self.expr(call, "must have Load context")
1102
1103 def test_num(self):
1104 class subint(int):
1105 pass
1106 class subfloat(float):
1107 pass
1108 class subcomplex(complex):
1109 pass
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001110 for obj in "0", "hello":
1111 self.expr(ast.Num(obj))
1112 for obj in subint(), subfloat(), subcomplex():
1113 self.expr(ast.Num(obj), "invalid type", exc=TypeError)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001114
1115 def test_attribute(self):
1116 attr = ast.Attribute(ast.Name("x", ast.Store()), "y", ast.Load())
1117 self.expr(attr, "must have Load context")
1118
1119 def test_subscript(self):
1120 sub = ast.Subscript(ast.Name("x", ast.Store()), ast.Index(ast.Num(3)),
1121 ast.Load())
1122 self.expr(sub, "must have Load context")
1123 x = ast.Name("x", ast.Load())
1124 sub = ast.Subscript(x, ast.Index(ast.Name("y", ast.Store())),
1125 ast.Load())
1126 self.expr(sub, "must have Load context")
1127 s = ast.Name("x", ast.Store())
1128 for args in (s, None, None), (None, s, None), (None, None, s):
1129 sl = ast.Slice(*args)
1130 self.expr(ast.Subscript(x, sl, ast.Load()),
1131 "must have Load context")
1132 sl = ast.ExtSlice([])
1133 self.expr(ast.Subscript(x, sl, ast.Load()), "empty dims on ExtSlice")
1134 sl = ast.ExtSlice([ast.Index(s)])
1135 self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context")
1136
1137 def test_starred(self):
1138 left = ast.List([ast.Starred(ast.Name("x", ast.Load()), ast.Store())],
1139 ast.Store())
1140 assign = ast.Assign([left], ast.Num(4))
1141 self.stmt(assign, "must have Store context")
1142
1143 def _sequence(self, fac):
1144 self.expr(fac([None], ast.Load()), "None disallowed")
1145 self.expr(fac([ast.Name("x", ast.Store())], ast.Load()),
1146 "must have Load context")
1147
1148 def test_list(self):
1149 self._sequence(ast.List)
1150
1151 def test_tuple(self):
1152 self._sequence(ast.Tuple)
1153
Benjamin Peterson442f2092012-12-06 17:41:04 -05001154 def test_nameconstant(self):
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001155 self.expr(ast.NameConstant(4))
Benjamin Peterson442f2092012-12-06 17:41:04 -05001156
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001157 def test_stdlib_validates(self):
1158 stdlib = os.path.dirname(ast.__file__)
1159 tests = [fn for fn in os.listdir(stdlib) if fn.endswith(".py")]
1160 tests.extend(["test/test_grammar.py", "test/test_unpack_ex.py"])
1161 for module in tests:
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001162 with self.subTest(module):
1163 fn = os.path.join(stdlib, module)
1164 with open(fn, "r", encoding="utf-8") as fp:
1165 source = fp.read()
1166 mod = ast.parse(source, fn)
1167 compile(mod, fn, "exec")
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001168
1169
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001170class ConstantTests(unittest.TestCase):
1171 """Tests on the ast.Constant node type."""
1172
1173 def compile_constant(self, value):
1174 tree = ast.parse("x = 123")
1175
1176 node = tree.body[0].value
1177 new_node = ast.Constant(value=value)
1178 ast.copy_location(new_node, node)
1179 tree.body[0].value = new_node
1180
1181 code = compile(tree, "<string>", "exec")
1182
1183 ns = {}
1184 exec(code, ns)
1185 return ns['x']
1186
Victor Stinnerbe59d142016-01-27 00:39:12 +01001187 def test_validation(self):
1188 with self.assertRaises(TypeError) as cm:
1189 self.compile_constant([1, 2, 3])
1190 self.assertEqual(str(cm.exception),
1191 "got an invalid type in Constant: list")
1192
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001193 def test_singletons(self):
1194 for const in (None, False, True, Ellipsis, b'', frozenset()):
1195 with self.subTest(const=const):
1196 value = self.compile_constant(const)
1197 self.assertIs(value, const)
1198
1199 def test_values(self):
1200 nested_tuple = (1,)
1201 nested_frozenset = frozenset({1})
1202 for level in range(3):
1203 nested_tuple = (nested_tuple, 2)
1204 nested_frozenset = frozenset({nested_frozenset, 2})
1205 values = (123, 123.0, 123j,
1206 "unicode", b'bytes',
1207 tuple("tuple"), frozenset("frozenset"),
1208 nested_tuple, nested_frozenset)
1209 for value in values:
1210 with self.subTest(value=value):
1211 result = self.compile_constant(value)
1212 self.assertEqual(result, value)
1213
1214 def test_assign_to_constant(self):
1215 tree = ast.parse("x = 1")
1216
1217 target = tree.body[0].targets[0]
1218 new_target = ast.Constant(value=1)
1219 ast.copy_location(new_target, target)
1220 tree.body[0].targets[0] = new_target
1221
1222 with self.assertRaises(ValueError) as cm:
1223 compile(tree, "string", "exec")
1224 self.assertEqual(str(cm.exception),
1225 "expression which can't be assigned "
1226 "to in Store context")
1227
1228 def test_get_docstring(self):
1229 tree = ast.parse("'docstring'\nx = 1")
1230 self.assertEqual(ast.get_docstring(tree), 'docstring')
1231
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001232 def get_load_const(self, tree):
1233 # Compile to bytecode, disassemble and get parameter of LOAD_CONST
1234 # instructions
1235 co = compile(tree, '<string>', 'exec')
1236 consts = []
1237 for instr in dis.get_instructions(co):
1238 if instr.opname == 'LOAD_CONST':
1239 consts.append(instr.argval)
1240 return consts
1241
1242 @support.cpython_only
1243 def test_load_const(self):
1244 consts = [None,
1245 True, False,
1246 124,
1247 2.0,
1248 3j,
1249 "unicode",
1250 b'bytes',
1251 (1, 2, 3)]
1252
Victor Stinnera2724092016-02-08 18:17:58 +01001253 code = '\n'.join(['x={!r}'.format(const) for const in consts])
1254 code += '\nx = ...'
1255 consts.extend((Ellipsis, None))
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001256
1257 tree = ast.parse(code)
Victor Stinnera2724092016-02-08 18:17:58 +01001258 self.assertEqual(self.get_load_const(tree),
1259 consts)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001260
1261 # Replace expression nodes with constants
Victor Stinnera2724092016-02-08 18:17:58 +01001262 for assign, const in zip(tree.body, consts):
1263 assert isinstance(assign, ast.Assign), ast.dump(assign)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001264 new_node = ast.Constant(value=const)
Victor Stinnera2724092016-02-08 18:17:58 +01001265 ast.copy_location(new_node, assign.value)
1266 assign.value = new_node
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001267
Victor Stinnera2724092016-02-08 18:17:58 +01001268 self.assertEqual(self.get_load_const(tree),
1269 consts)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001270
1271 def test_literal_eval(self):
1272 tree = ast.parse("1 + 2")
1273 binop = tree.body[0].value
1274
1275 new_left = ast.Constant(value=10)
1276 ast.copy_location(new_left, binop.left)
1277 binop.left = new_left
1278
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +02001279 new_right = ast.Constant(value=20j)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001280 ast.copy_location(new_right, binop.right)
1281 binop.right = new_right
1282
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +02001283 self.assertEqual(ast.literal_eval(binop), 10+20j)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001284
1285
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00001286class EndPositionTests(unittest.TestCase):
1287 """Tests for end position of AST nodes.
1288
1289 Testing end positions of nodes requires a bit of extra care
1290 because of how LL parsers work.
1291 """
1292 def _check_end_pos(self, ast_node, end_lineno, end_col_offset):
1293 self.assertEqual(ast_node.end_lineno, end_lineno)
1294 self.assertEqual(ast_node.end_col_offset, end_col_offset)
1295
1296 def _check_content(self, source, ast_node, content):
1297 self.assertEqual(ast.get_source_segment(source, ast_node), content)
1298
1299 def _parse_value(self, s):
1300 # Use duck-typing to support both single expression
1301 # and a right hand side of an assignment statement.
1302 return ast.parse(s).body[0].value
1303
1304 def test_lambda(self):
1305 s = 'lambda x, *y: None'
1306 lam = self._parse_value(s)
1307 self._check_content(s, lam.body, 'None')
1308 self._check_content(s, lam.args.args[0], 'x')
1309 self._check_content(s, lam.args.vararg, 'y')
1310
1311 def test_func_def(self):
1312 s = dedent('''
1313 def func(x: int,
1314 *args: str,
1315 z: float = 0,
1316 **kwargs: Any) -> bool:
1317 return True
1318 ''').strip()
1319 fdef = ast.parse(s).body[0]
1320 self._check_end_pos(fdef, 5, 15)
1321 self._check_content(s, fdef.body[0], 'return True')
1322 self._check_content(s, fdef.args.args[0], 'x: int')
1323 self._check_content(s, fdef.args.args[0].annotation, 'int')
1324 self._check_content(s, fdef.args.kwarg, 'kwargs: Any')
1325 self._check_content(s, fdef.args.kwarg.annotation, 'Any')
1326
1327 def test_call(self):
1328 s = 'func(x, y=2, **kw)'
1329 call = self._parse_value(s)
1330 self._check_content(s, call.func, 'func')
1331 self._check_content(s, call.keywords[0].value, '2')
1332 self._check_content(s, call.keywords[1].value, 'kw')
1333
1334 def test_call_noargs(self):
1335 s = 'x[0]()'
1336 call = self._parse_value(s)
1337 self._check_content(s, call.func, 'x[0]')
1338 self._check_end_pos(call, 1, 6)
1339
1340 def test_class_def(self):
1341 s = dedent('''
1342 class C(A, B):
1343 x: int = 0
1344 ''').strip()
1345 cdef = ast.parse(s).body[0]
1346 self._check_end_pos(cdef, 2, 14)
1347 self._check_content(s, cdef.bases[1], 'B')
1348 self._check_content(s, cdef.body[0], 'x: int = 0')
1349
1350 def test_class_kw(self):
1351 s = 'class S(metaclass=abc.ABCMeta): pass'
1352 cdef = ast.parse(s).body[0]
1353 self._check_content(s, cdef.keywords[0].value, 'abc.ABCMeta')
1354
1355 def test_multi_line_str(self):
1356 s = dedent('''
1357 x = """Some multi-line text.
1358
1359 It goes on starting from same indent."""
1360 ''').strip()
1361 assign = ast.parse(s).body[0]
1362 self._check_end_pos(assign, 3, 40)
1363 self._check_end_pos(assign.value, 3, 40)
1364
1365 def test_continued_str(self):
1366 s = dedent('''
1367 x = "first part" \\
1368 "second part"
1369 ''').strip()
1370 assign = ast.parse(s).body[0]
1371 self._check_end_pos(assign, 2, 13)
1372 self._check_end_pos(assign.value, 2, 13)
1373
1374 def test_suites(self):
1375 # We intentionally put these into the same string to check
1376 # that empty lines are not part of the suite.
1377 s = dedent('''
1378 while True:
1379 pass
1380
1381 if one():
1382 x = None
1383 elif other():
1384 y = None
1385 else:
1386 z = None
1387
1388 for x, y in stuff:
1389 assert True
1390
1391 try:
1392 raise RuntimeError
1393 except TypeError as e:
1394 pass
1395
1396 pass
1397 ''').strip()
1398 mod = ast.parse(s)
1399 while_loop = mod.body[0]
1400 if_stmt = mod.body[1]
1401 for_loop = mod.body[2]
1402 try_stmt = mod.body[3]
1403 pass_stmt = mod.body[4]
1404
1405 self._check_end_pos(while_loop, 2, 8)
1406 self._check_end_pos(if_stmt, 9, 12)
1407 self._check_end_pos(for_loop, 12, 15)
1408 self._check_end_pos(try_stmt, 17, 8)
1409 self._check_end_pos(pass_stmt, 19, 4)
1410
1411 self._check_content(s, while_loop.test, 'True')
1412 self._check_content(s, if_stmt.body[0], 'x = None')
1413 self._check_content(s, if_stmt.orelse[0].test, 'other()')
1414 self._check_content(s, for_loop.target, 'x, y')
1415 self._check_content(s, try_stmt.body[0], 'raise RuntimeError')
1416 self._check_content(s, try_stmt.handlers[0].type, 'TypeError')
1417
1418 def test_fstring(self):
1419 s = 'x = f"abc {x + y} abc"'
1420 fstr = self._parse_value(s)
1421 binop = fstr.values[1].value
1422 self._check_content(s, binop, 'x + y')
1423
1424 def test_fstring_multi_line(self):
1425 s = dedent('''
1426 f"""Some multi-line text.
1427 {
1428 arg_one
1429 +
1430 arg_two
1431 }
1432 It goes on..."""
1433 ''').strip()
1434 fstr = self._parse_value(s)
1435 binop = fstr.values[1].value
1436 self._check_end_pos(binop, 5, 7)
1437 self._check_content(s, binop.left, 'arg_one')
1438 self._check_content(s, binop.right, 'arg_two')
1439
1440 def test_import_from_multi_line(self):
1441 s = dedent('''
1442 from x.y.z import (
1443 a, b, c as c
1444 )
1445 ''').strip()
1446 imp = ast.parse(s).body[0]
1447 self._check_end_pos(imp, 3, 1)
1448
1449 def test_slices(self):
1450 s1 = 'f()[1, 2] [0]'
1451 s2 = 'x[ a.b: c.d]'
1452 sm = dedent('''
1453 x[ a.b: f () ,
1454 g () : c.d
1455 ]
1456 ''').strip()
1457 i1, i2, im = map(self._parse_value, (s1, s2, sm))
1458 self._check_content(s1, i1.value, 'f()[1, 2]')
1459 self._check_content(s1, i1.value.slice.value, '1, 2')
1460 self._check_content(s2, i2.slice.lower, 'a.b')
1461 self._check_content(s2, i2.slice.upper, 'c.d')
1462 self._check_content(sm, im.slice.dims[0].upper, 'f ()')
1463 self._check_content(sm, im.slice.dims[1].lower, 'g ()')
1464 self._check_end_pos(im, 3, 3)
1465
1466 def test_binop(self):
1467 s = dedent('''
1468 (1 * 2 + (3 ) +
1469 4
1470 )
1471 ''').strip()
1472 binop = self._parse_value(s)
1473 self._check_end_pos(binop, 2, 6)
1474 self._check_content(s, binop.right, '4')
1475 self._check_content(s, binop.left, '1 * 2 + (3 )')
1476 self._check_content(s, binop.left.right, '3')
1477
1478 def test_boolop(self):
1479 s = dedent('''
1480 if (one_condition and
1481 (other_condition or yet_another_one)):
1482 pass
1483 ''').strip()
1484 bop = ast.parse(s).body[0].test
1485 self._check_end_pos(bop, 2, 44)
1486 self._check_content(s, bop.values[1],
1487 'other_condition or yet_another_one')
1488
1489 def test_tuples(self):
1490 s1 = 'x = () ;'
1491 s2 = 'x = 1 , ;'
1492 s3 = 'x = (1 , 2 ) ;'
1493 sm = dedent('''
1494 x = (
1495 a, b,
1496 )
1497 ''').strip()
1498 t1, t2, t3, tm = map(self._parse_value, (s1, s2, s3, sm))
1499 self._check_content(s1, t1, '()')
1500 self._check_content(s2, t2, '1 ,')
1501 self._check_content(s3, t3, '(1 , 2 )')
1502 self._check_end_pos(tm, 3, 1)
1503
1504 def test_attribute_spaces(self):
1505 s = 'func(x. y .z)'
1506 call = self._parse_value(s)
1507 self._check_content(s, call, s)
1508 self._check_content(s, call.args[0], 'x. y .z')
1509
1510 def test_displays(self):
1511 s1 = '[{}, {1, }, {1, 2,} ]'
1512 s2 = '{a: b, f (): g () ,}'
1513 c1 = self._parse_value(s1)
1514 c2 = self._parse_value(s2)
1515 self._check_content(s1, c1.elts[0], '{}')
1516 self._check_content(s1, c1.elts[1], '{1, }')
1517 self._check_content(s1, c1.elts[2], '{1, 2,}')
1518 self._check_content(s2, c2.keys[1], 'f ()')
1519 self._check_content(s2, c2.values[1], 'g ()')
1520
1521 def test_comprehensions(self):
1522 s = dedent('''
1523 x = [{x for x, y in stuff
1524 if cond.x} for stuff in things]
1525 ''').strip()
1526 cmp = self._parse_value(s)
1527 self._check_end_pos(cmp, 2, 37)
1528 self._check_content(s, cmp.generators[0].iter, 'things')
1529 self._check_content(s, cmp.elt.generators[0].iter, 'stuff')
1530 self._check_content(s, cmp.elt.generators[0].ifs[0], 'cond.x')
1531 self._check_content(s, cmp.elt.generators[0].target, 'x, y')
1532
1533 def test_yield_await(self):
1534 s = dedent('''
1535 async def f():
1536 yield x
1537 await y
1538 ''').strip()
1539 fdef = ast.parse(s).body[0]
1540 self._check_content(s, fdef.body[0].value, 'yield x')
1541 self._check_content(s, fdef.body[1].value, 'await y')
1542
1543 def test_source_segment_multi(self):
1544 s_orig = dedent('''
1545 x = (
1546 a, b,
1547 ) + ()
1548 ''').strip()
1549 s_tuple = dedent('''
1550 (
1551 a, b,
1552 )
1553 ''').strip()
1554 binop = self._parse_value(s_orig)
1555 self.assertEqual(ast.get_source_segment(s_orig, binop.left), s_tuple)
1556
1557 def test_source_segment_padded(self):
1558 s_orig = dedent('''
1559 class C:
1560 def fun(self) -> None:
1561 "ЖЖЖЖЖ"
1562 ''').strip()
1563 s_method = ' def fun(self) -> None:\n' \
1564 ' "ЖЖЖЖЖ"'
1565 cdef = ast.parse(s_orig).body[0]
1566 self.assertEqual(ast.get_source_segment(s_orig, cdef.body[0], padded=True),
1567 s_method)
1568
1569 def test_source_segment_endings(self):
1570 s = 'v = 1\r\nw = 1\nx = 1\n\ry = 1\rz = 1\r\n'
1571 v, w, x, y, z = ast.parse(s).body
1572 self._check_content(s, v, 'v = 1')
1573 self._check_content(s, w, 'w = 1')
1574 self._check_content(s, x, 'x = 1')
1575 self._check_content(s, y, 'y = 1')
1576 self._check_content(s, z, 'z = 1')
1577
1578 def test_source_segment_tabs(self):
1579 s = dedent('''
1580 class C:
1581 \t\f def fun(self) -> None:
1582 \t\f pass
1583 ''').strip()
1584 s_method = ' \t\f def fun(self) -> None:\n' \
1585 ' \t\f pass'
1586
1587 cdef = ast.parse(s).body[0]
1588 self.assertEqual(ast.get_source_segment(s, cdef.body[0], padded=True), s_method)
1589
1590
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001591def main():
1592 if __name__ != '__main__':
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001593 return
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001594 if sys.argv[1:] == ['-g']:
1595 for statements, kind in ((exec_tests, "exec"), (single_tests, "single"),
1596 (eval_tests, "eval")):
1597 print(kind+"_results = [")
Victor Stinnerf0891962016-02-08 17:15:21 +01001598 for statement in statements:
1599 tree = ast.parse(statement, "?", kind)
1600 print("%r," % (to_tuple(tree),))
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001601 print("]")
1602 print("main()")
1603 raise SystemExit
Brett Cannon3e9a9ae2013-06-12 21:25:59 -04001604 unittest.main()
Tim Peters400cbc32006-02-28 18:44:41 +00001605
1606#### EVERYTHING BELOW IS GENERATED #####
1607exec_results = [
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001608('Module', [('Expr', (1, 0), ('Constant', (1, 0), None))]),
1609('Module', [('Expr', (1, 0), ('Constant', (1, 0), 'module docstring'))]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001610('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [('Pass', (1, 9))], [], None)]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001611('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [('Expr', (1, 9), ('Constant', (1, 9), 'function docstring'))], [], None)]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001612('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None)], None, [], [], None, []), [('Pass', (1, 10))], [], None)]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001613('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None)], None, [], [], None, [('Constant', (1, 8), 0)]), [('Pass', (1, 12))], [], None)]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001614('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], ('arg', (1, 7), 'args', None), [], [], None, []), [('Pass', (1, 14))], [], None)]),
1615('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], ('arg', (1, 8), 'kwargs', None), []), [('Pass', (1, 17))], [], None)]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001616('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None), ('arg', (1, 9), 'b', None), ('arg', (1, 14), 'c', None), ('arg', (1, 22), 'd', None), ('arg', (1, 28), 'e', None)], ('arg', (1, 35), 'args', None), [('arg', (1, 41), 'f', None)], [('Constant', (1, 43), 42)], ('arg', (1, 49), 'kwargs', None), [('Constant', (1, 11), 1), ('Constant', (1, 16), None), ('List', (1, 24), [], ('Load',)), ('Dict', (1, 30), [], [])]), [('Expr', (1, 58), ('Constant', (1, 58), 'doc for f()'))], [], None)]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001617('Module', [('ClassDef', (1, 0), 'C', [], [], [('Pass', (1, 8))], [])]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001618('Module', [('ClassDef', (1, 0), 'C', [], [], [('Expr', (1, 9), ('Constant', (1, 9), 'docstring for class C'))], [])]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001619('Module', [('ClassDef', (1, 0), 'C', [('Name', (1, 8), 'object', ('Load',))], [], [('Pass', (1, 17))], [])]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001620('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [('Return', (1, 8), ('Constant', (1, 15), 1))], [], None)]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001621('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001622('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Constant', (1, 4), 1))]),
Serhiy Storchakab619b092018-11-27 09:40:29 +02001623('Module', [('Assign', (1, 0), [('Tuple', (1, 0), [('Name', (1, 0), 'a', ('Store',)), ('Name', (1, 2), 'b', ('Store',))], ('Store',))], ('Name', (1, 6), 'c', ('Load',)))]),
1624('Module', [('Assign', (1, 0), [('Tuple', (1, 0), [('Name', (1, 1), 'a', ('Store',)), ('Name', (1, 3), 'b', ('Store',))], ('Store',))], ('Name', (1, 8), 'c', ('Load',)))]),
1625('Module', [('Assign', (1, 0), [('List', (1, 0), [('Name', (1, 1), 'a', ('Store',)), ('Name', (1, 3), 'b', ('Store',))], ('Store',))], ('Name', (1, 8), 'c', ('Load',)))]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001626('Module', [('AugAssign', (1, 0), ('Name', (1, 0), 'v', ('Store',)), ('Add',), ('Constant', (1, 5), 1))]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001627('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Pass', (1, 11))], [])]),
1628('Module', [('While', (1, 0), ('Name', (1, 6), 'v', ('Load',)), [('Pass', (1, 8))], [])]),
1629('Module', [('If', (1, 0), ('Name', (1, 3), 'v', ('Load',)), [('Pass', (1, 5))], [])]),
1630('Module', [('With', (1, 0), [('withitem', ('Name', (1, 5), 'x', ('Load',)), ('Name', (1, 10), 'y', ('Store',)))], [('Pass', (1, 13))])]),
1631('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))])]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001632('Module', [('Raise', (1, 0), ('Call', (1, 6), ('Name', (1, 6), 'Exception', ('Load',)), [('Constant', (1, 16), 'string')], []), None)]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001633('Module', [('Try', (1, 0), [('Pass', (2, 2))], [('ExceptHandler', (3, 0), ('Name', (3, 7), 'Exception', ('Load',)), None, [('Pass', (4, 2))])], [], [])]),
1634('Module', [('Try', (1, 0), [('Pass', (2, 2))], [], [], [('Pass', (4, 2))])]),
1635('Module', [('Assert', (1, 0), ('Name', (1, 7), 'v', ('Load',)), None)]),
1636('Module', [('Import', (1, 0), [('alias', 'sys', None)])]),
1637('Module', [('ImportFrom', (1, 0), 'sys', [('alias', 'v', None)], 0)]),
1638('Module', [('Global', (1, 0), ['v'])]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001639('Module', [('Expr', (1, 0), ('Constant', (1, 0), 1))]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001640('Module', [('Pass', (1, 0))]),
1641('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Break', (1, 11))], [])]),
1642('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Continue', (1, 11))], [])]),
1643('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))], [])]),
Serhiy Storchakab619b092018-11-27 09:40:29 +02001644('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))], [])]),
1645('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))], [])]),
1646('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)]))]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001647('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)]))]),
1648('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)]))]),
1649('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)]))]),
1650('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)]))]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001651('Module', [('AsyncFunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [('Expr', (2, 1), ('Constant', (2, 1), 'async function')), ('Expr', (3, 1), ('Await', (3, 1), ('Call', (3, 7), ('Name', (3, 7), 'something', ('Load',)), [], [])))], [], None)]),
1652('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))], [('Expr', (3, 7), ('Constant', (3, 7), 2))])], [], None)]),
1653('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)]),
1654('Module', [('Expr', (1, 0), ('Dict', (1, 0), [None, ('Constant', (1, 10), 2)], [('Dict', (1, 3), [('Constant', (1, 4), 1)], [('Constant', (1, 6), 2)]), ('Constant', (1, 12), 3)]))]),
1655('Module', [('Expr', (1, 0), ('Set', (1, 0), [('Starred', (1, 1), ('Set', (1, 2), [('Constant', (1, 3), 1), ('Constant', (1, 6), 2)]), ('Load',)), ('Constant', (1, 10), 3)]))]),
Serhiy Storchakab619b092018-11-27 09:40:29 +02001656('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)]),
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02001657('Module', [('FunctionDef', (3, 0), 'f', ('arguments', [], None, [], [], None, []), [('Pass', (3, 9))], [('Name', (1, 1), 'deco1', ('Load',)), ('Call', (2, 0), ('Name', (2, 1), 'deco2', ('Load',)), [], [])], None)]),
1658('Module', [('AsyncFunctionDef', (3, 0), 'f', ('arguments', [], None, [], [], None, []), [('Pass', (3, 15))], [('Name', (1, 1), 'deco1', ('Load',)), ('Call', (2, 0), ('Name', (2, 1), 'deco2', ('Load',)), [], [])], None)]),
1659('Module', [('ClassDef', (3, 0), 'C', [], [], [('Pass', (3, 9))], [('Name', (1, 1), 'deco1', ('Load',)), ('Call', (2, 0), ('Name', (2, 1), 'deco2', ('Load',)), [], [])])]),
Serhiy Storchakab619b092018-11-27 09:40:29 +02001660('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)]),
Tim Peters400cbc32006-02-28 18:44:41 +00001661]
1662single_results = [
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001663('Interactive', [('Expr', (1, 0), ('BinOp', (1, 0), ('Constant', (1, 0), 1), ('Add',), ('Constant', (1, 2), 2)))]),
Tim Peters400cbc32006-02-28 18:44:41 +00001664]
1665eval_results = [
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001666('Expression', ('Constant', (1, 0), None)),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001667('Expression', ('BoolOp', (1, 0), ('And',), [('Name', (1, 0), 'a', ('Load',)), ('Name', (1, 6), 'b', ('Load',))])),
1668('Expression', ('BinOp', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Add',), ('Name', (1, 4), 'b', ('Load',)))),
1669('Expression', ('UnaryOp', (1, 0), ('Not',), ('Name', (1, 4), 'v', ('Load',)))),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001670('Expression', ('Lambda', (1, 0), ('arguments', [], None, [], [], None, []), ('Constant', (1, 7), None))),
1671('Expression', ('Dict', (1, 0), [('Constant', (1, 2), 1)], [('Constant', (1, 4), 2)])),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001672('Expression', ('Dict', (1, 0), [], [])),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001673('Expression', ('Set', (1, 0), [('Constant', (1, 1), None)])),
1674('Expression', ('Dict', (1, 0), [('Constant', (2, 6), 1)], [('Constant', (4, 10), 2)])),
Serhiy Storchakab619b092018-11-27 09:40:29 +02001675('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)])),
1676('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)])),
1677('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)])),
1678('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)])),
1679('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)])),
1680('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)])),
1681('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)])),
1682('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)])),
1683('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)])),
1684('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)])),
1685('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)])),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001686('Expression', ('Compare', (1, 0), ('Constant', (1, 0), 1), [('Lt',), ('Lt',)], [('Constant', (1, 4), 2), ('Constant', (1, 8), 3)])),
1687('Expression', ('Call', (1, 0), ('Name', (1, 0), 'f', ('Load',)), [('Constant', (1, 2), 1), ('Constant', (1, 4), 2), ('Starred', (1, 10), ('Name', (1, 11), 'd', ('Load',)), ('Load',))], [('keyword', 'c', ('Constant', (1, 8), 3)), ('keyword', None, ('Name', (1, 15), 'e', ('Load',)))])),
Serhiy Storchakab619b092018-11-27 09:40:29 +02001688('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)])], [])),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001689('Expression', ('Constant', (1, 0), 10)),
1690('Expression', ('Constant', (1, 0), 'string')),
Benjamin Peterson7a66fc22015-02-02 10:51:20 -05001691('Expression', ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',))),
1692('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 +00001693('Expression', ('Name', (1, 0), 'v', ('Load',))),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001694('Expression', ('List', (1, 0), [('Constant', (1, 1), 1), ('Constant', (1, 3), 2), ('Constant', (1, 5), 3)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001695('Expression', ('List', (1, 0), [], ('Load',))),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001696('Expression', ('Tuple', (1, 0), [('Constant', (1, 0), 1), ('Constant', (1, 2), 2), ('Constant', (1, 4), 3)], ('Load',))),
Serhiy Storchakab619b092018-11-27 09:40:29 +02001697('Expression', ('Tuple', (1, 0), [('Constant', (1, 1), 1), ('Constant', (1, 3), 2), ('Constant', (1, 5), 3)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001698('Expression', ('Tuple', (1, 0), [], ('Load',))),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001699('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), ('Constant', (1, 14), 2), None), ('Load',))], [])),
Tim Peters400cbc32006-02-28 18:44:41 +00001700]
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001701main()