blob: 0d51b11419259d7a4c0eac11f62a205a10e8c231 [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
7
8from test import support
Tim Peters400cbc32006-02-28 18:44:41 +00009
10def to_tuple(t):
Guido van Rossum3172c5d2007-10-16 18:12:55 +000011 if t is None or isinstance(t, (str, int, complex)):
Tim Peters400cbc32006-02-28 18:44:41 +000012 return t
13 elif isinstance(t, list):
14 return [to_tuple(e) for e in t]
15 result = [t.__class__.__name__]
Martin v. Löwis49c5da12006-03-01 22:49:05 +000016 if hasattr(t, 'lineno') and hasattr(t, 'col_offset'):
17 result.append((t.lineno, t.col_offset))
Tim Peters400cbc32006-02-28 18:44:41 +000018 if t._fields is None:
19 return tuple(result)
20 for f in t._fields:
21 result.append(to_tuple(getattr(t, f)))
22 return tuple(result)
23
Neal Norwitzee9b10a2008-03-31 05:29:39 +000024
Tim Peters400cbc32006-02-28 18:44:41 +000025# These tests are compiled through "exec"
Ezio Melotti85a86292013-08-17 16:57:41 +030026# There should be at least one test per statement
Tim Peters400cbc32006-02-28 18:44:41 +000027exec_tests = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050028 # None
29 "None",
INADA Naokicb41b272017-02-23 00:31:59 +090030 # Module docstring
31 "'module docstring'",
Tim Peters400cbc32006-02-28 18:44:41 +000032 # FunctionDef
33 "def f(): pass",
INADA Naokicb41b272017-02-23 00:31:59 +090034 # FunctionDef with docstring
35 "def f(): 'function docstring'",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050036 # FunctionDef with arg
37 "def f(a): pass",
38 # FunctionDef with arg and default value
39 "def f(a=0): pass",
40 # FunctionDef with varargs
41 "def f(*args): pass",
42 # FunctionDef with kwargs
43 "def f(**kwargs): pass",
INADA Naokicb41b272017-02-23 00:31:59 +090044 # FunctionDef with all kind of args and docstring
45 "def f(a, b=1, c=None, d=[], e={}, *args, f=42, **kwargs): 'doc for f()'",
Tim Peters400cbc32006-02-28 18:44:41 +000046 # ClassDef
47 "class C:pass",
INADA Naokicb41b272017-02-23 00:31:59 +090048 # ClassDef with docstring
49 "class C: 'docstring for class C'",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050050 # ClassDef, new style class
51 "class C(object): pass",
Tim Peters400cbc32006-02-28 18:44:41 +000052 # Return
53 "def f():return 1",
54 # Delete
55 "del v",
56 # Assign
57 "v = 1",
58 # AugAssign
59 "v += 1",
Tim Peters400cbc32006-02-28 18:44:41 +000060 # For
61 "for v in v:pass",
62 # While
63 "while v:pass",
64 # If
65 "if v:pass",
Benjamin Petersonaeabd5f2011-05-27 15:02:03 -050066 # With
67 "with x as y: pass",
68 "with x as y, z as q: pass",
Tim Peters400cbc32006-02-28 18:44:41 +000069 # Raise
Collin Winter828f04a2007-08-31 00:04:24 +000070 "raise Exception('string')",
Tim Peters400cbc32006-02-28 18:44:41 +000071 # TryExcept
72 "try:\n pass\nexcept Exception:\n pass",
73 # TryFinally
74 "try:\n pass\nfinally:\n pass",
75 # Assert
76 "assert v",
77 # Import
78 "import sys",
79 # ImportFrom
80 "from sys import v",
Tim Peters400cbc32006-02-28 18:44:41 +000081 # Global
82 "global v",
83 # Expr
84 "1",
85 # Pass,
86 "pass",
87 # Break
Yury Selivanovb3d53132015-09-01 16:10:49 -040088 "for v in v:break",
Tim Peters400cbc32006-02-28 18:44:41 +000089 # Continue
Yury Selivanovb3d53132015-09-01 16:10:49 -040090 "for v in v:continue",
Benjamin Peterson2e4b0e12009-09-11 22:36:20 +000091 # for statements with naked tuples (see http://bugs.python.org/issue6704)
92 "for a,b in c: pass",
93 "[(a,b) for a,b in c]",
94 "((a,b) for a,b in c)",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050095 "((a,b) for (a,b) in c)",
96 # Multiline generator expression (test for .lineno & .col_offset)
97 """(
98 (
99 Aa
100 ,
101 Bb
102 )
103 for
104 Aa
105 ,
106 Bb in Cc
107 )""",
108 # dictcomp
109 "{a : b for w in x for m in p if g}",
110 # dictcomp with naked tuple
111 "{a : b for v,w in x}",
112 # setcomp
113 "{r for l in x if g}",
114 # setcomp with naked tuple
115 "{r for l,m in x}",
Yury Selivanov75445082015-05-11 22:57:16 -0400116 # AsyncFunctionDef
INADA Naokicb41b272017-02-23 00:31:59 +0900117 "async def f():\n 'async function'\n await something()",
Yury Selivanov75445082015-05-11 22:57:16 -0400118 # AsyncFor
119 "async def f():\n async for e in i: 1\n else: 2",
120 # AsyncWith
121 "async def f():\n async with a as b: 1",
Yury Selivanovb3d53132015-09-01 16:10:49 -0400122 # PEP 448: Additional Unpacking Generalizations
123 "{**{1:2}, 2:3}",
124 "{*{1, 2}, 3}",
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700125 # Asynchronous comprehensions
126 "async def f():\n [i async for b in c]",
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200127 # Decorated FunctionDef
128 "@deco1\n@deco2()\ndef f(): pass",
129 # Decorated AsyncFunctionDef
130 "@deco1\n@deco2()\nasync def f(): pass",
131 # Decorated ClassDef
132 "@deco1\n@deco2()\nclass C: pass",
Tim Peters400cbc32006-02-28 18:44:41 +0000133]
134
135# These are compiled through "single"
136# because of overlap with "eval", it just tests what
137# can't be tested with "eval"
138single_tests = [
139 "1+2"
140]
141
142# These are compiled through "eval"
143# It should test all expressions
144eval_tests = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500145 # None
146 "None",
Tim Peters400cbc32006-02-28 18:44:41 +0000147 # BoolOp
148 "a and b",
149 # BinOp
150 "a + b",
151 # UnaryOp
152 "not v",
153 # Lambda
154 "lambda:None",
155 # Dict
156 "{ 1:2 }",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500157 # Empty dict
158 "{}",
159 # Set
160 "{None,}",
161 # Multiline dict (test for .lineno & .col_offset)
162 """{
163 1
164 :
165 2
166 }""",
Tim Peters400cbc32006-02-28 18:44:41 +0000167 # ListComp
168 "[a for b in c if d]",
169 # GeneratorExp
170 "(a for b in c if d)",
171 # Yield - yield expressions can't work outside a function
172 #
173 # Compare
174 "1 < 2 < 3",
175 # Call
176 "f(1,2,c=3,*d,**e)",
Tim Peters400cbc32006-02-28 18:44:41 +0000177 # Num
Guido van Rossume2a383d2007-01-15 16:59:06 +0000178 "10",
Tim Peters400cbc32006-02-28 18:44:41 +0000179 # Str
180 "'string'",
181 # Attribute
182 "a.b",
183 # Subscript
184 "a[b:c]",
185 # Name
186 "v",
187 # List
188 "[1,2,3]",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500189 # Empty list
190 "[]",
Tim Peters400cbc32006-02-28 18:44:41 +0000191 # Tuple
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000192 "1,2,3",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500193 # Tuple
194 "(1,2,3)",
195 # Empty tuple
196 "()",
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000197 # Combination
198 "a.b.c.d(a.b[1:2])",
199
Tim Peters400cbc32006-02-28 18:44:41 +0000200]
201
202# TODO: expr_context, slice, boolop, operator, unaryop, cmpop, comprehension
203# excepthandler, arguments, keywords, alias
204
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000205class AST_Tests(unittest.TestCase):
Tim Peters400cbc32006-02-28 18:44:41 +0000206
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500207 def _assertTrueorder(self, ast_node, parent_pos):
Georg Brandl0c77a822008-06-10 16:37:50 +0000208 if not isinstance(ast_node, ast.AST) or ast_node._fields is None:
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000209 return
Georg Brandl0c77a822008-06-10 16:37:50 +0000210 if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000211 node_pos = (ast_node.lineno, ast_node.col_offset)
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200212 self.assertGreaterEqual(node_pos, parent_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000213 parent_pos = (ast_node.lineno, ast_node.col_offset)
214 for name in ast_node._fields:
215 value = getattr(ast_node, name)
216 if isinstance(value, list):
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200217 first_pos = parent_pos
218 if value and name == 'decorator_list':
219 first_pos = (value[0].lineno, value[0].col_offset)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000220 for child in value:
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200221 self._assertTrueorder(child, first_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000222 elif value is not None:
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500223 self._assertTrueorder(value, parent_pos)
Tim Peters5ddfe412006-03-01 23:02:57 +0000224
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500225 def test_AST_objects(self):
226 x = ast.AST()
227 self.assertEqual(x._fields, ())
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700228 x.foobar = 42
229 self.assertEqual(x.foobar, 42)
230 self.assertEqual(x.__dict__["foobar"], 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500231
232 with self.assertRaises(AttributeError):
233 x.vararg
234
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500235 with self.assertRaises(TypeError):
236 # "_ast.AST constructor takes 0 positional arguments"
237 ast.AST(2)
238
Benjamin Peterson9ed37432012-07-08 11:13:36 -0700239 def test_AST_garbage_collection(self):
240 class X:
241 pass
242 a = ast.AST()
243 a.x = X()
244 a.x.a = a
245 ref = weakref.ref(a.x)
246 del a
247 support.gc_collect()
248 self.assertIsNone(ref())
249
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000250 def test_snippets(self):
251 for input, output, kind in ((exec_tests, exec_results, "exec"),
252 (single_tests, single_results, "single"),
253 (eval_tests, eval_results, "eval")):
254 for i, o in zip(input, output):
Yury Selivanovb3d53132015-09-01 16:10:49 -0400255 with self.subTest(action="parsing", input=i):
256 ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST)
257 self.assertEqual(to_tuple(ast_tree), o)
258 self._assertTrueorder(ast_tree, (0, 0))
Victor Stinner15a30952016-02-08 22:45:06 +0100259 with self.subTest(action="compiling", input=i, kind=kind):
260 compile(ast_tree, "?", kind)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000261
Benjamin Peterson78565b22009-06-28 19:19:51 +0000262 def test_slice(self):
263 slc = ast.parse("x[::]").body[0].value.slice
264 self.assertIsNone(slc.upper)
265 self.assertIsNone(slc.lower)
266 self.assertIsNone(slc.step)
267
268 def test_from_import(self):
269 im = ast.parse("from . import y").body[0]
270 self.assertIsNone(im.module)
271
Benjamin Petersona4e4e352012-03-22 08:19:04 -0400272 def test_non_interned_future_from_ast(self):
273 mod = ast.parse("from __future__ import division")
274 self.assertIsInstance(mod.body[0], ast.ImportFrom)
275 mod.body[0].module = " __future__ ".strip()
276 compile(mod, "<test>", "exec")
277
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000278 def test_base_classes(self):
279 self.assertTrue(issubclass(ast.For, ast.stmt))
280 self.assertTrue(issubclass(ast.Name, ast.expr))
281 self.assertTrue(issubclass(ast.stmt, ast.AST))
282 self.assertTrue(issubclass(ast.expr, ast.AST))
283 self.assertTrue(issubclass(ast.comprehension, ast.AST))
284 self.assertTrue(issubclass(ast.Gt, ast.AST))
285
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500286 def test_field_attr_existence(self):
287 for name, item in ast.__dict__.items():
288 if isinstance(item, type) and name != 'AST' and name[0].isupper():
289 x = item()
290 if isinstance(x, ast.AST):
291 self.assertEqual(type(x._fields), tuple)
292
293 def test_arguments(self):
294 x = ast.arguments()
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500295 self.assertEqual(x._fields, ('args', 'vararg', 'kwonlyargs',
296 'kw_defaults', 'kwarg', 'defaults'))
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500297
298 with self.assertRaises(AttributeError):
299 x.vararg
300
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700301 x = ast.arguments(*range(1, 7))
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500302 self.assertEqual(x.vararg, 2)
303
304 def test_field_attr_writable(self):
305 x = ast.Num()
306 # We can assign to _fields
307 x._fields = 666
308 self.assertEqual(x._fields, 666)
309
310 def test_classattrs(self):
311 x = ast.Num()
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300312 self.assertEqual(x._fields, ('value',))
313
314 with self.assertRaises(AttributeError):
315 x.value
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500316
317 with self.assertRaises(AttributeError):
318 x.n
319
320 x = ast.Num(42)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300321 self.assertEqual(x.value, 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500322 self.assertEqual(x.n, 42)
323
324 with self.assertRaises(AttributeError):
325 x.lineno
326
327 with self.assertRaises(AttributeError):
328 x.foobar
329
330 x = ast.Num(lineno=2)
331 self.assertEqual(x.lineno, 2)
332
333 x = ast.Num(42, lineno=0)
334 self.assertEqual(x.lineno, 0)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300335 self.assertEqual(x._fields, ('value',))
336 self.assertEqual(x.value, 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500337 self.assertEqual(x.n, 42)
338
339 self.assertRaises(TypeError, ast.Num, 1, 2)
340 self.assertRaises(TypeError, ast.Num, 1, 2, lineno=0)
341
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300342 self.assertEqual(ast.Num(42).n, 42)
343 self.assertEqual(ast.Num(4.25).n, 4.25)
344 self.assertEqual(ast.Num(4.25j).n, 4.25j)
345 self.assertEqual(ast.Str('42').s, '42')
346 self.assertEqual(ast.Bytes(b'42').s, b'42')
347 self.assertIs(ast.NameConstant(True).value, True)
348 self.assertIs(ast.NameConstant(False).value, False)
349 self.assertIs(ast.NameConstant(None).value, None)
350
351 self.assertEqual(ast.Constant(42).value, 42)
352 self.assertEqual(ast.Constant(4.25).value, 4.25)
353 self.assertEqual(ast.Constant(4.25j).value, 4.25j)
354 self.assertEqual(ast.Constant('42').value, '42')
355 self.assertEqual(ast.Constant(b'42').value, b'42')
356 self.assertIs(ast.Constant(True).value, True)
357 self.assertIs(ast.Constant(False).value, False)
358 self.assertIs(ast.Constant(None).value, None)
359 self.assertIs(ast.Constant(...).value, ...)
360
361 def test_realtype(self):
362 self.assertEqual(type(ast.Num(42)), ast.Constant)
363 self.assertEqual(type(ast.Num(4.25)), ast.Constant)
364 self.assertEqual(type(ast.Num(4.25j)), ast.Constant)
365 self.assertEqual(type(ast.Str('42')), ast.Constant)
366 self.assertEqual(type(ast.Bytes(b'42')), ast.Constant)
367 self.assertEqual(type(ast.NameConstant(True)), ast.Constant)
368 self.assertEqual(type(ast.NameConstant(False)), ast.Constant)
369 self.assertEqual(type(ast.NameConstant(None)), ast.Constant)
370 self.assertEqual(type(ast.Ellipsis()), ast.Constant)
371
372 def test_isinstance(self):
373 self.assertTrue(isinstance(ast.Num(42), ast.Num))
374 self.assertTrue(isinstance(ast.Num(4.2), ast.Num))
375 self.assertTrue(isinstance(ast.Num(4.2j), ast.Num))
376 self.assertTrue(isinstance(ast.Str('42'), ast.Str))
377 self.assertTrue(isinstance(ast.Bytes(b'42'), ast.Bytes))
378 self.assertTrue(isinstance(ast.NameConstant(True), ast.NameConstant))
379 self.assertTrue(isinstance(ast.NameConstant(False), ast.NameConstant))
380 self.assertTrue(isinstance(ast.NameConstant(None), ast.NameConstant))
381 self.assertTrue(isinstance(ast.Ellipsis(), ast.Ellipsis))
382
383 self.assertTrue(isinstance(ast.Constant(42), ast.Num))
384 self.assertTrue(isinstance(ast.Constant(4.2), ast.Num))
385 self.assertTrue(isinstance(ast.Constant(4.2j), ast.Num))
386 self.assertTrue(isinstance(ast.Constant('42'), ast.Str))
387 self.assertTrue(isinstance(ast.Constant(b'42'), ast.Bytes))
388 self.assertTrue(isinstance(ast.Constant(True), ast.NameConstant))
389 self.assertTrue(isinstance(ast.Constant(False), ast.NameConstant))
390 self.assertTrue(isinstance(ast.Constant(None), ast.NameConstant))
391 self.assertTrue(isinstance(ast.Constant(...), ast.Ellipsis))
392
393 self.assertFalse(isinstance(ast.Str('42'), ast.Num))
394 self.assertFalse(isinstance(ast.Num(42), ast.Str))
395 self.assertFalse(isinstance(ast.Str('42'), ast.Bytes))
396 self.assertFalse(isinstance(ast.Num(42), ast.NameConstant))
397 self.assertFalse(isinstance(ast.Num(42), ast.Ellipsis))
398
399 self.assertFalse(isinstance(ast.Constant('42'), ast.Num))
400 self.assertFalse(isinstance(ast.Constant(42), ast.Str))
401 self.assertFalse(isinstance(ast.Constant('42'), ast.Bytes))
402 self.assertFalse(isinstance(ast.Constant(42), ast.NameConstant))
403 self.assertFalse(isinstance(ast.Constant(42), ast.Ellipsis))
404
405 self.assertFalse(isinstance(ast.Constant(), ast.Num))
406 self.assertFalse(isinstance(ast.Constant(), ast.Str))
407 self.assertFalse(isinstance(ast.Constant(), ast.Bytes))
408 self.assertFalse(isinstance(ast.Constant(), ast.NameConstant))
409 self.assertFalse(isinstance(ast.Constant(), ast.Ellipsis))
410
Serhiy Storchaka6015cc52018-10-28 13:43:03 +0200411 class S(str): pass
412 self.assertTrue(isinstance(ast.Constant(S('42')), ast.Str))
413 self.assertFalse(isinstance(ast.Constant(S('42')), ast.Num))
414
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300415 def test_subclasses(self):
416 class N(ast.Num):
417 def __init__(self, *args, **kwargs):
418 super().__init__(*args, **kwargs)
419 self.z = 'spam'
420 class N2(ast.Num):
421 pass
422
423 n = N(42)
424 self.assertEqual(n.n, 42)
425 self.assertEqual(n.z, 'spam')
426 self.assertEqual(type(n), N)
427 self.assertTrue(isinstance(n, N))
428 self.assertTrue(isinstance(n, ast.Num))
429 self.assertFalse(isinstance(n, N2))
430 self.assertFalse(isinstance(ast.Num(42), N))
431 n = N(n=42)
432 self.assertEqual(n.n, 42)
433 self.assertEqual(type(n), N)
434
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500435 def test_module(self):
436 body = [ast.Num(42)]
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300437 x = ast.Module(body)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500438 self.assertEqual(x.body, body)
439
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000440 def test_nodeclasses(self):
Florent Xicluna992d9e02011-11-11 19:35:42 +0100441 # Zero arguments constructor explicitly allowed
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500442 x = ast.BinOp()
443 self.assertEqual(x._fields, ('left', 'op', 'right'))
444
445 # Random attribute allowed too
446 x.foobarbaz = 5
447 self.assertEqual(x.foobarbaz, 5)
448
449 n1 = ast.Num(1)
450 n3 = ast.Num(3)
451 addop = ast.Add()
452 x = ast.BinOp(n1, addop, n3)
453 self.assertEqual(x.left, n1)
454 self.assertEqual(x.op, addop)
455 self.assertEqual(x.right, n3)
Benjamin Peterson68b543a2011-06-27 17:51:18 -0500456
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500457 x = ast.BinOp(1, 2, 3)
458 self.assertEqual(x.left, 1)
459 self.assertEqual(x.op, 2)
460 self.assertEqual(x.right, 3)
461
Georg Brandl0c77a822008-06-10 16:37:50 +0000462 x = ast.BinOp(1, 2, 3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000463 self.assertEqual(x.left, 1)
464 self.assertEqual(x.op, 2)
465 self.assertEqual(x.right, 3)
466 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000467
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500468 # node raises exception when given too many arguments
469 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500470 # node raises exception when given too many arguments
471 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4, lineno=0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000472
473 # can set attributes through kwargs too
Georg Brandl0c77a822008-06-10 16:37:50 +0000474 x = ast.BinOp(left=1, op=2, right=3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000475 self.assertEqual(x.left, 1)
476 self.assertEqual(x.op, 2)
477 self.assertEqual(x.right, 3)
478 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000479
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500480 # Random kwargs also allowed
481 x = ast.BinOp(1, 2, 3, foobarbaz=42)
482 self.assertEqual(x.foobarbaz, 42)
483
484 def test_no_fields(self):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000485 # this used to fail because Sub._fields was None
Georg Brandl0c77a822008-06-10 16:37:50 +0000486 x = ast.Sub()
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500487 self.assertEqual(x._fields, ())
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000488
489 def test_pickling(self):
490 import pickle
491 mods = [pickle]
492 try:
493 import cPickle
494 mods.append(cPickle)
495 except ImportError:
496 pass
497 protocols = [0, 1, 2]
498 for mod in mods:
499 for protocol in protocols:
500 for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests):
501 ast2 = mod.loads(mod.dumps(ast, protocol))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000502 self.assertEqual(to_tuple(ast2), to_tuple(ast))
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000503
Benjamin Peterson5b066812010-11-20 01:38:49 +0000504 def test_invalid_sum(self):
505 pos = dict(lineno=2, col_offset=3)
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300506 m = ast.Module([ast.Expr(ast.expr(**pos), **pos)])
Benjamin Peterson5b066812010-11-20 01:38:49 +0000507 with self.assertRaises(TypeError) as cm:
508 compile(m, "<test>", "exec")
509 self.assertIn("but got <_ast.expr", str(cm.exception))
510
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500511 def test_invalid_identitifer(self):
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300512 m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))])
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500513 ast.fix_missing_locations(m)
514 with self.assertRaises(TypeError) as cm:
515 compile(m, "<test>", "exec")
516 self.assertIn("identifier must be of type str", str(cm.exception))
517
Mark Dickinsonded35ae2012-11-25 14:36:26 +0000518 def test_empty_yield_from(self):
519 # Issue 16546: yield from value is not optional.
520 empty_yield_from = ast.parse("def f():\n yield from g()")
521 empty_yield_from.body[0].body[0].value.value = None
522 with self.assertRaises(ValueError) as cm:
523 compile(empty_yield_from, "<test>", "exec")
524 self.assertIn("field value is required", str(cm.exception))
525
Oren Milman7dc46d82017-09-30 20:16:24 +0300526 @support.cpython_only
527 def test_issue31592(self):
528 # There shouldn't be an assertion failure in case of a bad
529 # unicodedata.normalize().
530 import unicodedata
531 def bad_normalize(*args):
532 return None
533 with support.swap_attr(unicodedata, 'normalize', bad_normalize):
534 self.assertRaises(TypeError, ast.parse, '\u03D5')
535
Georg Brandl0c77a822008-06-10 16:37:50 +0000536
537class ASTHelpers_Test(unittest.TestCase):
538
539 def test_parse(self):
540 a = ast.parse('foo(1 + 1)')
541 b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST)
542 self.assertEqual(ast.dump(a), ast.dump(b))
543
Benjamin Peterson2e2c9032012-09-02 14:23:15 -0400544 def test_parse_in_error(self):
545 try:
546 1/0
547 except Exception:
Benjamin Petersonbd0df502012-09-02 15:04:51 -0400548 with self.assertRaises(SyntaxError) as e:
549 ast.literal_eval(r"'\U'")
550 self.assertIsNotNone(e.exception.__context__)
Benjamin Peterson2e2c9032012-09-02 14:23:15 -0400551
Georg Brandl0c77a822008-06-10 16:37:50 +0000552 def test_dump(self):
553 node = ast.parse('spam(eggs, "and cheese")')
554 self.assertEqual(ast.dump(node),
555 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300556 "args=[Name(id='eggs', ctx=Load()), Constant(value='and cheese')], "
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300557 "keywords=[]))])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000558 )
559 self.assertEqual(ast.dump(node, annotate_fields=False),
560 "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300561 "Constant('and cheese')], []))])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000562 )
563 self.assertEqual(ast.dump(node, include_attributes=True),
564 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
565 "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), "
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300566 "lineno=1, col_offset=5), Constant(value='and cheese', lineno=1, "
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400567 "col_offset=11)], keywords=[], "
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300568 "lineno=1, col_offset=0), lineno=1, col_offset=0)])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000569 )
570
571 def test_copy_location(self):
572 src = ast.parse('1 + 1', mode='eval')
573 src.body.right = ast.copy_location(ast.Num(2), src.body.right)
574 self.assertEqual(ast.dump(src, include_attributes=True),
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300575 'Expression(body=BinOp(left=Constant(value=1, lineno=1, col_offset=0), '
576 'op=Add(), right=Constant(value=2, lineno=1, col_offset=4), lineno=1, '
Georg Brandl0c77a822008-06-10 16:37:50 +0000577 'col_offset=0))'
578 )
579
580 def test_fix_missing_locations(self):
581 src = ast.parse('write("spam")')
582 src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()),
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400583 [ast.Str('eggs')], [])))
Georg Brandl0c77a822008-06-10 16:37:50 +0000584 self.assertEqual(src, ast.fix_missing_locations(src))
585 self.assertEqual(ast.dump(src, include_attributes=True),
586 "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), "
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300587 "lineno=1, col_offset=0), args=[Constant(value='spam', lineno=1, "
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400588 "col_offset=6)], keywords=[], "
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500589 "lineno=1, col_offset=0), lineno=1, col_offset=0), "
Georg Brandl0c77a822008-06-10 16:37:50 +0000590 "Expr(value=Call(func=Name(id='spam', ctx=Load(), lineno=1, "
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300591 "col_offset=0), args=[Constant(value='eggs', lineno=1, col_offset=0)], "
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400592 "keywords=[], lineno=1, "
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300593 "col_offset=0), lineno=1, col_offset=0)])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000594 )
595
596 def test_increment_lineno(self):
597 src = ast.parse('1 + 1', mode='eval')
598 self.assertEqual(ast.increment_lineno(src, n=3), src)
599 self.assertEqual(ast.dump(src, include_attributes=True),
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300600 'Expression(body=BinOp(left=Constant(value=1, lineno=4, col_offset=0), '
601 'op=Add(), right=Constant(value=1, lineno=4, col_offset=4), lineno=4, '
Georg Brandl0c77a822008-06-10 16:37:50 +0000602 'col_offset=0))'
603 )
Georg Brandl619e7ba2011-01-09 07:38:51 +0000604 # issue10869: do not increment lineno of root twice
Georg Brandlefb69022011-01-09 07:50:48 +0000605 src = ast.parse('1 + 1', mode='eval')
Georg Brandl619e7ba2011-01-09 07:38:51 +0000606 self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
607 self.assertEqual(ast.dump(src, include_attributes=True),
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300608 'Expression(body=BinOp(left=Constant(value=1, lineno=4, col_offset=0), '
609 'op=Add(), right=Constant(value=1, lineno=4, col_offset=4), lineno=4, '
Georg Brandl619e7ba2011-01-09 07:38:51 +0000610 'col_offset=0))'
611 )
Georg Brandl0c77a822008-06-10 16:37:50 +0000612
613 def test_iter_fields(self):
614 node = ast.parse('foo()', mode='eval')
615 d = dict(ast.iter_fields(node.body))
616 self.assertEqual(d.pop('func').id, 'foo')
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400617 self.assertEqual(d, {'keywords': [], 'args': []})
Georg Brandl0c77a822008-06-10 16:37:50 +0000618
619 def test_iter_child_nodes(self):
620 node = ast.parse("spam(23, 42, eggs='leek')", mode='eval')
621 self.assertEqual(len(list(ast.iter_child_nodes(node.body))), 4)
622 iterator = ast.iter_child_nodes(node.body)
623 self.assertEqual(next(iterator).id, 'spam')
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300624 self.assertEqual(next(iterator).value, 23)
625 self.assertEqual(next(iterator).value, 42)
Georg Brandl0c77a822008-06-10 16:37:50 +0000626 self.assertEqual(ast.dump(next(iterator)),
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300627 "keyword(arg='eggs', value=Constant(value='leek'))"
Georg Brandl0c77a822008-06-10 16:37:50 +0000628 )
629
630 def test_get_docstring(self):
Serhiy Storchaka08f127a2018-06-15 11:05:15 +0300631 node = ast.parse('"""line one\n line two"""')
632 self.assertEqual(ast.get_docstring(node),
633 'line one\nline two')
634
635 node = ast.parse('class foo:\n """line one\n line two"""')
636 self.assertEqual(ast.get_docstring(node.body[0]),
637 'line one\nline two')
638
Georg Brandl0c77a822008-06-10 16:37:50 +0000639 node = ast.parse('def foo():\n """line one\n line two"""')
640 self.assertEqual(ast.get_docstring(node.body[0]),
641 'line one\nline two')
642
Yury Selivanov2f07a662015-07-23 08:54:35 +0300643 node = ast.parse('async def foo():\n """spam\n ham"""')
644 self.assertEqual(ast.get_docstring(node.body[0]), 'spam\nham')
Serhiy Storchaka08f127a2018-06-15 11:05:15 +0300645
646 def test_get_docstring_none(self):
Matthias Bussonnier41cea702017-02-23 22:44:19 -0800647 self.assertIsNone(ast.get_docstring(ast.parse('')))
Serhiy Storchaka08f127a2018-06-15 11:05:15 +0300648 node = ast.parse('x = "not docstring"')
649 self.assertIsNone(ast.get_docstring(node))
650 node = ast.parse('def foo():\n pass')
651 self.assertIsNone(ast.get_docstring(node))
652
653 node = ast.parse('class foo:\n pass')
654 self.assertIsNone(ast.get_docstring(node.body[0]))
655 node = ast.parse('class foo:\n x = "not docstring"')
656 self.assertIsNone(ast.get_docstring(node.body[0]))
657 node = ast.parse('class foo:\n def bar(self): pass')
658 self.assertIsNone(ast.get_docstring(node.body[0]))
659
660 node = ast.parse('def foo():\n pass')
661 self.assertIsNone(ast.get_docstring(node.body[0]))
662 node = ast.parse('def foo():\n x = "not docstring"')
663 self.assertIsNone(ast.get_docstring(node.body[0]))
664
665 node = ast.parse('async def foo():\n pass')
666 self.assertIsNone(ast.get_docstring(node.body[0]))
667 node = ast.parse('async def foo():\n x = "not docstring"')
668 self.assertIsNone(ast.get_docstring(node.body[0]))
Yury Selivanov2f07a662015-07-23 08:54:35 +0300669
Georg Brandl0c77a822008-06-10 16:37:50 +0000670 def test_literal_eval(self):
671 self.assertEqual(ast.literal_eval('[1, 2, 3]'), [1, 2, 3])
672 self.assertEqual(ast.literal_eval('{"foo": 42}'), {"foo": 42})
673 self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None))
Benjamin Peterson3e742892010-07-11 12:59:24 +0000674 self.assertEqual(ast.literal_eval('{1, 2, 3}'), {1, 2, 3})
Benjamin Peterson5ef96e52010-07-11 23:06:06 +0000675 self.assertEqual(ast.literal_eval('b"hi"'), b"hi")
Georg Brandl0c77a822008-06-10 16:37:50 +0000676 self.assertRaises(ValueError, ast.literal_eval, 'foo()')
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +0200677 self.assertEqual(ast.literal_eval('6'), 6)
678 self.assertEqual(ast.literal_eval('+6'), 6)
Raymond Hettingerbc959732010-10-08 00:47:45 +0000679 self.assertEqual(ast.literal_eval('-6'), -6)
Raymond Hettingerbc959732010-10-08 00:47:45 +0000680 self.assertEqual(ast.literal_eval('3.25'), 3.25)
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +0200681 self.assertEqual(ast.literal_eval('+3.25'), 3.25)
682 self.assertEqual(ast.literal_eval('-3.25'), -3.25)
683 self.assertEqual(repr(ast.literal_eval('-0.0')), '-0.0')
684 self.assertRaises(ValueError, ast.literal_eval, '++6')
685 self.assertRaises(ValueError, ast.literal_eval, '+True')
686 self.assertRaises(ValueError, ast.literal_eval, '2+3')
Georg Brandl0c77a822008-06-10 16:37:50 +0000687
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +0200688 def test_literal_eval_complex(self):
689 # Issue #4907
690 self.assertEqual(ast.literal_eval('6j'), 6j)
691 self.assertEqual(ast.literal_eval('-6j'), -6j)
692 self.assertEqual(ast.literal_eval('6.75j'), 6.75j)
693 self.assertEqual(ast.literal_eval('-6.75j'), -6.75j)
694 self.assertEqual(ast.literal_eval('3+6j'), 3+6j)
695 self.assertEqual(ast.literal_eval('-3+6j'), -3+6j)
696 self.assertEqual(ast.literal_eval('3-6j'), 3-6j)
697 self.assertEqual(ast.literal_eval('-3-6j'), -3-6j)
698 self.assertEqual(ast.literal_eval('3.25+6.75j'), 3.25+6.75j)
699 self.assertEqual(ast.literal_eval('-3.25+6.75j'), -3.25+6.75j)
700 self.assertEqual(ast.literal_eval('3.25-6.75j'), 3.25-6.75j)
701 self.assertEqual(ast.literal_eval('-3.25-6.75j'), -3.25-6.75j)
702 self.assertEqual(ast.literal_eval('(3+6j)'), 3+6j)
703 self.assertRaises(ValueError, ast.literal_eval, '-6j+3')
704 self.assertRaises(ValueError, ast.literal_eval, '-6j+3j')
705 self.assertRaises(ValueError, ast.literal_eval, '3+-6j')
706 self.assertRaises(ValueError, ast.literal_eval, '3+(0+6j)')
707 self.assertRaises(ValueError, ast.literal_eval, '-(3+6j)')
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000708
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100709 def test_bad_integer(self):
710 # issue13436: Bad error message with invalid numeric values
711 body = [ast.ImportFrom(module='time',
712 names=[ast.alias(name='sleep')],
713 level=None,
714 lineno=None, col_offset=None)]
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300715 mod = ast.Module(body)
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100716 with self.assertRaises(ValueError) as cm:
717 compile(mod, 'test', 'exec')
718 self.assertIn("invalid integer value: None", str(cm.exception))
719
Berker Peksag0a5bd512016-04-29 19:50:02 +0300720 def test_level_as_none(self):
721 body = [ast.ImportFrom(module='time',
722 names=[ast.alias(name='sleep')],
723 level=None,
724 lineno=0, col_offset=0)]
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300725 mod = ast.Module(body)
Berker Peksag0a5bd512016-04-29 19:50:02 +0300726 code = compile(mod, 'test', 'exec')
727 ns = {}
728 exec(code, ns)
729 self.assertIn('sleep', ns)
730
Georg Brandl0c77a822008-06-10 16:37:50 +0000731
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500732class ASTValidatorTests(unittest.TestCase):
733
734 def mod(self, mod, msg=None, mode="exec", *, exc=ValueError):
735 mod.lineno = mod.col_offset = 0
736 ast.fix_missing_locations(mod)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300737 if msg is None:
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500738 compile(mod, "<test>", mode)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300739 else:
740 with self.assertRaises(exc) as cm:
741 compile(mod, "<test>", mode)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500742 self.assertIn(msg, str(cm.exception))
743
744 def expr(self, node, msg=None, *, exc=ValueError):
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300745 mod = ast.Module([ast.Expr(node)])
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500746 self.mod(mod, msg, exc=exc)
747
748 def stmt(self, stmt, msg=None):
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300749 mod = ast.Module([stmt])
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500750 self.mod(mod, msg)
751
752 def test_module(self):
753 m = ast.Interactive([ast.Expr(ast.Name("x", ast.Store()))])
754 self.mod(m, "must have Load context", "single")
755 m = ast.Expression(ast.Name("x", ast.Store()))
756 self.mod(m, "must have Load context", "eval")
757
758 def _check_arguments(self, fac, check):
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700759 def arguments(args=None, vararg=None,
760 kwonlyargs=None, kwarg=None,
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500761 defaults=None, kw_defaults=None):
762 if args is None:
763 args = []
764 if kwonlyargs is None:
765 kwonlyargs = []
766 if defaults is None:
767 defaults = []
768 if kw_defaults is None:
769 kw_defaults = []
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700770 args = ast.arguments(args, vararg, kwonlyargs, kw_defaults,
771 kwarg, defaults)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500772 return fac(args)
773 args = [ast.arg("x", ast.Name("x", ast.Store()))]
774 check(arguments(args=args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500775 check(arguments(kwonlyargs=args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500776 check(arguments(defaults=[ast.Num(3)]),
777 "more positional defaults than args")
778 check(arguments(kw_defaults=[ast.Num(4)]),
779 "length of kwonlyargs is not the same as kw_defaults")
780 args = [ast.arg("x", ast.Name("x", ast.Load()))]
781 check(arguments(args=args, defaults=[ast.Name("x", ast.Store())]),
782 "must have Load context")
783 args = [ast.arg("a", ast.Name("x", ast.Load())),
784 ast.arg("b", ast.Name("y", ast.Load()))]
785 check(arguments(kwonlyargs=args,
786 kw_defaults=[None, ast.Name("x", ast.Store())]),
787 "must have Load context")
788
789 def test_funcdef(self):
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700790 a = ast.arguments([], None, [], [], None, [])
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300791 f = ast.FunctionDef("x", a, [], [], None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500792 self.stmt(f, "empty body on FunctionDef")
793 f = ast.FunctionDef("x", a, [ast.Pass()], [ast.Name("x", ast.Store())],
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300794 None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500795 self.stmt(f, "must have Load context")
796 f = ast.FunctionDef("x", a, [ast.Pass()], [],
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300797 ast.Name("x", ast.Store()))
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500798 self.stmt(f, "must have Load context")
799 def fac(args):
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300800 return ast.FunctionDef("x", args, [ast.Pass()], [], None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500801 self._check_arguments(fac, self.stmt)
802
803 def test_classdef(self):
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400804 def cls(bases=None, keywords=None, body=None, decorator_list=None):
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500805 if bases is None:
806 bases = []
807 if keywords is None:
808 keywords = []
809 if body is None:
810 body = [ast.Pass()]
811 if decorator_list is None:
812 decorator_list = []
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400813 return ast.ClassDef("myclass", bases, keywords,
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300814 body, decorator_list)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500815 self.stmt(cls(bases=[ast.Name("x", ast.Store())]),
816 "must have Load context")
817 self.stmt(cls(keywords=[ast.keyword("x", ast.Name("x", ast.Store()))]),
818 "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500819 self.stmt(cls(body=[]), "empty body on ClassDef")
820 self.stmt(cls(body=[None]), "None disallowed")
821 self.stmt(cls(decorator_list=[ast.Name("x", ast.Store())]),
822 "must have Load context")
823
824 def test_delete(self):
825 self.stmt(ast.Delete([]), "empty targets on Delete")
826 self.stmt(ast.Delete([None]), "None disallowed")
827 self.stmt(ast.Delete([ast.Name("x", ast.Load())]),
828 "must have Del context")
829
830 def test_assign(self):
831 self.stmt(ast.Assign([], ast.Num(3)), "empty targets on Assign")
832 self.stmt(ast.Assign([None], ast.Num(3)), "None disallowed")
833 self.stmt(ast.Assign([ast.Name("x", ast.Load())], ast.Num(3)),
834 "must have Store context")
835 self.stmt(ast.Assign([ast.Name("x", ast.Store())],
836 ast.Name("y", ast.Store())),
837 "must have Load context")
838
839 def test_augassign(self):
840 aug = ast.AugAssign(ast.Name("x", ast.Load()), ast.Add(),
841 ast.Name("y", ast.Load()))
842 self.stmt(aug, "must have Store context")
843 aug = ast.AugAssign(ast.Name("x", ast.Store()), ast.Add(),
844 ast.Name("y", ast.Store()))
845 self.stmt(aug, "must have Load context")
846
847 def test_for(self):
848 x = ast.Name("x", ast.Store())
849 y = ast.Name("y", ast.Load())
850 p = ast.Pass()
851 self.stmt(ast.For(x, y, [], []), "empty body on For")
852 self.stmt(ast.For(ast.Name("x", ast.Load()), y, [p], []),
853 "must have Store context")
854 self.stmt(ast.For(x, ast.Name("y", ast.Store()), [p], []),
855 "must have Load context")
856 e = ast.Expr(ast.Name("x", ast.Store()))
857 self.stmt(ast.For(x, y, [e], []), "must have Load context")
858 self.stmt(ast.For(x, y, [p], [e]), "must have Load context")
859
860 def test_while(self):
861 self.stmt(ast.While(ast.Num(3), [], []), "empty body on While")
862 self.stmt(ast.While(ast.Name("x", ast.Store()), [ast.Pass()], []),
863 "must have Load context")
864 self.stmt(ast.While(ast.Num(3), [ast.Pass()],
865 [ast.Expr(ast.Name("x", ast.Store()))]),
866 "must have Load context")
867
868 def test_if(self):
869 self.stmt(ast.If(ast.Num(3), [], []), "empty body on If")
870 i = ast.If(ast.Name("x", ast.Store()), [ast.Pass()], [])
871 self.stmt(i, "must have Load context")
872 i = ast.If(ast.Num(3), [ast.Expr(ast.Name("x", ast.Store()))], [])
873 self.stmt(i, "must have Load context")
874 i = ast.If(ast.Num(3), [ast.Pass()],
875 [ast.Expr(ast.Name("x", ast.Store()))])
876 self.stmt(i, "must have Load context")
877
878 def test_with(self):
879 p = ast.Pass()
880 self.stmt(ast.With([], [p]), "empty items on With")
881 i = ast.withitem(ast.Num(3), None)
882 self.stmt(ast.With([i], []), "empty body on With")
883 i = ast.withitem(ast.Name("x", ast.Store()), None)
884 self.stmt(ast.With([i], [p]), "must have Load context")
885 i = ast.withitem(ast.Num(3), ast.Name("x", ast.Load()))
886 self.stmt(ast.With([i], [p]), "must have Store context")
887
888 def test_raise(self):
889 r = ast.Raise(None, ast.Num(3))
890 self.stmt(r, "Raise with cause but no exception")
891 r = ast.Raise(ast.Name("x", ast.Store()), None)
892 self.stmt(r, "must have Load context")
893 r = ast.Raise(ast.Num(4), ast.Name("x", ast.Store()))
894 self.stmt(r, "must have Load context")
895
896 def test_try(self):
897 p = ast.Pass()
898 t = ast.Try([], [], [], [p])
899 self.stmt(t, "empty body on Try")
900 t = ast.Try([ast.Expr(ast.Name("x", ast.Store()))], [], [], [p])
901 self.stmt(t, "must have Load context")
902 t = ast.Try([p], [], [], [])
903 self.stmt(t, "Try has neither except handlers nor finalbody")
904 t = ast.Try([p], [], [p], [p])
905 self.stmt(t, "Try has orelse but no except handlers")
906 t = ast.Try([p], [ast.ExceptHandler(None, "x", [])], [], [])
907 self.stmt(t, "empty body on ExceptHandler")
908 e = [ast.ExceptHandler(ast.Name("x", ast.Store()), "y", [p])]
909 self.stmt(ast.Try([p], e, [], []), "must have Load context")
910 e = [ast.ExceptHandler(None, "x", [p])]
911 t = ast.Try([p], e, [ast.Expr(ast.Name("x", ast.Store()))], [p])
912 self.stmt(t, "must have Load context")
913 t = ast.Try([p], e, [p], [ast.Expr(ast.Name("x", ast.Store()))])
914 self.stmt(t, "must have Load context")
915
916 def test_assert(self):
917 self.stmt(ast.Assert(ast.Name("x", ast.Store()), None),
918 "must have Load context")
919 assrt = ast.Assert(ast.Name("x", ast.Load()),
920 ast.Name("y", ast.Store()))
921 self.stmt(assrt, "must have Load context")
922
923 def test_import(self):
924 self.stmt(ast.Import([]), "empty names on Import")
925
926 def test_importfrom(self):
927 imp = ast.ImportFrom(None, [ast.alias("x", None)], -42)
Serhiy Storchaka7de28402016-06-27 23:40:43 +0300928 self.stmt(imp, "Negative ImportFrom level")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500929 self.stmt(ast.ImportFrom(None, [], 0), "empty names on ImportFrom")
930
931 def test_global(self):
932 self.stmt(ast.Global([]), "empty names on Global")
933
934 def test_nonlocal(self):
935 self.stmt(ast.Nonlocal([]), "empty names on Nonlocal")
936
937 def test_expr(self):
938 e = ast.Expr(ast.Name("x", ast.Store()))
939 self.stmt(e, "must have Load context")
940
941 def test_boolop(self):
942 b = ast.BoolOp(ast.And(), [])
943 self.expr(b, "less than 2 values")
944 b = ast.BoolOp(ast.And(), [ast.Num(3)])
945 self.expr(b, "less than 2 values")
946 b = ast.BoolOp(ast.And(), [ast.Num(4), None])
947 self.expr(b, "None disallowed")
948 b = ast.BoolOp(ast.And(), [ast.Num(4), ast.Name("x", ast.Store())])
949 self.expr(b, "must have Load context")
950
951 def test_unaryop(self):
952 u = ast.UnaryOp(ast.Not(), ast.Name("x", ast.Store()))
953 self.expr(u, "must have Load context")
954
955 def test_lambda(self):
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700956 a = ast.arguments([], None, [], [], None, [])
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500957 self.expr(ast.Lambda(a, ast.Name("x", ast.Store())),
958 "must have Load context")
959 def fac(args):
960 return ast.Lambda(args, ast.Name("x", ast.Load()))
961 self._check_arguments(fac, self.expr)
962
963 def test_ifexp(self):
964 l = ast.Name("x", ast.Load())
965 s = ast.Name("y", ast.Store())
966 for args in (s, l, l), (l, s, l), (l, l, s):
Benjamin Peterson71ce8972011-08-09 16:17:12 -0500967 self.expr(ast.IfExp(*args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500968
969 def test_dict(self):
970 d = ast.Dict([], [ast.Name("x", ast.Load())])
971 self.expr(d, "same number of keys as values")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500972 d = ast.Dict([ast.Name("x", ast.Load())], [None])
973 self.expr(d, "None disallowed")
974
975 def test_set(self):
976 self.expr(ast.Set([None]), "None disallowed")
977 s = ast.Set([ast.Name("x", ast.Store())])
978 self.expr(s, "must have Load context")
979
980 def _check_comprehension(self, fac):
981 self.expr(fac([]), "comprehension with no generators")
982 g = ast.comprehension(ast.Name("x", ast.Load()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700983 ast.Name("x", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500984 self.expr(fac([g]), "must have Store context")
985 g = ast.comprehension(ast.Name("x", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700986 ast.Name("x", ast.Store()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500987 self.expr(fac([g]), "must have Load context")
988 x = ast.Name("x", ast.Store())
989 y = ast.Name("y", ast.Load())
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700990 g = ast.comprehension(x, y, [None], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500991 self.expr(fac([g]), "None disallowed")
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700992 g = ast.comprehension(x, y, [ast.Name("x", ast.Store())], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500993 self.expr(fac([g]), "must have Load context")
994
995 def _simple_comp(self, fac):
996 g = ast.comprehension(ast.Name("x", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700997 ast.Name("x", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500998 self.expr(fac(ast.Name("x", ast.Store()), [g]),
999 "must have Load context")
1000 def wrap(gens):
1001 return fac(ast.Name("x", ast.Store()), gens)
1002 self._check_comprehension(wrap)
1003
1004 def test_listcomp(self):
1005 self._simple_comp(ast.ListComp)
1006
1007 def test_setcomp(self):
1008 self._simple_comp(ast.SetComp)
1009
1010 def test_generatorexp(self):
1011 self._simple_comp(ast.GeneratorExp)
1012
1013 def test_dictcomp(self):
1014 g = ast.comprehension(ast.Name("y", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001015 ast.Name("p", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001016 c = ast.DictComp(ast.Name("x", ast.Store()),
1017 ast.Name("y", ast.Load()), [g])
1018 self.expr(c, "must have Load context")
1019 c = ast.DictComp(ast.Name("x", ast.Load()),
1020 ast.Name("y", ast.Store()), [g])
1021 self.expr(c, "must have Load context")
1022 def factory(comps):
1023 k = ast.Name("x", ast.Load())
1024 v = ast.Name("y", ast.Load())
1025 return ast.DictComp(k, v, comps)
1026 self._check_comprehension(factory)
1027
1028 def test_yield(self):
Benjamin Peterson527c6222012-01-14 08:58:23 -05001029 self.expr(ast.Yield(ast.Name("x", ast.Store())), "must have Load")
1030 self.expr(ast.YieldFrom(ast.Name("x", ast.Store())), "must have Load")
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001031
1032 def test_compare(self):
1033 left = ast.Name("x", ast.Load())
1034 comp = ast.Compare(left, [ast.In()], [])
1035 self.expr(comp, "no comparators")
1036 comp = ast.Compare(left, [ast.In()], [ast.Num(4), ast.Num(5)])
1037 self.expr(comp, "different number of comparators and operands")
1038 comp = ast.Compare(ast.Num("blah"), [ast.In()], [left])
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001039 self.expr(comp)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001040 comp = ast.Compare(left, [ast.In()], [ast.Num("blah")])
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001041 self.expr(comp)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001042
1043 def test_call(self):
1044 func = ast.Name("x", ast.Load())
1045 args = [ast.Name("y", ast.Load())]
1046 keywords = [ast.keyword("w", ast.Name("z", ast.Load()))]
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001047 call = ast.Call(ast.Name("x", ast.Store()), args, keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001048 self.expr(call, "must have Load context")
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001049 call = ast.Call(func, [None], keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001050 self.expr(call, "None disallowed")
1051 bad_keywords = [ast.keyword("w", ast.Name("z", ast.Store()))]
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001052 call = ast.Call(func, args, bad_keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001053 self.expr(call, "must have Load context")
1054
1055 def test_num(self):
1056 class subint(int):
1057 pass
1058 class subfloat(float):
1059 pass
1060 class subcomplex(complex):
1061 pass
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001062 for obj in "0", "hello":
1063 self.expr(ast.Num(obj))
1064 for obj in subint(), subfloat(), subcomplex():
1065 self.expr(ast.Num(obj), "invalid type", exc=TypeError)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001066
1067 def test_attribute(self):
1068 attr = ast.Attribute(ast.Name("x", ast.Store()), "y", ast.Load())
1069 self.expr(attr, "must have Load context")
1070
1071 def test_subscript(self):
1072 sub = ast.Subscript(ast.Name("x", ast.Store()), ast.Index(ast.Num(3)),
1073 ast.Load())
1074 self.expr(sub, "must have Load context")
1075 x = ast.Name("x", ast.Load())
1076 sub = ast.Subscript(x, ast.Index(ast.Name("y", ast.Store())),
1077 ast.Load())
1078 self.expr(sub, "must have Load context")
1079 s = ast.Name("x", ast.Store())
1080 for args in (s, None, None), (None, s, None), (None, None, s):
1081 sl = ast.Slice(*args)
1082 self.expr(ast.Subscript(x, sl, ast.Load()),
1083 "must have Load context")
1084 sl = ast.ExtSlice([])
1085 self.expr(ast.Subscript(x, sl, ast.Load()), "empty dims on ExtSlice")
1086 sl = ast.ExtSlice([ast.Index(s)])
1087 self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context")
1088
1089 def test_starred(self):
1090 left = ast.List([ast.Starred(ast.Name("x", ast.Load()), ast.Store())],
1091 ast.Store())
1092 assign = ast.Assign([left], ast.Num(4))
1093 self.stmt(assign, "must have Store context")
1094
1095 def _sequence(self, fac):
1096 self.expr(fac([None], ast.Load()), "None disallowed")
1097 self.expr(fac([ast.Name("x", ast.Store())], ast.Load()),
1098 "must have Load context")
1099
1100 def test_list(self):
1101 self._sequence(ast.List)
1102
1103 def test_tuple(self):
1104 self._sequence(ast.Tuple)
1105
Benjamin Peterson442f2092012-12-06 17:41:04 -05001106 def test_nameconstant(self):
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001107 self.expr(ast.NameConstant(4))
Benjamin Peterson442f2092012-12-06 17:41:04 -05001108
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001109 def test_stdlib_validates(self):
1110 stdlib = os.path.dirname(ast.__file__)
1111 tests = [fn for fn in os.listdir(stdlib) if fn.endswith(".py")]
1112 tests.extend(["test/test_grammar.py", "test/test_unpack_ex.py"])
1113 for module in tests:
1114 fn = os.path.join(stdlib, module)
1115 with open(fn, "r", encoding="utf-8") as fp:
1116 source = fp.read()
Victor Stinnerd502a072013-03-22 00:06:20 +01001117 mod = ast.parse(source, fn)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001118 compile(mod, fn, "exec")
1119
1120
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001121class ConstantTests(unittest.TestCase):
1122 """Tests on the ast.Constant node type."""
1123
1124 def compile_constant(self, value):
1125 tree = ast.parse("x = 123")
1126
1127 node = tree.body[0].value
1128 new_node = ast.Constant(value=value)
1129 ast.copy_location(new_node, node)
1130 tree.body[0].value = new_node
1131
1132 code = compile(tree, "<string>", "exec")
1133
1134 ns = {}
1135 exec(code, ns)
1136 return ns['x']
1137
Victor Stinnerbe59d142016-01-27 00:39:12 +01001138 def test_validation(self):
1139 with self.assertRaises(TypeError) as cm:
1140 self.compile_constant([1, 2, 3])
1141 self.assertEqual(str(cm.exception),
1142 "got an invalid type in Constant: list")
1143
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001144 def test_singletons(self):
1145 for const in (None, False, True, Ellipsis, b'', frozenset()):
1146 with self.subTest(const=const):
1147 value = self.compile_constant(const)
1148 self.assertIs(value, const)
1149
1150 def test_values(self):
1151 nested_tuple = (1,)
1152 nested_frozenset = frozenset({1})
1153 for level in range(3):
1154 nested_tuple = (nested_tuple, 2)
1155 nested_frozenset = frozenset({nested_frozenset, 2})
1156 values = (123, 123.0, 123j,
1157 "unicode", b'bytes',
1158 tuple("tuple"), frozenset("frozenset"),
1159 nested_tuple, nested_frozenset)
1160 for value in values:
1161 with self.subTest(value=value):
1162 result = self.compile_constant(value)
1163 self.assertEqual(result, value)
1164
1165 def test_assign_to_constant(self):
1166 tree = ast.parse("x = 1")
1167
1168 target = tree.body[0].targets[0]
1169 new_target = ast.Constant(value=1)
1170 ast.copy_location(new_target, target)
1171 tree.body[0].targets[0] = new_target
1172
1173 with self.assertRaises(ValueError) as cm:
1174 compile(tree, "string", "exec")
1175 self.assertEqual(str(cm.exception),
1176 "expression which can't be assigned "
1177 "to in Store context")
1178
1179 def test_get_docstring(self):
1180 tree = ast.parse("'docstring'\nx = 1")
1181 self.assertEqual(ast.get_docstring(tree), 'docstring')
1182
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001183 def get_load_const(self, tree):
1184 # Compile to bytecode, disassemble and get parameter of LOAD_CONST
1185 # instructions
1186 co = compile(tree, '<string>', 'exec')
1187 consts = []
1188 for instr in dis.get_instructions(co):
1189 if instr.opname == 'LOAD_CONST':
1190 consts.append(instr.argval)
1191 return consts
1192
1193 @support.cpython_only
1194 def test_load_const(self):
1195 consts = [None,
1196 True, False,
1197 124,
1198 2.0,
1199 3j,
1200 "unicode",
1201 b'bytes',
1202 (1, 2, 3)]
1203
Victor Stinnera2724092016-02-08 18:17:58 +01001204 code = '\n'.join(['x={!r}'.format(const) for const in consts])
1205 code += '\nx = ...'
1206 consts.extend((Ellipsis, None))
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001207
1208 tree = ast.parse(code)
Victor Stinnera2724092016-02-08 18:17:58 +01001209 self.assertEqual(self.get_load_const(tree),
1210 consts)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001211
1212 # Replace expression nodes with constants
Victor Stinnera2724092016-02-08 18:17:58 +01001213 for assign, const in zip(tree.body, consts):
1214 assert isinstance(assign, ast.Assign), ast.dump(assign)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001215 new_node = ast.Constant(value=const)
Victor Stinnera2724092016-02-08 18:17:58 +01001216 ast.copy_location(new_node, assign.value)
1217 assign.value = new_node
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001218
Victor Stinnera2724092016-02-08 18:17:58 +01001219 self.assertEqual(self.get_load_const(tree),
1220 consts)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001221
1222 def test_literal_eval(self):
1223 tree = ast.parse("1 + 2")
1224 binop = tree.body[0].value
1225
1226 new_left = ast.Constant(value=10)
1227 ast.copy_location(new_left, binop.left)
1228 binop.left = new_left
1229
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +02001230 new_right = ast.Constant(value=20j)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001231 ast.copy_location(new_right, binop.right)
1232 binop.right = new_right
1233
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +02001234 self.assertEqual(ast.literal_eval(binop), 10+20j)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001235
1236
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001237def main():
1238 if __name__ != '__main__':
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001239 return
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001240 if sys.argv[1:] == ['-g']:
1241 for statements, kind in ((exec_tests, "exec"), (single_tests, "single"),
1242 (eval_tests, "eval")):
1243 print(kind+"_results = [")
Victor Stinnerf0891962016-02-08 17:15:21 +01001244 for statement in statements:
1245 tree = ast.parse(statement, "?", kind)
1246 print("%r," % (to_tuple(tree),))
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001247 print("]")
1248 print("main()")
1249 raise SystemExit
Brett Cannon3e9a9ae2013-06-12 21:25:59 -04001250 unittest.main()
Tim Peters400cbc32006-02-28 18:44:41 +00001251
1252#### EVERYTHING BELOW IS GENERATED #####
1253exec_results = [
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001254('Module', [('Expr', (1, 0), ('Constant', (1, 0), None))]),
1255('Module', [('Expr', (1, 0), ('Constant', (1, 0), 'module docstring'))]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001256('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [('Pass', (1, 9))], [], None)]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001257('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [('Expr', (1, 9), ('Constant', (1, 9), 'function docstring'))], [], None)]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001258('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None)], None, [], [], None, []), [('Pass', (1, 10))], [], None)]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001259('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 +03001260('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], ('arg', (1, 7), 'args', None), [], [], None, []), [('Pass', (1, 14))], [], None)]),
1261('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], ('arg', (1, 8), 'kwargs', None), []), [('Pass', (1, 17))], [], None)]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001262('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 +03001263('Module', [('ClassDef', (1, 0), 'C', [], [], [('Pass', (1, 8))], [])]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001264('Module', [('ClassDef', (1, 0), 'C', [], [], [('Expr', (1, 9), ('Constant', (1, 9), 'docstring for class C'))], [])]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001265('Module', [('ClassDef', (1, 0), 'C', [('Name', (1, 8), 'object', ('Load',))], [], [('Pass', (1, 17))], [])]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001266('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [('Return', (1, 8), ('Constant', (1, 15), 1))], [], None)]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001267('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001268('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Constant', (1, 4), 1))]),
1269('Module', [('AugAssign', (1, 0), ('Name', (1, 0), 'v', ('Store',)), ('Add',), ('Constant', (1, 5), 1))]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001270('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Pass', (1, 11))], [])]),
1271('Module', [('While', (1, 0), ('Name', (1, 6), 'v', ('Load',)), [('Pass', (1, 8))], [])]),
1272('Module', [('If', (1, 0), ('Name', (1, 3), 'v', ('Load',)), [('Pass', (1, 5))], [])]),
1273('Module', [('With', (1, 0), [('withitem', ('Name', (1, 5), 'x', ('Load',)), ('Name', (1, 10), 'y', ('Store',)))], [('Pass', (1, 13))])]),
1274('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 +03001275('Module', [('Raise', (1, 0), ('Call', (1, 6), ('Name', (1, 6), 'Exception', ('Load',)), [('Constant', (1, 16), 'string')], []), None)]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001276('Module', [('Try', (1, 0), [('Pass', (2, 2))], [('ExceptHandler', (3, 0), ('Name', (3, 7), 'Exception', ('Load',)), None, [('Pass', (4, 2))])], [], [])]),
1277('Module', [('Try', (1, 0), [('Pass', (2, 2))], [], [], [('Pass', (4, 2))])]),
1278('Module', [('Assert', (1, 0), ('Name', (1, 7), 'v', ('Load',)), None)]),
1279('Module', [('Import', (1, 0), [('alias', 'sys', None)])]),
1280('Module', [('ImportFrom', (1, 0), 'sys', [('alias', 'v', None)], 0)]),
1281('Module', [('Global', (1, 0), ['v'])]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001282('Module', [('Expr', (1, 0), ('Constant', (1, 0), 1))]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001283('Module', [('Pass', (1, 0))]),
1284('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Break', (1, 11))], [])]),
1285('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Continue', (1, 11))], [])]),
1286('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))], [])]),
1287('Module', [('Expr', (1, 0), ('ListComp', (1, 1), ('Tuple', (1, 2), [('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)]))]),
1288('Module', [('Expr', (1, 0), ('GeneratorExp', (1, 1), ('Tuple', (1, 2), [('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)]))]),
1289('Module', [('Expr', (1, 0), ('GeneratorExp', (1, 1), ('Tuple', (1, 2), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 12), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [], 0)]))]),
1290('Module', [('Expr', (1, 0), ('GeneratorExp', (2, 4), ('Tuple', (3, 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)]))]),
1291('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)]))]),
1292('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)]))]),
1293('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)]))]),
1294('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 +03001295('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)]),
1296('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)]),
1297('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)]),
1298('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)]))]),
1299('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)]))]),
guoci90fc8982018-09-11 17:45:45 -04001300('Module', [('AsyncFunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [('Expr', (2, 1), ('ListComp', (2, 2), ('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 +02001301('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)]),
1302('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)]),
1303('Module', [('ClassDef', (3, 0), 'C', [], [], [('Pass', (3, 9))], [('Name', (1, 1), 'deco1', ('Load',)), ('Call', (2, 0), ('Name', (2, 1), 'deco2', ('Load',)), [], [])])]),
Tim Peters400cbc32006-02-28 18:44:41 +00001304]
1305single_results = [
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001306('Interactive', [('Expr', (1, 0), ('BinOp', (1, 0), ('Constant', (1, 0), 1), ('Add',), ('Constant', (1, 2), 2)))]),
Tim Peters400cbc32006-02-28 18:44:41 +00001307]
1308eval_results = [
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001309('Expression', ('Constant', (1, 0), None)),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001310('Expression', ('BoolOp', (1, 0), ('And',), [('Name', (1, 0), 'a', ('Load',)), ('Name', (1, 6), 'b', ('Load',))])),
1311('Expression', ('BinOp', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Add',), ('Name', (1, 4), 'b', ('Load',)))),
1312('Expression', ('UnaryOp', (1, 0), ('Not',), ('Name', (1, 4), 'v', ('Load',)))),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001313('Expression', ('Lambda', (1, 0), ('arguments', [], None, [], [], None, []), ('Constant', (1, 7), None))),
1314('Expression', ('Dict', (1, 0), [('Constant', (1, 2), 1)], [('Constant', (1, 4), 2)])),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001315('Expression', ('Dict', (1, 0), [], [])),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001316('Expression', ('Set', (1, 0), [('Constant', (1, 1), None)])),
1317('Expression', ('Dict', (1, 0), [('Constant', (2, 6), 1)], [('Constant', (4, 10), 2)])),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001318('Expression', ('ListComp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), [('comprehension', ('Name', (1, 7), 'b', ('Store',)), ('Name', (1, 12), 'c', ('Load',)), [('Name', (1, 17), 'd', ('Load',))], 0)])),
1319('Expression', ('GeneratorExp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), [('comprehension', ('Name', (1, 7), 'b', ('Store',)), ('Name', (1, 12), 'c', ('Load',)), [('Name', (1, 17), 'd', ('Load',))], 0)])),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001320('Expression', ('Compare', (1, 0), ('Constant', (1, 0), 1), [('Lt',), ('Lt',)], [('Constant', (1, 4), 2), ('Constant', (1, 8), 3)])),
1321('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',)))])),
1322('Expression', ('Constant', (1, 0), 10)),
1323('Expression', ('Constant', (1, 0), 'string')),
Benjamin Peterson7a66fc22015-02-02 10:51:20 -05001324('Expression', ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',))),
1325('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 +00001326('Expression', ('Name', (1, 0), 'v', ('Load',))),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001327('Expression', ('List', (1, 0), [('Constant', (1, 1), 1), ('Constant', (1, 3), 2), ('Constant', (1, 5), 3)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001328('Expression', ('List', (1, 0), [], ('Load',))),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001329('Expression', ('Tuple', (1, 0), [('Constant', (1, 0), 1), ('Constant', (1, 2), 2), ('Constant', (1, 4), 3)], ('Load',))),
1330('Expression', ('Tuple', (1, 1), [('Constant', (1, 1), 1), ('Constant', (1, 3), 2), ('Constant', (1, 5), 3)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001331('Expression', ('Tuple', (1, 0), [], ('Load',))),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001332('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 +00001333]
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001334main()