blob: 10be02eee0c03c4bc52cfc8419381ebafe15fb56 [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]",
Tim Peters400cbc32006-02-28 18:44:41 +0000127]
128
129# These are compiled through "single"
130# because of overlap with "eval", it just tests what
131# can't be tested with "eval"
132single_tests = [
133 "1+2"
134]
135
136# These are compiled through "eval"
137# It should test all expressions
138eval_tests = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500139 # None
140 "None",
Tim Peters400cbc32006-02-28 18:44:41 +0000141 # BoolOp
142 "a and b",
143 # BinOp
144 "a + b",
145 # UnaryOp
146 "not v",
147 # Lambda
148 "lambda:None",
149 # Dict
150 "{ 1:2 }",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500151 # Empty dict
152 "{}",
153 # Set
154 "{None,}",
155 # Multiline dict (test for .lineno & .col_offset)
156 """{
157 1
158 :
159 2
160 }""",
Tim Peters400cbc32006-02-28 18:44:41 +0000161 # ListComp
162 "[a for b in c if d]",
163 # GeneratorExp
164 "(a for b in c if d)",
165 # Yield - yield expressions can't work outside a function
166 #
167 # Compare
168 "1 < 2 < 3",
169 # Call
170 "f(1,2,c=3,*d,**e)",
Tim Peters400cbc32006-02-28 18:44:41 +0000171 # Num
Guido van Rossume2a383d2007-01-15 16:59:06 +0000172 "10",
Tim Peters400cbc32006-02-28 18:44:41 +0000173 # Str
174 "'string'",
175 # Attribute
176 "a.b",
177 # Subscript
178 "a[b:c]",
179 # Name
180 "v",
181 # List
182 "[1,2,3]",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500183 # Empty list
184 "[]",
Tim Peters400cbc32006-02-28 18:44:41 +0000185 # Tuple
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000186 "1,2,3",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500187 # Tuple
188 "(1,2,3)",
189 # Empty tuple
190 "()",
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000191 # Combination
192 "a.b.c.d(a.b[1:2])",
193
Tim Peters400cbc32006-02-28 18:44:41 +0000194]
195
196# TODO: expr_context, slice, boolop, operator, unaryop, cmpop, comprehension
197# excepthandler, arguments, keywords, alias
198
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000199class AST_Tests(unittest.TestCase):
Tim Peters400cbc32006-02-28 18:44:41 +0000200
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500201 def _assertTrueorder(self, ast_node, parent_pos):
Georg Brandl0c77a822008-06-10 16:37:50 +0000202 if not isinstance(ast_node, ast.AST) or ast_node._fields is None:
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000203 return
Georg Brandl0c77a822008-06-10 16:37:50 +0000204 if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000205 node_pos = (ast_node.lineno, ast_node.col_offset)
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500206 self.assertTrue(node_pos >= parent_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000207 parent_pos = (ast_node.lineno, ast_node.col_offset)
208 for name in ast_node._fields:
209 value = getattr(ast_node, name)
210 if isinstance(value, list):
211 for child in value:
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500212 self._assertTrueorder(child, parent_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000213 elif value is not None:
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500214 self._assertTrueorder(value, parent_pos)
Tim Peters5ddfe412006-03-01 23:02:57 +0000215
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500216 def test_AST_objects(self):
217 x = ast.AST()
218 self.assertEqual(x._fields, ())
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700219 x.foobar = 42
220 self.assertEqual(x.foobar, 42)
221 self.assertEqual(x.__dict__["foobar"], 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500222
223 with self.assertRaises(AttributeError):
224 x.vararg
225
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500226 with self.assertRaises(TypeError):
227 # "_ast.AST constructor takes 0 positional arguments"
228 ast.AST(2)
229
Benjamin Peterson9ed37432012-07-08 11:13:36 -0700230 def test_AST_garbage_collection(self):
231 class X:
232 pass
233 a = ast.AST()
234 a.x = X()
235 a.x.a = a
236 ref = weakref.ref(a.x)
237 del a
238 support.gc_collect()
239 self.assertIsNone(ref())
240
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000241 def test_snippets(self):
242 for input, output, kind in ((exec_tests, exec_results, "exec"),
243 (single_tests, single_results, "single"),
244 (eval_tests, eval_results, "eval")):
245 for i, o in zip(input, output):
Yury Selivanovb3d53132015-09-01 16:10:49 -0400246 with self.subTest(action="parsing", input=i):
247 ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST)
248 self.assertEqual(to_tuple(ast_tree), o)
249 self._assertTrueorder(ast_tree, (0, 0))
Victor Stinner15a30952016-02-08 22:45:06 +0100250 with self.subTest(action="compiling", input=i, kind=kind):
251 compile(ast_tree, "?", kind)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000252
Benjamin Peterson78565b22009-06-28 19:19:51 +0000253 def test_slice(self):
254 slc = ast.parse("x[::]").body[0].value.slice
255 self.assertIsNone(slc.upper)
256 self.assertIsNone(slc.lower)
257 self.assertIsNone(slc.step)
258
259 def test_from_import(self):
260 im = ast.parse("from . import y").body[0]
261 self.assertIsNone(im.module)
262
Benjamin Petersona4e4e352012-03-22 08:19:04 -0400263 def test_non_interned_future_from_ast(self):
264 mod = ast.parse("from __future__ import division")
265 self.assertIsInstance(mod.body[0], ast.ImportFrom)
266 mod.body[0].module = " __future__ ".strip()
267 compile(mod, "<test>", "exec")
268
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000269 def test_base_classes(self):
270 self.assertTrue(issubclass(ast.For, ast.stmt))
271 self.assertTrue(issubclass(ast.Name, ast.expr))
272 self.assertTrue(issubclass(ast.stmt, ast.AST))
273 self.assertTrue(issubclass(ast.expr, ast.AST))
274 self.assertTrue(issubclass(ast.comprehension, ast.AST))
275 self.assertTrue(issubclass(ast.Gt, ast.AST))
276
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500277 def test_field_attr_existence(self):
278 for name, item in ast.__dict__.items():
279 if isinstance(item, type) and name != 'AST' and name[0].isupper():
280 x = item()
281 if isinstance(x, ast.AST):
282 self.assertEqual(type(x._fields), tuple)
283
284 def test_arguments(self):
285 x = ast.arguments()
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500286 self.assertEqual(x._fields, ('args', 'vararg', 'kwonlyargs',
287 'kw_defaults', 'kwarg', 'defaults'))
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500288
289 with self.assertRaises(AttributeError):
290 x.vararg
291
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700292 x = ast.arguments(*range(1, 7))
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500293 self.assertEqual(x.vararg, 2)
294
295 def test_field_attr_writable(self):
296 x = ast.Num()
297 # We can assign to _fields
298 x._fields = 666
299 self.assertEqual(x._fields, 666)
300
301 def test_classattrs(self):
302 x = ast.Num()
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300303 self.assertEqual(x._fields, ('value',))
304
305 with self.assertRaises(AttributeError):
306 x.value
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500307
308 with self.assertRaises(AttributeError):
309 x.n
310
311 x = ast.Num(42)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300312 self.assertEqual(x.value, 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500313 self.assertEqual(x.n, 42)
314
315 with self.assertRaises(AttributeError):
316 x.lineno
317
318 with self.assertRaises(AttributeError):
319 x.foobar
320
321 x = ast.Num(lineno=2)
322 self.assertEqual(x.lineno, 2)
323
324 x = ast.Num(42, lineno=0)
325 self.assertEqual(x.lineno, 0)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300326 self.assertEqual(x._fields, ('value',))
327 self.assertEqual(x.value, 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500328 self.assertEqual(x.n, 42)
329
330 self.assertRaises(TypeError, ast.Num, 1, 2)
331 self.assertRaises(TypeError, ast.Num, 1, 2, lineno=0)
332
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300333 self.assertEqual(ast.Num(42).n, 42)
334 self.assertEqual(ast.Num(4.25).n, 4.25)
335 self.assertEqual(ast.Num(4.25j).n, 4.25j)
336 self.assertEqual(ast.Str('42').s, '42')
337 self.assertEqual(ast.Bytes(b'42').s, b'42')
338 self.assertIs(ast.NameConstant(True).value, True)
339 self.assertIs(ast.NameConstant(False).value, False)
340 self.assertIs(ast.NameConstant(None).value, None)
341
342 self.assertEqual(ast.Constant(42).value, 42)
343 self.assertEqual(ast.Constant(4.25).value, 4.25)
344 self.assertEqual(ast.Constant(4.25j).value, 4.25j)
345 self.assertEqual(ast.Constant('42').value, '42')
346 self.assertEqual(ast.Constant(b'42').value, b'42')
347 self.assertIs(ast.Constant(True).value, True)
348 self.assertIs(ast.Constant(False).value, False)
349 self.assertIs(ast.Constant(None).value, None)
350 self.assertIs(ast.Constant(...).value, ...)
351
352 def test_realtype(self):
353 self.assertEqual(type(ast.Num(42)), ast.Constant)
354 self.assertEqual(type(ast.Num(4.25)), ast.Constant)
355 self.assertEqual(type(ast.Num(4.25j)), ast.Constant)
356 self.assertEqual(type(ast.Str('42')), ast.Constant)
357 self.assertEqual(type(ast.Bytes(b'42')), ast.Constant)
358 self.assertEqual(type(ast.NameConstant(True)), ast.Constant)
359 self.assertEqual(type(ast.NameConstant(False)), ast.Constant)
360 self.assertEqual(type(ast.NameConstant(None)), ast.Constant)
361 self.assertEqual(type(ast.Ellipsis()), ast.Constant)
362
363 def test_isinstance(self):
364 self.assertTrue(isinstance(ast.Num(42), ast.Num))
365 self.assertTrue(isinstance(ast.Num(4.2), ast.Num))
366 self.assertTrue(isinstance(ast.Num(4.2j), ast.Num))
367 self.assertTrue(isinstance(ast.Str('42'), ast.Str))
368 self.assertTrue(isinstance(ast.Bytes(b'42'), ast.Bytes))
369 self.assertTrue(isinstance(ast.NameConstant(True), ast.NameConstant))
370 self.assertTrue(isinstance(ast.NameConstant(False), ast.NameConstant))
371 self.assertTrue(isinstance(ast.NameConstant(None), ast.NameConstant))
372 self.assertTrue(isinstance(ast.Ellipsis(), ast.Ellipsis))
373
374 self.assertTrue(isinstance(ast.Constant(42), ast.Num))
375 self.assertTrue(isinstance(ast.Constant(4.2), ast.Num))
376 self.assertTrue(isinstance(ast.Constant(4.2j), ast.Num))
377 self.assertTrue(isinstance(ast.Constant('42'), ast.Str))
378 self.assertTrue(isinstance(ast.Constant(b'42'), ast.Bytes))
379 self.assertTrue(isinstance(ast.Constant(True), ast.NameConstant))
380 self.assertTrue(isinstance(ast.Constant(False), ast.NameConstant))
381 self.assertTrue(isinstance(ast.Constant(None), ast.NameConstant))
382 self.assertTrue(isinstance(ast.Constant(...), ast.Ellipsis))
383
384 self.assertFalse(isinstance(ast.Str('42'), ast.Num))
385 self.assertFalse(isinstance(ast.Num(42), ast.Str))
386 self.assertFalse(isinstance(ast.Str('42'), ast.Bytes))
387 self.assertFalse(isinstance(ast.Num(42), ast.NameConstant))
388 self.assertFalse(isinstance(ast.Num(42), ast.Ellipsis))
389
390 self.assertFalse(isinstance(ast.Constant('42'), ast.Num))
391 self.assertFalse(isinstance(ast.Constant(42), ast.Str))
392 self.assertFalse(isinstance(ast.Constant('42'), ast.Bytes))
393 self.assertFalse(isinstance(ast.Constant(42), ast.NameConstant))
394 self.assertFalse(isinstance(ast.Constant(42), ast.Ellipsis))
395
396 self.assertFalse(isinstance(ast.Constant(), ast.Num))
397 self.assertFalse(isinstance(ast.Constant(), ast.Str))
398 self.assertFalse(isinstance(ast.Constant(), ast.Bytes))
399 self.assertFalse(isinstance(ast.Constant(), ast.NameConstant))
400 self.assertFalse(isinstance(ast.Constant(), ast.Ellipsis))
401
402 def test_subclasses(self):
403 class N(ast.Num):
404 def __init__(self, *args, **kwargs):
405 super().__init__(*args, **kwargs)
406 self.z = 'spam'
407 class N2(ast.Num):
408 pass
409
410 n = N(42)
411 self.assertEqual(n.n, 42)
412 self.assertEqual(n.z, 'spam')
413 self.assertEqual(type(n), N)
414 self.assertTrue(isinstance(n, N))
415 self.assertTrue(isinstance(n, ast.Num))
416 self.assertFalse(isinstance(n, N2))
417 self.assertFalse(isinstance(ast.Num(42), N))
418 n = N(n=42)
419 self.assertEqual(n.n, 42)
420 self.assertEqual(type(n), N)
421
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500422 def test_module(self):
423 body = [ast.Num(42)]
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300424 x = ast.Module(body)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500425 self.assertEqual(x.body, body)
426
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000427 def test_nodeclasses(self):
Florent Xicluna992d9e02011-11-11 19:35:42 +0100428 # Zero arguments constructor explicitly allowed
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500429 x = ast.BinOp()
430 self.assertEqual(x._fields, ('left', 'op', 'right'))
431
432 # Random attribute allowed too
433 x.foobarbaz = 5
434 self.assertEqual(x.foobarbaz, 5)
435
436 n1 = ast.Num(1)
437 n3 = ast.Num(3)
438 addop = ast.Add()
439 x = ast.BinOp(n1, addop, n3)
440 self.assertEqual(x.left, n1)
441 self.assertEqual(x.op, addop)
442 self.assertEqual(x.right, n3)
Benjamin Peterson68b543a2011-06-27 17:51:18 -0500443
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500444 x = ast.BinOp(1, 2, 3)
445 self.assertEqual(x.left, 1)
446 self.assertEqual(x.op, 2)
447 self.assertEqual(x.right, 3)
448
Georg Brandl0c77a822008-06-10 16:37:50 +0000449 x = ast.BinOp(1, 2, 3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000450 self.assertEqual(x.left, 1)
451 self.assertEqual(x.op, 2)
452 self.assertEqual(x.right, 3)
453 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000454
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500455 # node raises exception when given too many arguments
456 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500457 # node raises exception when given too many arguments
458 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4, lineno=0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000459
460 # can set attributes through kwargs too
Georg Brandl0c77a822008-06-10 16:37:50 +0000461 x = ast.BinOp(left=1, op=2, right=3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000462 self.assertEqual(x.left, 1)
463 self.assertEqual(x.op, 2)
464 self.assertEqual(x.right, 3)
465 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000466
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500467 # Random kwargs also allowed
468 x = ast.BinOp(1, 2, 3, foobarbaz=42)
469 self.assertEqual(x.foobarbaz, 42)
470
471 def test_no_fields(self):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000472 # this used to fail because Sub._fields was None
Georg Brandl0c77a822008-06-10 16:37:50 +0000473 x = ast.Sub()
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500474 self.assertEqual(x._fields, ())
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000475
476 def test_pickling(self):
477 import pickle
478 mods = [pickle]
479 try:
480 import cPickle
481 mods.append(cPickle)
482 except ImportError:
483 pass
484 protocols = [0, 1, 2]
485 for mod in mods:
486 for protocol in protocols:
487 for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests):
488 ast2 = mod.loads(mod.dumps(ast, protocol))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000489 self.assertEqual(to_tuple(ast2), to_tuple(ast))
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000490
Benjamin Peterson5b066812010-11-20 01:38:49 +0000491 def test_invalid_sum(self):
492 pos = dict(lineno=2, col_offset=3)
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300493 m = ast.Module([ast.Expr(ast.expr(**pos), **pos)])
Benjamin Peterson5b066812010-11-20 01:38:49 +0000494 with self.assertRaises(TypeError) as cm:
495 compile(m, "<test>", "exec")
496 self.assertIn("but got <_ast.expr", str(cm.exception))
497
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500498 def test_invalid_identitifer(self):
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300499 m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))])
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500500 ast.fix_missing_locations(m)
501 with self.assertRaises(TypeError) as cm:
502 compile(m, "<test>", "exec")
503 self.assertIn("identifier must be of type str", str(cm.exception))
504
Mark Dickinsonded35ae2012-11-25 14:36:26 +0000505 def test_empty_yield_from(self):
506 # Issue 16546: yield from value is not optional.
507 empty_yield_from = ast.parse("def f():\n yield from g()")
508 empty_yield_from.body[0].body[0].value.value = None
509 with self.assertRaises(ValueError) as cm:
510 compile(empty_yield_from, "<test>", "exec")
511 self.assertIn("field value is required", str(cm.exception))
512
Oren Milman7dc46d82017-09-30 20:16:24 +0300513 @support.cpython_only
514 def test_issue31592(self):
515 # There shouldn't be an assertion failure in case of a bad
516 # unicodedata.normalize().
517 import unicodedata
518 def bad_normalize(*args):
519 return None
520 with support.swap_attr(unicodedata, 'normalize', bad_normalize):
521 self.assertRaises(TypeError, ast.parse, '\u03D5')
522
Georg Brandl0c77a822008-06-10 16:37:50 +0000523
524class ASTHelpers_Test(unittest.TestCase):
525
526 def test_parse(self):
527 a = ast.parse('foo(1 + 1)')
528 b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST)
529 self.assertEqual(ast.dump(a), ast.dump(b))
530
Benjamin Peterson2e2c9032012-09-02 14:23:15 -0400531 def test_parse_in_error(self):
532 try:
533 1/0
534 except Exception:
Benjamin Petersonbd0df502012-09-02 15:04:51 -0400535 with self.assertRaises(SyntaxError) as e:
536 ast.literal_eval(r"'\U'")
537 self.assertIsNotNone(e.exception.__context__)
Benjamin Peterson2e2c9032012-09-02 14:23:15 -0400538
Georg Brandl0c77a822008-06-10 16:37:50 +0000539 def test_dump(self):
540 node = ast.parse('spam(eggs, "and cheese")')
541 self.assertEqual(ast.dump(node),
542 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300543 "args=[Name(id='eggs', ctx=Load()), Constant(value='and cheese')], "
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300544 "keywords=[]))])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000545 )
546 self.assertEqual(ast.dump(node, annotate_fields=False),
547 "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300548 "Constant('and cheese')], []))])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000549 )
550 self.assertEqual(ast.dump(node, include_attributes=True),
551 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
552 "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), "
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300553 "lineno=1, col_offset=5), Constant(value='and cheese', lineno=1, "
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400554 "col_offset=11)], keywords=[], "
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300555 "lineno=1, col_offset=0), lineno=1, col_offset=0)])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000556 )
557
558 def test_copy_location(self):
559 src = ast.parse('1 + 1', mode='eval')
560 src.body.right = ast.copy_location(ast.Num(2), src.body.right)
561 self.assertEqual(ast.dump(src, include_attributes=True),
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300562 'Expression(body=BinOp(left=Constant(value=1, lineno=1, col_offset=0), '
563 'op=Add(), right=Constant(value=2, lineno=1, col_offset=4), lineno=1, '
Georg Brandl0c77a822008-06-10 16:37:50 +0000564 'col_offset=0))'
565 )
566
567 def test_fix_missing_locations(self):
568 src = ast.parse('write("spam")')
569 src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()),
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400570 [ast.Str('eggs')], [])))
Georg Brandl0c77a822008-06-10 16:37:50 +0000571 self.assertEqual(src, ast.fix_missing_locations(src))
572 self.assertEqual(ast.dump(src, include_attributes=True),
573 "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), "
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300574 "lineno=1, col_offset=0), args=[Constant(value='spam', lineno=1, "
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400575 "col_offset=6)], keywords=[], "
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500576 "lineno=1, col_offset=0), lineno=1, col_offset=0), "
Georg Brandl0c77a822008-06-10 16:37:50 +0000577 "Expr(value=Call(func=Name(id='spam', ctx=Load(), lineno=1, "
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300578 "col_offset=0), args=[Constant(value='eggs', lineno=1, col_offset=0)], "
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400579 "keywords=[], lineno=1, "
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300580 "col_offset=0), lineno=1, col_offset=0)])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000581 )
582
583 def test_increment_lineno(self):
584 src = ast.parse('1 + 1', mode='eval')
585 self.assertEqual(ast.increment_lineno(src, n=3), src)
586 self.assertEqual(ast.dump(src, include_attributes=True),
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300587 'Expression(body=BinOp(left=Constant(value=1, lineno=4, col_offset=0), '
588 'op=Add(), right=Constant(value=1, lineno=4, col_offset=4), lineno=4, '
Georg Brandl0c77a822008-06-10 16:37:50 +0000589 'col_offset=0))'
590 )
Georg Brandl619e7ba2011-01-09 07:38:51 +0000591 # issue10869: do not increment lineno of root twice
Georg Brandlefb69022011-01-09 07:50:48 +0000592 src = ast.parse('1 + 1', mode='eval')
Georg Brandl619e7ba2011-01-09 07:38:51 +0000593 self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
594 self.assertEqual(ast.dump(src, include_attributes=True),
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300595 'Expression(body=BinOp(left=Constant(value=1, lineno=4, col_offset=0), '
596 'op=Add(), right=Constant(value=1, lineno=4, col_offset=4), lineno=4, '
Georg Brandl619e7ba2011-01-09 07:38:51 +0000597 'col_offset=0))'
598 )
Georg Brandl0c77a822008-06-10 16:37:50 +0000599
600 def test_iter_fields(self):
601 node = ast.parse('foo()', mode='eval')
602 d = dict(ast.iter_fields(node.body))
603 self.assertEqual(d.pop('func').id, 'foo')
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400604 self.assertEqual(d, {'keywords': [], 'args': []})
Georg Brandl0c77a822008-06-10 16:37:50 +0000605
606 def test_iter_child_nodes(self):
607 node = ast.parse("spam(23, 42, eggs='leek')", mode='eval')
608 self.assertEqual(len(list(ast.iter_child_nodes(node.body))), 4)
609 iterator = ast.iter_child_nodes(node.body)
610 self.assertEqual(next(iterator).id, 'spam')
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300611 self.assertEqual(next(iterator).value, 23)
612 self.assertEqual(next(iterator).value, 42)
Georg Brandl0c77a822008-06-10 16:37:50 +0000613 self.assertEqual(ast.dump(next(iterator)),
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300614 "keyword(arg='eggs', value=Constant(value='leek'))"
Georg Brandl0c77a822008-06-10 16:37:50 +0000615 )
616
617 def test_get_docstring(self):
Serhiy Storchaka08f127a2018-06-15 11:05:15 +0300618 node = ast.parse('"""line one\n line two"""')
619 self.assertEqual(ast.get_docstring(node),
620 'line one\nline two')
621
622 node = ast.parse('class foo:\n """line one\n line two"""')
623 self.assertEqual(ast.get_docstring(node.body[0]),
624 'line one\nline two')
625
Georg Brandl0c77a822008-06-10 16:37:50 +0000626 node = ast.parse('def foo():\n """line one\n line two"""')
627 self.assertEqual(ast.get_docstring(node.body[0]),
628 'line one\nline two')
629
Yury Selivanov2f07a662015-07-23 08:54:35 +0300630 node = ast.parse('async def foo():\n """spam\n ham"""')
631 self.assertEqual(ast.get_docstring(node.body[0]), 'spam\nham')
Serhiy Storchaka08f127a2018-06-15 11:05:15 +0300632
633 def test_get_docstring_none(self):
Matthias Bussonnier41cea702017-02-23 22:44:19 -0800634 self.assertIsNone(ast.get_docstring(ast.parse('')))
Serhiy Storchaka08f127a2018-06-15 11:05:15 +0300635 node = ast.parse('x = "not docstring"')
636 self.assertIsNone(ast.get_docstring(node))
637 node = ast.parse('def foo():\n pass')
638 self.assertIsNone(ast.get_docstring(node))
639
640 node = ast.parse('class foo:\n pass')
641 self.assertIsNone(ast.get_docstring(node.body[0]))
642 node = ast.parse('class foo:\n x = "not docstring"')
643 self.assertIsNone(ast.get_docstring(node.body[0]))
644 node = ast.parse('class foo:\n def bar(self): pass')
645 self.assertIsNone(ast.get_docstring(node.body[0]))
646
647 node = ast.parse('def foo():\n pass')
648 self.assertIsNone(ast.get_docstring(node.body[0]))
649 node = ast.parse('def foo():\n x = "not docstring"')
650 self.assertIsNone(ast.get_docstring(node.body[0]))
651
652 node = ast.parse('async def foo():\n pass')
653 self.assertIsNone(ast.get_docstring(node.body[0]))
654 node = ast.parse('async def foo():\n x = "not docstring"')
655 self.assertIsNone(ast.get_docstring(node.body[0]))
Yury Selivanov2f07a662015-07-23 08:54:35 +0300656
Georg Brandl0c77a822008-06-10 16:37:50 +0000657 def test_literal_eval(self):
658 self.assertEqual(ast.literal_eval('[1, 2, 3]'), [1, 2, 3])
659 self.assertEqual(ast.literal_eval('{"foo": 42}'), {"foo": 42})
660 self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None))
Benjamin Peterson3e742892010-07-11 12:59:24 +0000661 self.assertEqual(ast.literal_eval('{1, 2, 3}'), {1, 2, 3})
Benjamin Peterson5ef96e52010-07-11 23:06:06 +0000662 self.assertEqual(ast.literal_eval('b"hi"'), b"hi")
Georg Brandl0c77a822008-06-10 16:37:50 +0000663 self.assertRaises(ValueError, ast.literal_eval, 'foo()')
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +0200664 self.assertEqual(ast.literal_eval('6'), 6)
665 self.assertEqual(ast.literal_eval('+6'), 6)
Raymond Hettingerbc959732010-10-08 00:47:45 +0000666 self.assertEqual(ast.literal_eval('-6'), -6)
Raymond Hettingerbc959732010-10-08 00:47:45 +0000667 self.assertEqual(ast.literal_eval('3.25'), 3.25)
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +0200668 self.assertEqual(ast.literal_eval('+3.25'), 3.25)
669 self.assertEqual(ast.literal_eval('-3.25'), -3.25)
670 self.assertEqual(repr(ast.literal_eval('-0.0')), '-0.0')
671 self.assertRaises(ValueError, ast.literal_eval, '++6')
672 self.assertRaises(ValueError, ast.literal_eval, '+True')
673 self.assertRaises(ValueError, ast.literal_eval, '2+3')
Georg Brandl0c77a822008-06-10 16:37:50 +0000674
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +0200675 def test_literal_eval_complex(self):
676 # Issue #4907
677 self.assertEqual(ast.literal_eval('6j'), 6j)
678 self.assertEqual(ast.literal_eval('-6j'), -6j)
679 self.assertEqual(ast.literal_eval('6.75j'), 6.75j)
680 self.assertEqual(ast.literal_eval('-6.75j'), -6.75j)
681 self.assertEqual(ast.literal_eval('3+6j'), 3+6j)
682 self.assertEqual(ast.literal_eval('-3+6j'), -3+6j)
683 self.assertEqual(ast.literal_eval('3-6j'), 3-6j)
684 self.assertEqual(ast.literal_eval('-3-6j'), -3-6j)
685 self.assertEqual(ast.literal_eval('3.25+6.75j'), 3.25+6.75j)
686 self.assertEqual(ast.literal_eval('-3.25+6.75j'), -3.25+6.75j)
687 self.assertEqual(ast.literal_eval('3.25-6.75j'), 3.25-6.75j)
688 self.assertEqual(ast.literal_eval('-3.25-6.75j'), -3.25-6.75j)
689 self.assertEqual(ast.literal_eval('(3+6j)'), 3+6j)
690 self.assertRaises(ValueError, ast.literal_eval, '-6j+3')
691 self.assertRaises(ValueError, ast.literal_eval, '-6j+3j')
692 self.assertRaises(ValueError, ast.literal_eval, '3+-6j')
693 self.assertRaises(ValueError, ast.literal_eval, '3+(0+6j)')
694 self.assertRaises(ValueError, ast.literal_eval, '-(3+6j)')
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000695
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100696 def test_bad_integer(self):
697 # issue13436: Bad error message with invalid numeric values
698 body = [ast.ImportFrom(module='time',
699 names=[ast.alias(name='sleep')],
700 level=None,
701 lineno=None, col_offset=None)]
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300702 mod = ast.Module(body)
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100703 with self.assertRaises(ValueError) as cm:
704 compile(mod, 'test', 'exec')
705 self.assertIn("invalid integer value: None", str(cm.exception))
706
Berker Peksag0a5bd512016-04-29 19:50:02 +0300707 def test_level_as_none(self):
708 body = [ast.ImportFrom(module='time',
709 names=[ast.alias(name='sleep')],
710 level=None,
711 lineno=0, col_offset=0)]
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300712 mod = ast.Module(body)
Berker Peksag0a5bd512016-04-29 19:50:02 +0300713 code = compile(mod, 'test', 'exec')
714 ns = {}
715 exec(code, ns)
716 self.assertIn('sleep', ns)
717
Georg Brandl0c77a822008-06-10 16:37:50 +0000718
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500719class ASTValidatorTests(unittest.TestCase):
720
721 def mod(self, mod, msg=None, mode="exec", *, exc=ValueError):
722 mod.lineno = mod.col_offset = 0
723 ast.fix_missing_locations(mod)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300724 if msg is None:
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500725 compile(mod, "<test>", mode)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300726 else:
727 with self.assertRaises(exc) as cm:
728 compile(mod, "<test>", mode)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500729 self.assertIn(msg, str(cm.exception))
730
731 def expr(self, node, msg=None, *, exc=ValueError):
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300732 mod = ast.Module([ast.Expr(node)])
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500733 self.mod(mod, msg, exc=exc)
734
735 def stmt(self, stmt, msg=None):
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300736 mod = ast.Module([stmt])
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500737 self.mod(mod, msg)
738
739 def test_module(self):
740 m = ast.Interactive([ast.Expr(ast.Name("x", ast.Store()))])
741 self.mod(m, "must have Load context", "single")
742 m = ast.Expression(ast.Name("x", ast.Store()))
743 self.mod(m, "must have Load context", "eval")
744
745 def _check_arguments(self, fac, check):
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700746 def arguments(args=None, vararg=None,
747 kwonlyargs=None, kwarg=None,
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500748 defaults=None, kw_defaults=None):
749 if args is None:
750 args = []
751 if kwonlyargs is None:
752 kwonlyargs = []
753 if defaults is None:
754 defaults = []
755 if kw_defaults is None:
756 kw_defaults = []
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700757 args = ast.arguments(args, vararg, kwonlyargs, kw_defaults,
758 kwarg, defaults)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500759 return fac(args)
760 args = [ast.arg("x", ast.Name("x", ast.Store()))]
761 check(arguments(args=args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500762 check(arguments(kwonlyargs=args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500763 check(arguments(defaults=[ast.Num(3)]),
764 "more positional defaults than args")
765 check(arguments(kw_defaults=[ast.Num(4)]),
766 "length of kwonlyargs is not the same as kw_defaults")
767 args = [ast.arg("x", ast.Name("x", ast.Load()))]
768 check(arguments(args=args, defaults=[ast.Name("x", ast.Store())]),
769 "must have Load context")
770 args = [ast.arg("a", ast.Name("x", ast.Load())),
771 ast.arg("b", ast.Name("y", ast.Load()))]
772 check(arguments(kwonlyargs=args,
773 kw_defaults=[None, ast.Name("x", ast.Store())]),
774 "must have Load context")
775
776 def test_funcdef(self):
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700777 a = ast.arguments([], None, [], [], None, [])
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300778 f = ast.FunctionDef("x", a, [], [], None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500779 self.stmt(f, "empty body on FunctionDef")
780 f = ast.FunctionDef("x", a, [ast.Pass()], [ast.Name("x", ast.Store())],
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300781 None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500782 self.stmt(f, "must have Load context")
783 f = ast.FunctionDef("x", a, [ast.Pass()], [],
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300784 ast.Name("x", ast.Store()))
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500785 self.stmt(f, "must have Load context")
786 def fac(args):
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300787 return ast.FunctionDef("x", args, [ast.Pass()], [], None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500788 self._check_arguments(fac, self.stmt)
789
790 def test_classdef(self):
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400791 def cls(bases=None, keywords=None, body=None, decorator_list=None):
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500792 if bases is None:
793 bases = []
794 if keywords is None:
795 keywords = []
796 if body is None:
797 body = [ast.Pass()]
798 if decorator_list is None:
799 decorator_list = []
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400800 return ast.ClassDef("myclass", bases, keywords,
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300801 body, decorator_list)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500802 self.stmt(cls(bases=[ast.Name("x", ast.Store())]),
803 "must have Load context")
804 self.stmt(cls(keywords=[ast.keyword("x", ast.Name("x", ast.Store()))]),
805 "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500806 self.stmt(cls(body=[]), "empty body on ClassDef")
807 self.stmt(cls(body=[None]), "None disallowed")
808 self.stmt(cls(decorator_list=[ast.Name("x", ast.Store())]),
809 "must have Load context")
810
811 def test_delete(self):
812 self.stmt(ast.Delete([]), "empty targets on Delete")
813 self.stmt(ast.Delete([None]), "None disallowed")
814 self.stmt(ast.Delete([ast.Name("x", ast.Load())]),
815 "must have Del context")
816
817 def test_assign(self):
818 self.stmt(ast.Assign([], ast.Num(3)), "empty targets on Assign")
819 self.stmt(ast.Assign([None], ast.Num(3)), "None disallowed")
820 self.stmt(ast.Assign([ast.Name("x", ast.Load())], ast.Num(3)),
821 "must have Store context")
822 self.stmt(ast.Assign([ast.Name("x", ast.Store())],
823 ast.Name("y", ast.Store())),
824 "must have Load context")
825
826 def test_augassign(self):
827 aug = ast.AugAssign(ast.Name("x", ast.Load()), ast.Add(),
828 ast.Name("y", ast.Load()))
829 self.stmt(aug, "must have Store context")
830 aug = ast.AugAssign(ast.Name("x", ast.Store()), ast.Add(),
831 ast.Name("y", ast.Store()))
832 self.stmt(aug, "must have Load context")
833
834 def test_for(self):
835 x = ast.Name("x", ast.Store())
836 y = ast.Name("y", ast.Load())
837 p = ast.Pass()
838 self.stmt(ast.For(x, y, [], []), "empty body on For")
839 self.stmt(ast.For(ast.Name("x", ast.Load()), y, [p], []),
840 "must have Store context")
841 self.stmt(ast.For(x, ast.Name("y", ast.Store()), [p], []),
842 "must have Load context")
843 e = ast.Expr(ast.Name("x", ast.Store()))
844 self.stmt(ast.For(x, y, [e], []), "must have Load context")
845 self.stmt(ast.For(x, y, [p], [e]), "must have Load context")
846
847 def test_while(self):
848 self.stmt(ast.While(ast.Num(3), [], []), "empty body on While")
849 self.stmt(ast.While(ast.Name("x", ast.Store()), [ast.Pass()], []),
850 "must have Load context")
851 self.stmt(ast.While(ast.Num(3), [ast.Pass()],
852 [ast.Expr(ast.Name("x", ast.Store()))]),
853 "must have Load context")
854
855 def test_if(self):
856 self.stmt(ast.If(ast.Num(3), [], []), "empty body on If")
857 i = ast.If(ast.Name("x", ast.Store()), [ast.Pass()], [])
858 self.stmt(i, "must have Load context")
859 i = ast.If(ast.Num(3), [ast.Expr(ast.Name("x", ast.Store()))], [])
860 self.stmt(i, "must have Load context")
861 i = ast.If(ast.Num(3), [ast.Pass()],
862 [ast.Expr(ast.Name("x", ast.Store()))])
863 self.stmt(i, "must have Load context")
864
865 def test_with(self):
866 p = ast.Pass()
867 self.stmt(ast.With([], [p]), "empty items on With")
868 i = ast.withitem(ast.Num(3), None)
869 self.stmt(ast.With([i], []), "empty body on With")
870 i = ast.withitem(ast.Name("x", ast.Store()), None)
871 self.stmt(ast.With([i], [p]), "must have Load context")
872 i = ast.withitem(ast.Num(3), ast.Name("x", ast.Load()))
873 self.stmt(ast.With([i], [p]), "must have Store context")
874
875 def test_raise(self):
876 r = ast.Raise(None, ast.Num(3))
877 self.stmt(r, "Raise with cause but no exception")
878 r = ast.Raise(ast.Name("x", ast.Store()), None)
879 self.stmt(r, "must have Load context")
880 r = ast.Raise(ast.Num(4), ast.Name("x", ast.Store()))
881 self.stmt(r, "must have Load context")
882
883 def test_try(self):
884 p = ast.Pass()
885 t = ast.Try([], [], [], [p])
886 self.stmt(t, "empty body on Try")
887 t = ast.Try([ast.Expr(ast.Name("x", ast.Store()))], [], [], [p])
888 self.stmt(t, "must have Load context")
889 t = ast.Try([p], [], [], [])
890 self.stmt(t, "Try has neither except handlers nor finalbody")
891 t = ast.Try([p], [], [p], [p])
892 self.stmt(t, "Try has orelse but no except handlers")
893 t = ast.Try([p], [ast.ExceptHandler(None, "x", [])], [], [])
894 self.stmt(t, "empty body on ExceptHandler")
895 e = [ast.ExceptHandler(ast.Name("x", ast.Store()), "y", [p])]
896 self.stmt(ast.Try([p], e, [], []), "must have Load context")
897 e = [ast.ExceptHandler(None, "x", [p])]
898 t = ast.Try([p], e, [ast.Expr(ast.Name("x", ast.Store()))], [p])
899 self.stmt(t, "must have Load context")
900 t = ast.Try([p], e, [p], [ast.Expr(ast.Name("x", ast.Store()))])
901 self.stmt(t, "must have Load context")
902
903 def test_assert(self):
904 self.stmt(ast.Assert(ast.Name("x", ast.Store()), None),
905 "must have Load context")
906 assrt = ast.Assert(ast.Name("x", ast.Load()),
907 ast.Name("y", ast.Store()))
908 self.stmt(assrt, "must have Load context")
909
910 def test_import(self):
911 self.stmt(ast.Import([]), "empty names on Import")
912
913 def test_importfrom(self):
914 imp = ast.ImportFrom(None, [ast.alias("x", None)], -42)
Serhiy Storchaka7de28402016-06-27 23:40:43 +0300915 self.stmt(imp, "Negative ImportFrom level")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500916 self.stmt(ast.ImportFrom(None, [], 0), "empty names on ImportFrom")
917
918 def test_global(self):
919 self.stmt(ast.Global([]), "empty names on Global")
920
921 def test_nonlocal(self):
922 self.stmt(ast.Nonlocal([]), "empty names on Nonlocal")
923
924 def test_expr(self):
925 e = ast.Expr(ast.Name("x", ast.Store()))
926 self.stmt(e, "must have Load context")
927
928 def test_boolop(self):
929 b = ast.BoolOp(ast.And(), [])
930 self.expr(b, "less than 2 values")
931 b = ast.BoolOp(ast.And(), [ast.Num(3)])
932 self.expr(b, "less than 2 values")
933 b = ast.BoolOp(ast.And(), [ast.Num(4), None])
934 self.expr(b, "None disallowed")
935 b = ast.BoolOp(ast.And(), [ast.Num(4), ast.Name("x", ast.Store())])
936 self.expr(b, "must have Load context")
937
938 def test_unaryop(self):
939 u = ast.UnaryOp(ast.Not(), ast.Name("x", ast.Store()))
940 self.expr(u, "must have Load context")
941
942 def test_lambda(self):
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700943 a = ast.arguments([], None, [], [], None, [])
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500944 self.expr(ast.Lambda(a, ast.Name("x", ast.Store())),
945 "must have Load context")
946 def fac(args):
947 return ast.Lambda(args, ast.Name("x", ast.Load()))
948 self._check_arguments(fac, self.expr)
949
950 def test_ifexp(self):
951 l = ast.Name("x", ast.Load())
952 s = ast.Name("y", ast.Store())
953 for args in (s, l, l), (l, s, l), (l, l, s):
Benjamin Peterson71ce8972011-08-09 16:17:12 -0500954 self.expr(ast.IfExp(*args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500955
956 def test_dict(self):
957 d = ast.Dict([], [ast.Name("x", ast.Load())])
958 self.expr(d, "same number of keys as values")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500959 d = ast.Dict([ast.Name("x", ast.Load())], [None])
960 self.expr(d, "None disallowed")
961
962 def test_set(self):
963 self.expr(ast.Set([None]), "None disallowed")
964 s = ast.Set([ast.Name("x", ast.Store())])
965 self.expr(s, "must have Load context")
966
967 def _check_comprehension(self, fac):
968 self.expr(fac([]), "comprehension with no generators")
969 g = ast.comprehension(ast.Name("x", ast.Load()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700970 ast.Name("x", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500971 self.expr(fac([g]), "must have Store context")
972 g = ast.comprehension(ast.Name("x", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700973 ast.Name("x", ast.Store()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500974 self.expr(fac([g]), "must have Load context")
975 x = ast.Name("x", ast.Store())
976 y = ast.Name("y", ast.Load())
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700977 g = ast.comprehension(x, y, [None], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500978 self.expr(fac([g]), "None disallowed")
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700979 g = ast.comprehension(x, y, [ast.Name("x", ast.Store())], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500980 self.expr(fac([g]), "must have Load context")
981
982 def _simple_comp(self, fac):
983 g = ast.comprehension(ast.Name("x", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700984 ast.Name("x", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500985 self.expr(fac(ast.Name("x", ast.Store()), [g]),
986 "must have Load context")
987 def wrap(gens):
988 return fac(ast.Name("x", ast.Store()), gens)
989 self._check_comprehension(wrap)
990
991 def test_listcomp(self):
992 self._simple_comp(ast.ListComp)
993
994 def test_setcomp(self):
995 self._simple_comp(ast.SetComp)
996
997 def test_generatorexp(self):
998 self._simple_comp(ast.GeneratorExp)
999
1000 def test_dictcomp(self):
1001 g = ast.comprehension(ast.Name("y", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001002 ast.Name("p", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001003 c = ast.DictComp(ast.Name("x", ast.Store()),
1004 ast.Name("y", ast.Load()), [g])
1005 self.expr(c, "must have Load context")
1006 c = ast.DictComp(ast.Name("x", ast.Load()),
1007 ast.Name("y", ast.Store()), [g])
1008 self.expr(c, "must have Load context")
1009 def factory(comps):
1010 k = ast.Name("x", ast.Load())
1011 v = ast.Name("y", ast.Load())
1012 return ast.DictComp(k, v, comps)
1013 self._check_comprehension(factory)
1014
1015 def test_yield(self):
Benjamin Peterson527c6222012-01-14 08:58:23 -05001016 self.expr(ast.Yield(ast.Name("x", ast.Store())), "must have Load")
1017 self.expr(ast.YieldFrom(ast.Name("x", ast.Store())), "must have Load")
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001018
1019 def test_compare(self):
1020 left = ast.Name("x", ast.Load())
1021 comp = ast.Compare(left, [ast.In()], [])
1022 self.expr(comp, "no comparators")
1023 comp = ast.Compare(left, [ast.In()], [ast.Num(4), ast.Num(5)])
1024 self.expr(comp, "different number of comparators and operands")
1025 comp = ast.Compare(ast.Num("blah"), [ast.In()], [left])
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001026 self.expr(comp)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001027 comp = ast.Compare(left, [ast.In()], [ast.Num("blah")])
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001028 self.expr(comp)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001029
1030 def test_call(self):
1031 func = ast.Name("x", ast.Load())
1032 args = [ast.Name("y", ast.Load())]
1033 keywords = [ast.keyword("w", ast.Name("z", ast.Load()))]
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001034 call = ast.Call(ast.Name("x", ast.Store()), args, keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001035 self.expr(call, "must have Load context")
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001036 call = ast.Call(func, [None], keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001037 self.expr(call, "None disallowed")
1038 bad_keywords = [ast.keyword("w", ast.Name("z", ast.Store()))]
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001039 call = ast.Call(func, args, bad_keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001040 self.expr(call, "must have Load context")
1041
1042 def test_num(self):
1043 class subint(int):
1044 pass
1045 class subfloat(float):
1046 pass
1047 class subcomplex(complex):
1048 pass
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001049 for obj in "0", "hello":
1050 self.expr(ast.Num(obj))
1051 for obj in subint(), subfloat(), subcomplex():
1052 self.expr(ast.Num(obj), "invalid type", exc=TypeError)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001053
1054 def test_attribute(self):
1055 attr = ast.Attribute(ast.Name("x", ast.Store()), "y", ast.Load())
1056 self.expr(attr, "must have Load context")
1057
1058 def test_subscript(self):
1059 sub = ast.Subscript(ast.Name("x", ast.Store()), ast.Index(ast.Num(3)),
1060 ast.Load())
1061 self.expr(sub, "must have Load context")
1062 x = ast.Name("x", ast.Load())
1063 sub = ast.Subscript(x, ast.Index(ast.Name("y", ast.Store())),
1064 ast.Load())
1065 self.expr(sub, "must have Load context")
1066 s = ast.Name("x", ast.Store())
1067 for args in (s, None, None), (None, s, None), (None, None, s):
1068 sl = ast.Slice(*args)
1069 self.expr(ast.Subscript(x, sl, ast.Load()),
1070 "must have Load context")
1071 sl = ast.ExtSlice([])
1072 self.expr(ast.Subscript(x, sl, ast.Load()), "empty dims on ExtSlice")
1073 sl = ast.ExtSlice([ast.Index(s)])
1074 self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context")
1075
1076 def test_starred(self):
1077 left = ast.List([ast.Starred(ast.Name("x", ast.Load()), ast.Store())],
1078 ast.Store())
1079 assign = ast.Assign([left], ast.Num(4))
1080 self.stmt(assign, "must have Store context")
1081
1082 def _sequence(self, fac):
1083 self.expr(fac([None], ast.Load()), "None disallowed")
1084 self.expr(fac([ast.Name("x", ast.Store())], ast.Load()),
1085 "must have Load context")
1086
1087 def test_list(self):
1088 self._sequence(ast.List)
1089
1090 def test_tuple(self):
1091 self._sequence(ast.Tuple)
1092
Benjamin Peterson442f2092012-12-06 17:41:04 -05001093 def test_nameconstant(self):
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001094 self.expr(ast.NameConstant(4))
Benjamin Peterson442f2092012-12-06 17:41:04 -05001095
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001096 def test_stdlib_validates(self):
1097 stdlib = os.path.dirname(ast.__file__)
1098 tests = [fn for fn in os.listdir(stdlib) if fn.endswith(".py")]
1099 tests.extend(["test/test_grammar.py", "test/test_unpack_ex.py"])
1100 for module in tests:
1101 fn = os.path.join(stdlib, module)
1102 with open(fn, "r", encoding="utf-8") as fp:
1103 source = fp.read()
Victor Stinnerd502a072013-03-22 00:06:20 +01001104 mod = ast.parse(source, fn)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001105 compile(mod, fn, "exec")
1106
1107
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001108class ConstantTests(unittest.TestCase):
1109 """Tests on the ast.Constant node type."""
1110
1111 def compile_constant(self, value):
1112 tree = ast.parse("x = 123")
1113
1114 node = tree.body[0].value
1115 new_node = ast.Constant(value=value)
1116 ast.copy_location(new_node, node)
1117 tree.body[0].value = new_node
1118
1119 code = compile(tree, "<string>", "exec")
1120
1121 ns = {}
1122 exec(code, ns)
1123 return ns['x']
1124
Victor Stinnerbe59d142016-01-27 00:39:12 +01001125 def test_validation(self):
1126 with self.assertRaises(TypeError) as cm:
1127 self.compile_constant([1, 2, 3])
1128 self.assertEqual(str(cm.exception),
1129 "got an invalid type in Constant: list")
1130
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001131 def test_singletons(self):
1132 for const in (None, False, True, Ellipsis, b'', frozenset()):
1133 with self.subTest(const=const):
1134 value = self.compile_constant(const)
1135 self.assertIs(value, const)
1136
1137 def test_values(self):
1138 nested_tuple = (1,)
1139 nested_frozenset = frozenset({1})
1140 for level in range(3):
1141 nested_tuple = (nested_tuple, 2)
1142 nested_frozenset = frozenset({nested_frozenset, 2})
1143 values = (123, 123.0, 123j,
1144 "unicode", b'bytes',
1145 tuple("tuple"), frozenset("frozenset"),
1146 nested_tuple, nested_frozenset)
1147 for value in values:
1148 with self.subTest(value=value):
1149 result = self.compile_constant(value)
1150 self.assertEqual(result, value)
1151
1152 def test_assign_to_constant(self):
1153 tree = ast.parse("x = 1")
1154
1155 target = tree.body[0].targets[0]
1156 new_target = ast.Constant(value=1)
1157 ast.copy_location(new_target, target)
1158 tree.body[0].targets[0] = new_target
1159
1160 with self.assertRaises(ValueError) as cm:
1161 compile(tree, "string", "exec")
1162 self.assertEqual(str(cm.exception),
1163 "expression which can't be assigned "
1164 "to in Store context")
1165
1166 def test_get_docstring(self):
1167 tree = ast.parse("'docstring'\nx = 1")
1168 self.assertEqual(ast.get_docstring(tree), 'docstring')
1169
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001170 def get_load_const(self, tree):
1171 # Compile to bytecode, disassemble and get parameter of LOAD_CONST
1172 # instructions
1173 co = compile(tree, '<string>', 'exec')
1174 consts = []
1175 for instr in dis.get_instructions(co):
1176 if instr.opname == 'LOAD_CONST':
1177 consts.append(instr.argval)
1178 return consts
1179
1180 @support.cpython_only
1181 def test_load_const(self):
1182 consts = [None,
1183 True, False,
1184 124,
1185 2.0,
1186 3j,
1187 "unicode",
1188 b'bytes',
1189 (1, 2, 3)]
1190
Victor Stinnera2724092016-02-08 18:17:58 +01001191 code = '\n'.join(['x={!r}'.format(const) for const in consts])
1192 code += '\nx = ...'
1193 consts.extend((Ellipsis, None))
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001194
1195 tree = ast.parse(code)
Victor Stinnera2724092016-02-08 18:17:58 +01001196 self.assertEqual(self.get_load_const(tree),
1197 consts)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001198
1199 # Replace expression nodes with constants
Victor Stinnera2724092016-02-08 18:17:58 +01001200 for assign, const in zip(tree.body, consts):
1201 assert isinstance(assign, ast.Assign), ast.dump(assign)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001202 new_node = ast.Constant(value=const)
Victor Stinnera2724092016-02-08 18:17:58 +01001203 ast.copy_location(new_node, assign.value)
1204 assign.value = new_node
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001205
Victor Stinnera2724092016-02-08 18:17:58 +01001206 self.assertEqual(self.get_load_const(tree),
1207 consts)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001208
1209 def test_literal_eval(self):
1210 tree = ast.parse("1 + 2")
1211 binop = tree.body[0].value
1212
1213 new_left = ast.Constant(value=10)
1214 ast.copy_location(new_left, binop.left)
1215 binop.left = new_left
1216
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +02001217 new_right = ast.Constant(value=20j)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001218 ast.copy_location(new_right, binop.right)
1219 binop.right = new_right
1220
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +02001221 self.assertEqual(ast.literal_eval(binop), 10+20j)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001222
1223
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001224def main():
1225 if __name__ != '__main__':
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001226 return
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001227 if sys.argv[1:] == ['-g']:
1228 for statements, kind in ((exec_tests, "exec"), (single_tests, "single"),
1229 (eval_tests, "eval")):
1230 print(kind+"_results = [")
Victor Stinnerf0891962016-02-08 17:15:21 +01001231 for statement in statements:
1232 tree = ast.parse(statement, "?", kind)
1233 print("%r," % (to_tuple(tree),))
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001234 print("]")
1235 print("main()")
1236 raise SystemExit
Brett Cannon3e9a9ae2013-06-12 21:25:59 -04001237 unittest.main()
Tim Peters400cbc32006-02-28 18:44:41 +00001238
1239#### EVERYTHING BELOW IS GENERATED #####
1240exec_results = [
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001241('Module', [('Expr', (1, 0), ('Constant', (1, 0), None))]),
1242('Module', [('Expr', (1, 0), ('Constant', (1, 0), 'module docstring'))]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001243('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [('Pass', (1, 9))], [], None)]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001244('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [('Expr', (1, 9), ('Constant', (1, 9), 'function docstring'))], [], None)]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001245('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None)], None, [], [], None, []), [('Pass', (1, 10))], [], None)]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001246('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 +03001247('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], ('arg', (1, 7), 'args', None), [], [], None, []), [('Pass', (1, 14))], [], None)]),
1248('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], ('arg', (1, 8), 'kwargs', None), []), [('Pass', (1, 17))], [], None)]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001249('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 +03001250('Module', [('ClassDef', (1, 0), 'C', [], [], [('Pass', (1, 8))], [])]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001251('Module', [('ClassDef', (1, 0), 'C', [], [], [('Expr', (1, 9), ('Constant', (1, 9), 'docstring for class C'))], [])]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001252('Module', [('ClassDef', (1, 0), 'C', [('Name', (1, 8), 'object', ('Load',))], [], [('Pass', (1, 17))], [])]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001253('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [('Return', (1, 8), ('Constant', (1, 15), 1))], [], None)]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001254('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001255('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Constant', (1, 4), 1))]),
1256('Module', [('AugAssign', (1, 0), ('Name', (1, 0), 'v', ('Store',)), ('Add',), ('Constant', (1, 5), 1))]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001257('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Pass', (1, 11))], [])]),
1258('Module', [('While', (1, 0), ('Name', (1, 6), 'v', ('Load',)), [('Pass', (1, 8))], [])]),
1259('Module', [('If', (1, 0), ('Name', (1, 3), 'v', ('Load',)), [('Pass', (1, 5))], [])]),
1260('Module', [('With', (1, 0), [('withitem', ('Name', (1, 5), 'x', ('Load',)), ('Name', (1, 10), 'y', ('Store',)))], [('Pass', (1, 13))])]),
1261('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 +03001262('Module', [('Raise', (1, 0), ('Call', (1, 6), ('Name', (1, 6), 'Exception', ('Load',)), [('Constant', (1, 16), 'string')], []), None)]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001263('Module', [('Try', (1, 0), [('Pass', (2, 2))], [('ExceptHandler', (3, 0), ('Name', (3, 7), 'Exception', ('Load',)), None, [('Pass', (4, 2))])], [], [])]),
1264('Module', [('Try', (1, 0), [('Pass', (2, 2))], [], [], [('Pass', (4, 2))])]),
1265('Module', [('Assert', (1, 0), ('Name', (1, 7), 'v', ('Load',)), None)]),
1266('Module', [('Import', (1, 0), [('alias', 'sys', None)])]),
1267('Module', [('ImportFrom', (1, 0), 'sys', [('alias', 'v', None)], 0)]),
1268('Module', [('Global', (1, 0), ['v'])]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001269('Module', [('Expr', (1, 0), ('Constant', (1, 0), 1))]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001270('Module', [('Pass', (1, 0))]),
1271('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Break', (1, 11))], [])]),
1272('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Continue', (1, 11))], [])]),
1273('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))], [])]),
1274('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)]))]),
1275('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)]))]),
1276('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)]))]),
1277('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)]))]),
1278('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)]))]),
1279('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)]))]),
1280('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)]))]),
1281('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 +03001282('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)]),
1283('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)]),
1284('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)]),
1285('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)]))]),
1286('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 -04001287('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)]),
Tim Peters400cbc32006-02-28 18:44:41 +00001288]
1289single_results = [
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001290('Interactive', [('Expr', (1, 0), ('BinOp', (1, 0), ('Constant', (1, 0), 1), ('Add',), ('Constant', (1, 2), 2)))]),
Tim Peters400cbc32006-02-28 18:44:41 +00001291]
1292eval_results = [
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001293('Expression', ('Constant', (1, 0), None)),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001294('Expression', ('BoolOp', (1, 0), ('And',), [('Name', (1, 0), 'a', ('Load',)), ('Name', (1, 6), 'b', ('Load',))])),
1295('Expression', ('BinOp', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Add',), ('Name', (1, 4), 'b', ('Load',)))),
1296('Expression', ('UnaryOp', (1, 0), ('Not',), ('Name', (1, 4), 'v', ('Load',)))),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001297('Expression', ('Lambda', (1, 0), ('arguments', [], None, [], [], None, []), ('Constant', (1, 7), None))),
1298('Expression', ('Dict', (1, 0), [('Constant', (1, 2), 1)], [('Constant', (1, 4), 2)])),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001299('Expression', ('Dict', (1, 0), [], [])),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001300('Expression', ('Set', (1, 0), [('Constant', (1, 1), None)])),
1301('Expression', ('Dict', (1, 0), [('Constant', (2, 6), 1)], [('Constant', (4, 10), 2)])),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001302('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)])),
1303('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 +03001304('Expression', ('Compare', (1, 0), ('Constant', (1, 0), 1), [('Lt',), ('Lt',)], [('Constant', (1, 4), 2), ('Constant', (1, 8), 3)])),
1305('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',)))])),
1306('Expression', ('Constant', (1, 0), 10)),
1307('Expression', ('Constant', (1, 0), 'string')),
Benjamin Peterson7a66fc22015-02-02 10:51:20 -05001308('Expression', ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',))),
1309('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 +00001310('Expression', ('Name', (1, 0), 'v', ('Load',))),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001311('Expression', ('List', (1, 0), [('Constant', (1, 1), 1), ('Constant', (1, 3), 2), ('Constant', (1, 5), 3)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001312('Expression', ('List', (1, 0), [], ('Load',))),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001313('Expression', ('Tuple', (1, 0), [('Constant', (1, 0), 1), ('Constant', (1, 2), 2), ('Constant', (1, 4), 3)], ('Load',))),
1314('Expression', ('Tuple', (1, 1), [('Constant', (1, 1), 1), ('Constant', (1, 3), 2), ('Constant', (1, 5), 3)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001315('Expression', ('Tuple', (1, 0), [], ('Load',))),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001316('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 +00001317]
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001318main()