blob: db9a6caf42f1d0e9ecb157eed8e70de597e5ba7e [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",
Serhiy Storchakab619b092018-11-27 09:40:29 +020058 "a,b = c",
59 "(a,b) = c",
60 "[a,b] = c",
Tim Peters400cbc32006-02-28 18:44:41 +000061 # AugAssign
62 "v += 1",
Tim Peters400cbc32006-02-28 18:44:41 +000063 # For
64 "for v in v:pass",
65 # While
66 "while v:pass",
67 # If
68 "if v:pass",
Benjamin Petersonaeabd5f2011-05-27 15:02:03 -050069 # With
70 "with x as y: pass",
71 "with x as y, z as q: pass",
Tim Peters400cbc32006-02-28 18:44:41 +000072 # Raise
Collin Winter828f04a2007-08-31 00:04:24 +000073 "raise Exception('string')",
Tim Peters400cbc32006-02-28 18:44:41 +000074 # TryExcept
75 "try:\n pass\nexcept Exception:\n pass",
76 # TryFinally
77 "try:\n pass\nfinally:\n pass",
78 # Assert
79 "assert v",
80 # Import
81 "import sys",
82 # ImportFrom
83 "from sys import v",
Tim Peters400cbc32006-02-28 18:44:41 +000084 # Global
85 "global v",
86 # Expr
87 "1",
88 # Pass,
89 "pass",
90 # Break
Yury Selivanovb3d53132015-09-01 16:10:49 -040091 "for v in v:break",
Tim Peters400cbc32006-02-28 18:44:41 +000092 # Continue
Yury Selivanovb3d53132015-09-01 16:10:49 -040093 "for v in v:continue",
Benjamin Peterson2e4b0e12009-09-11 22:36:20 +000094 # for statements with naked tuples (see http://bugs.python.org/issue6704)
95 "for a,b in c: pass",
Serhiy Storchakab619b092018-11-27 09:40:29 +020096 "for (a,b) in c: pass",
97 "for [a,b] in c: pass",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050098 # Multiline generator expression (test for .lineno & .col_offset)
99 """(
100 (
101 Aa
102 ,
103 Bb
104 )
105 for
106 Aa
107 ,
108 Bb in Cc
109 )""",
110 # dictcomp
111 "{a : b for w in x for m in p if g}",
112 # dictcomp with naked tuple
113 "{a : b for v,w in x}",
114 # setcomp
115 "{r for l in x if g}",
116 # setcomp with naked tuple
117 "{r for l,m in x}",
Yury Selivanov75445082015-05-11 22:57:16 -0400118 # AsyncFunctionDef
INADA Naokicb41b272017-02-23 00:31:59 +0900119 "async def f():\n 'async function'\n await something()",
Yury Selivanov75445082015-05-11 22:57:16 -0400120 # AsyncFor
121 "async def f():\n async for e in i: 1\n else: 2",
122 # AsyncWith
123 "async def f():\n async with a as b: 1",
Yury Selivanovb3d53132015-09-01 16:10:49 -0400124 # PEP 448: Additional Unpacking Generalizations
125 "{**{1:2}, 2:3}",
126 "{*{1, 2}, 3}",
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700127 # Asynchronous comprehensions
128 "async def f():\n [i async for b in c]",
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200129 # Decorated FunctionDef
130 "@deco1\n@deco2()\ndef f(): pass",
131 # Decorated AsyncFunctionDef
132 "@deco1\n@deco2()\nasync def f(): pass",
133 # Decorated ClassDef
134 "@deco1\n@deco2()\nclass C: pass",
Serhiy Storchakab619b092018-11-27 09:40:29 +0200135 # Decorator with generator argument
136 "@deco(a for a in b)\ndef f(): pass",
Tim Peters400cbc32006-02-28 18:44:41 +0000137]
138
139# These are compiled through "single"
140# because of overlap with "eval", it just tests what
141# can't be tested with "eval"
142single_tests = [
143 "1+2"
144]
145
146# These are compiled through "eval"
147# It should test all expressions
148eval_tests = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500149 # None
150 "None",
Tim Peters400cbc32006-02-28 18:44:41 +0000151 # BoolOp
152 "a and b",
153 # BinOp
154 "a + b",
155 # UnaryOp
156 "not v",
157 # Lambda
158 "lambda:None",
159 # Dict
160 "{ 1:2 }",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500161 # Empty dict
162 "{}",
163 # Set
164 "{None,}",
165 # Multiline dict (test for .lineno & .col_offset)
166 """{
167 1
168 :
169 2
170 }""",
Tim Peters400cbc32006-02-28 18:44:41 +0000171 # ListComp
172 "[a for b in c if d]",
173 # GeneratorExp
174 "(a for b in c if d)",
Serhiy Storchakab619b092018-11-27 09:40:29 +0200175 # Comprehensions with multiple for targets
176 "[(a,b) for a,b in c]",
177 "[(a,b) for (a,b) in c]",
178 "[(a,b) for [a,b] in c]",
179 "{(a,b) for a,b in c}",
180 "{(a,b) for (a,b) in c}",
181 "{(a,b) for [a,b] in c}",
182 "((a,b) for a,b in c)",
183 "((a,b) for (a,b) in c)",
184 "((a,b) for [a,b] in c)",
Tim Peters400cbc32006-02-28 18:44:41 +0000185 # Yield - yield expressions can't work outside a function
186 #
187 # Compare
188 "1 < 2 < 3",
189 # Call
190 "f(1,2,c=3,*d,**e)",
Serhiy Storchakab619b092018-11-27 09:40:29 +0200191 # Call with a generator argument
192 "f(a for a in b)",
Tim Peters400cbc32006-02-28 18:44:41 +0000193 # Num
Guido van Rossume2a383d2007-01-15 16:59:06 +0000194 "10",
Tim Peters400cbc32006-02-28 18:44:41 +0000195 # Str
196 "'string'",
197 # Attribute
198 "a.b",
199 # Subscript
200 "a[b:c]",
201 # Name
202 "v",
203 # List
204 "[1,2,3]",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500205 # Empty list
206 "[]",
Tim Peters400cbc32006-02-28 18:44:41 +0000207 # Tuple
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000208 "1,2,3",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500209 # Tuple
210 "(1,2,3)",
211 # Empty tuple
212 "()",
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000213 # Combination
214 "a.b.c.d(a.b[1:2])",
215
Tim Peters400cbc32006-02-28 18:44:41 +0000216]
217
218# TODO: expr_context, slice, boolop, operator, unaryop, cmpop, comprehension
219# excepthandler, arguments, keywords, alias
220
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000221class AST_Tests(unittest.TestCase):
Tim Peters400cbc32006-02-28 18:44:41 +0000222
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500223 def _assertTrueorder(self, ast_node, parent_pos):
Georg Brandl0c77a822008-06-10 16:37:50 +0000224 if not isinstance(ast_node, ast.AST) or ast_node._fields is None:
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000225 return
Georg Brandl0c77a822008-06-10 16:37:50 +0000226 if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000227 node_pos = (ast_node.lineno, ast_node.col_offset)
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200228 self.assertGreaterEqual(node_pos, parent_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000229 parent_pos = (ast_node.lineno, ast_node.col_offset)
230 for name in ast_node._fields:
231 value = getattr(ast_node, name)
232 if isinstance(value, list):
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200233 first_pos = parent_pos
234 if value and name == 'decorator_list':
235 first_pos = (value[0].lineno, value[0].col_offset)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000236 for child in value:
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200237 self._assertTrueorder(child, first_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000238 elif value is not None:
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500239 self._assertTrueorder(value, parent_pos)
Tim Peters5ddfe412006-03-01 23:02:57 +0000240
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500241 def test_AST_objects(self):
242 x = ast.AST()
243 self.assertEqual(x._fields, ())
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700244 x.foobar = 42
245 self.assertEqual(x.foobar, 42)
246 self.assertEqual(x.__dict__["foobar"], 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500247
248 with self.assertRaises(AttributeError):
249 x.vararg
250
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500251 with self.assertRaises(TypeError):
252 # "_ast.AST constructor takes 0 positional arguments"
253 ast.AST(2)
254
Benjamin Peterson9ed37432012-07-08 11:13:36 -0700255 def test_AST_garbage_collection(self):
256 class X:
257 pass
258 a = ast.AST()
259 a.x = X()
260 a.x.a = a
261 ref = weakref.ref(a.x)
262 del a
263 support.gc_collect()
264 self.assertIsNone(ref())
265
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000266 def test_snippets(self):
267 for input, output, kind in ((exec_tests, exec_results, "exec"),
268 (single_tests, single_results, "single"),
269 (eval_tests, eval_results, "eval")):
270 for i, o in zip(input, output):
Yury Selivanovb3d53132015-09-01 16:10:49 -0400271 with self.subTest(action="parsing", input=i):
272 ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST)
273 self.assertEqual(to_tuple(ast_tree), o)
274 self._assertTrueorder(ast_tree, (0, 0))
Victor Stinner15a30952016-02-08 22:45:06 +0100275 with self.subTest(action="compiling", input=i, kind=kind):
276 compile(ast_tree, "?", kind)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000277
Benjamin Peterson78565b22009-06-28 19:19:51 +0000278 def test_slice(self):
279 slc = ast.parse("x[::]").body[0].value.slice
280 self.assertIsNone(slc.upper)
281 self.assertIsNone(slc.lower)
282 self.assertIsNone(slc.step)
283
284 def test_from_import(self):
285 im = ast.parse("from . import y").body[0]
286 self.assertIsNone(im.module)
287
Benjamin Petersona4e4e352012-03-22 08:19:04 -0400288 def test_non_interned_future_from_ast(self):
289 mod = ast.parse("from __future__ import division")
290 self.assertIsInstance(mod.body[0], ast.ImportFrom)
291 mod.body[0].module = " __future__ ".strip()
292 compile(mod, "<test>", "exec")
293
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000294 def test_base_classes(self):
295 self.assertTrue(issubclass(ast.For, ast.stmt))
296 self.assertTrue(issubclass(ast.Name, ast.expr))
297 self.assertTrue(issubclass(ast.stmt, ast.AST))
298 self.assertTrue(issubclass(ast.expr, ast.AST))
299 self.assertTrue(issubclass(ast.comprehension, ast.AST))
300 self.assertTrue(issubclass(ast.Gt, ast.AST))
301
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500302 def test_field_attr_existence(self):
303 for name, item in ast.__dict__.items():
304 if isinstance(item, type) and name != 'AST' and name[0].isupper():
305 x = item()
306 if isinstance(x, ast.AST):
307 self.assertEqual(type(x._fields), tuple)
308
309 def test_arguments(self):
310 x = ast.arguments()
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500311 self.assertEqual(x._fields, ('args', 'vararg', 'kwonlyargs',
312 'kw_defaults', 'kwarg', 'defaults'))
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500313
314 with self.assertRaises(AttributeError):
315 x.vararg
316
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700317 x = ast.arguments(*range(1, 7))
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500318 self.assertEqual(x.vararg, 2)
319
320 def test_field_attr_writable(self):
321 x = ast.Num()
322 # We can assign to _fields
323 x._fields = 666
324 self.assertEqual(x._fields, 666)
325
326 def test_classattrs(self):
327 x = ast.Num()
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300328 self.assertEqual(x._fields, ('value',))
329
330 with self.assertRaises(AttributeError):
331 x.value
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500332
333 with self.assertRaises(AttributeError):
334 x.n
335
336 x = ast.Num(42)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300337 self.assertEqual(x.value, 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500338 self.assertEqual(x.n, 42)
339
340 with self.assertRaises(AttributeError):
341 x.lineno
342
343 with self.assertRaises(AttributeError):
344 x.foobar
345
346 x = ast.Num(lineno=2)
347 self.assertEqual(x.lineno, 2)
348
349 x = ast.Num(42, lineno=0)
350 self.assertEqual(x.lineno, 0)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300351 self.assertEqual(x._fields, ('value',))
352 self.assertEqual(x.value, 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500353 self.assertEqual(x.n, 42)
354
355 self.assertRaises(TypeError, ast.Num, 1, 2)
356 self.assertRaises(TypeError, ast.Num, 1, 2, lineno=0)
357
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300358 self.assertEqual(ast.Num(42).n, 42)
359 self.assertEqual(ast.Num(4.25).n, 4.25)
360 self.assertEqual(ast.Num(4.25j).n, 4.25j)
361 self.assertEqual(ast.Str('42').s, '42')
362 self.assertEqual(ast.Bytes(b'42').s, b'42')
363 self.assertIs(ast.NameConstant(True).value, True)
364 self.assertIs(ast.NameConstant(False).value, False)
365 self.assertIs(ast.NameConstant(None).value, None)
366
367 self.assertEqual(ast.Constant(42).value, 42)
368 self.assertEqual(ast.Constant(4.25).value, 4.25)
369 self.assertEqual(ast.Constant(4.25j).value, 4.25j)
370 self.assertEqual(ast.Constant('42').value, '42')
371 self.assertEqual(ast.Constant(b'42').value, b'42')
372 self.assertIs(ast.Constant(True).value, True)
373 self.assertIs(ast.Constant(False).value, False)
374 self.assertIs(ast.Constant(None).value, None)
375 self.assertIs(ast.Constant(...).value, ...)
376
377 def test_realtype(self):
378 self.assertEqual(type(ast.Num(42)), ast.Constant)
379 self.assertEqual(type(ast.Num(4.25)), ast.Constant)
380 self.assertEqual(type(ast.Num(4.25j)), ast.Constant)
381 self.assertEqual(type(ast.Str('42')), ast.Constant)
382 self.assertEqual(type(ast.Bytes(b'42')), ast.Constant)
383 self.assertEqual(type(ast.NameConstant(True)), ast.Constant)
384 self.assertEqual(type(ast.NameConstant(False)), ast.Constant)
385 self.assertEqual(type(ast.NameConstant(None)), ast.Constant)
386 self.assertEqual(type(ast.Ellipsis()), ast.Constant)
387
388 def test_isinstance(self):
389 self.assertTrue(isinstance(ast.Num(42), ast.Num))
390 self.assertTrue(isinstance(ast.Num(4.2), ast.Num))
391 self.assertTrue(isinstance(ast.Num(4.2j), ast.Num))
392 self.assertTrue(isinstance(ast.Str('42'), ast.Str))
393 self.assertTrue(isinstance(ast.Bytes(b'42'), ast.Bytes))
394 self.assertTrue(isinstance(ast.NameConstant(True), ast.NameConstant))
395 self.assertTrue(isinstance(ast.NameConstant(False), ast.NameConstant))
396 self.assertTrue(isinstance(ast.NameConstant(None), ast.NameConstant))
397 self.assertTrue(isinstance(ast.Ellipsis(), ast.Ellipsis))
398
399 self.assertTrue(isinstance(ast.Constant(42), ast.Num))
400 self.assertTrue(isinstance(ast.Constant(4.2), ast.Num))
401 self.assertTrue(isinstance(ast.Constant(4.2j), ast.Num))
402 self.assertTrue(isinstance(ast.Constant('42'), ast.Str))
403 self.assertTrue(isinstance(ast.Constant(b'42'), ast.Bytes))
404 self.assertTrue(isinstance(ast.Constant(True), ast.NameConstant))
405 self.assertTrue(isinstance(ast.Constant(False), ast.NameConstant))
406 self.assertTrue(isinstance(ast.Constant(None), ast.NameConstant))
407 self.assertTrue(isinstance(ast.Constant(...), ast.Ellipsis))
408
409 self.assertFalse(isinstance(ast.Str('42'), ast.Num))
410 self.assertFalse(isinstance(ast.Num(42), ast.Str))
411 self.assertFalse(isinstance(ast.Str('42'), ast.Bytes))
412 self.assertFalse(isinstance(ast.Num(42), ast.NameConstant))
413 self.assertFalse(isinstance(ast.Num(42), ast.Ellipsis))
414
415 self.assertFalse(isinstance(ast.Constant('42'), ast.Num))
416 self.assertFalse(isinstance(ast.Constant(42), ast.Str))
417 self.assertFalse(isinstance(ast.Constant('42'), ast.Bytes))
418 self.assertFalse(isinstance(ast.Constant(42), ast.NameConstant))
419 self.assertFalse(isinstance(ast.Constant(42), ast.Ellipsis))
420
421 self.assertFalse(isinstance(ast.Constant(), ast.Num))
422 self.assertFalse(isinstance(ast.Constant(), ast.Str))
423 self.assertFalse(isinstance(ast.Constant(), ast.Bytes))
424 self.assertFalse(isinstance(ast.Constant(), ast.NameConstant))
425 self.assertFalse(isinstance(ast.Constant(), ast.Ellipsis))
426
Serhiy Storchaka6015cc52018-10-28 13:43:03 +0200427 class S(str): pass
428 self.assertTrue(isinstance(ast.Constant(S('42')), ast.Str))
429 self.assertFalse(isinstance(ast.Constant(S('42')), ast.Num))
430
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300431 def test_subclasses(self):
432 class N(ast.Num):
433 def __init__(self, *args, **kwargs):
434 super().__init__(*args, **kwargs)
435 self.z = 'spam'
436 class N2(ast.Num):
437 pass
438
439 n = N(42)
440 self.assertEqual(n.n, 42)
441 self.assertEqual(n.z, 'spam')
442 self.assertEqual(type(n), N)
443 self.assertTrue(isinstance(n, N))
444 self.assertTrue(isinstance(n, ast.Num))
445 self.assertFalse(isinstance(n, N2))
446 self.assertFalse(isinstance(ast.Num(42), N))
447 n = N(n=42)
448 self.assertEqual(n.n, 42)
449 self.assertEqual(type(n), N)
450
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500451 def test_module(self):
452 body = [ast.Num(42)]
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300453 x = ast.Module(body)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500454 self.assertEqual(x.body, body)
455
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000456 def test_nodeclasses(self):
Florent Xicluna992d9e02011-11-11 19:35:42 +0100457 # Zero arguments constructor explicitly allowed
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500458 x = ast.BinOp()
459 self.assertEqual(x._fields, ('left', 'op', 'right'))
460
461 # Random attribute allowed too
462 x.foobarbaz = 5
463 self.assertEqual(x.foobarbaz, 5)
464
465 n1 = ast.Num(1)
466 n3 = ast.Num(3)
467 addop = ast.Add()
468 x = ast.BinOp(n1, addop, n3)
469 self.assertEqual(x.left, n1)
470 self.assertEqual(x.op, addop)
471 self.assertEqual(x.right, n3)
Benjamin Peterson68b543a2011-06-27 17:51:18 -0500472
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500473 x = ast.BinOp(1, 2, 3)
474 self.assertEqual(x.left, 1)
475 self.assertEqual(x.op, 2)
476 self.assertEqual(x.right, 3)
477
Georg Brandl0c77a822008-06-10 16:37:50 +0000478 x = ast.BinOp(1, 2, 3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000479 self.assertEqual(x.left, 1)
480 self.assertEqual(x.op, 2)
481 self.assertEqual(x.right, 3)
482 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000483
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500484 # node raises exception when given too many arguments
485 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500486 # node raises exception when given too many arguments
487 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4, lineno=0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000488
489 # can set attributes through kwargs too
Georg Brandl0c77a822008-06-10 16:37:50 +0000490 x = ast.BinOp(left=1, op=2, right=3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000491 self.assertEqual(x.left, 1)
492 self.assertEqual(x.op, 2)
493 self.assertEqual(x.right, 3)
494 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000495
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500496 # Random kwargs also allowed
497 x = ast.BinOp(1, 2, 3, foobarbaz=42)
498 self.assertEqual(x.foobarbaz, 42)
499
500 def test_no_fields(self):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000501 # this used to fail because Sub._fields was None
Georg Brandl0c77a822008-06-10 16:37:50 +0000502 x = ast.Sub()
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500503 self.assertEqual(x._fields, ())
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000504
505 def test_pickling(self):
506 import pickle
507 mods = [pickle]
508 try:
509 import cPickle
510 mods.append(cPickle)
511 except ImportError:
512 pass
513 protocols = [0, 1, 2]
514 for mod in mods:
515 for protocol in protocols:
516 for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests):
517 ast2 = mod.loads(mod.dumps(ast, protocol))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000518 self.assertEqual(to_tuple(ast2), to_tuple(ast))
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000519
Benjamin Peterson5b066812010-11-20 01:38:49 +0000520 def test_invalid_sum(self):
521 pos = dict(lineno=2, col_offset=3)
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300522 m = ast.Module([ast.Expr(ast.expr(**pos), **pos)])
Benjamin Peterson5b066812010-11-20 01:38:49 +0000523 with self.assertRaises(TypeError) as cm:
524 compile(m, "<test>", "exec")
525 self.assertIn("but got <_ast.expr", str(cm.exception))
526
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500527 def test_invalid_identitifer(self):
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300528 m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))])
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500529 ast.fix_missing_locations(m)
530 with self.assertRaises(TypeError) as cm:
531 compile(m, "<test>", "exec")
532 self.assertIn("identifier must be of type str", str(cm.exception))
533
Mark Dickinsonded35ae2012-11-25 14:36:26 +0000534 def test_empty_yield_from(self):
535 # Issue 16546: yield from value is not optional.
536 empty_yield_from = ast.parse("def f():\n yield from g()")
537 empty_yield_from.body[0].body[0].value.value = None
538 with self.assertRaises(ValueError) as cm:
539 compile(empty_yield_from, "<test>", "exec")
540 self.assertIn("field value is required", str(cm.exception))
541
Oren Milman7dc46d82017-09-30 20:16:24 +0300542 @support.cpython_only
543 def test_issue31592(self):
544 # There shouldn't be an assertion failure in case of a bad
545 # unicodedata.normalize().
546 import unicodedata
547 def bad_normalize(*args):
548 return None
549 with support.swap_attr(unicodedata, 'normalize', bad_normalize):
550 self.assertRaises(TypeError, ast.parse, '\u03D5')
551
Georg Brandl0c77a822008-06-10 16:37:50 +0000552
553class ASTHelpers_Test(unittest.TestCase):
554
555 def test_parse(self):
556 a = ast.parse('foo(1 + 1)')
557 b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST)
558 self.assertEqual(ast.dump(a), ast.dump(b))
559
Benjamin Peterson2e2c9032012-09-02 14:23:15 -0400560 def test_parse_in_error(self):
561 try:
562 1/0
563 except Exception:
Benjamin Petersonbd0df502012-09-02 15:04:51 -0400564 with self.assertRaises(SyntaxError) as e:
565 ast.literal_eval(r"'\U'")
566 self.assertIsNotNone(e.exception.__context__)
Benjamin Peterson2e2c9032012-09-02 14:23:15 -0400567
Georg Brandl0c77a822008-06-10 16:37:50 +0000568 def test_dump(self):
569 node = ast.parse('spam(eggs, "and cheese")')
570 self.assertEqual(ast.dump(node),
571 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300572 "args=[Name(id='eggs', ctx=Load()), Constant(value='and cheese')], "
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300573 "keywords=[]))])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000574 )
575 self.assertEqual(ast.dump(node, annotate_fields=False),
576 "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300577 "Constant('and cheese')], []))])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000578 )
579 self.assertEqual(ast.dump(node, include_attributes=True),
580 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
581 "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), "
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300582 "lineno=1, col_offset=5), Constant(value='and cheese', lineno=1, "
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400583 "col_offset=11)], keywords=[], "
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300584 "lineno=1, col_offset=0), lineno=1, col_offset=0)])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000585 )
586
587 def test_copy_location(self):
588 src = ast.parse('1 + 1', mode='eval')
589 src.body.right = ast.copy_location(ast.Num(2), src.body.right)
590 self.assertEqual(ast.dump(src, include_attributes=True),
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300591 'Expression(body=BinOp(left=Constant(value=1, lineno=1, col_offset=0), '
592 'op=Add(), right=Constant(value=2, lineno=1, col_offset=4), lineno=1, '
Georg Brandl0c77a822008-06-10 16:37:50 +0000593 'col_offset=0))'
594 )
595
596 def test_fix_missing_locations(self):
597 src = ast.parse('write("spam")')
598 src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()),
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400599 [ast.Str('eggs')], [])))
Georg Brandl0c77a822008-06-10 16:37:50 +0000600 self.assertEqual(src, ast.fix_missing_locations(src))
601 self.assertEqual(ast.dump(src, include_attributes=True),
602 "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), "
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300603 "lineno=1, col_offset=0), args=[Constant(value='spam', lineno=1, "
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400604 "col_offset=6)], keywords=[], "
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500605 "lineno=1, col_offset=0), lineno=1, col_offset=0), "
Georg Brandl0c77a822008-06-10 16:37:50 +0000606 "Expr(value=Call(func=Name(id='spam', ctx=Load(), lineno=1, "
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300607 "col_offset=0), args=[Constant(value='eggs', lineno=1, col_offset=0)], "
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400608 "keywords=[], lineno=1, "
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300609 "col_offset=0), lineno=1, col_offset=0)])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000610 )
611
612 def test_increment_lineno(self):
613 src = ast.parse('1 + 1', mode='eval')
614 self.assertEqual(ast.increment_lineno(src, n=3), src)
615 self.assertEqual(ast.dump(src, include_attributes=True),
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300616 'Expression(body=BinOp(left=Constant(value=1, lineno=4, col_offset=0), '
617 'op=Add(), right=Constant(value=1, lineno=4, col_offset=4), lineno=4, '
Georg Brandl0c77a822008-06-10 16:37:50 +0000618 'col_offset=0))'
619 )
Georg Brandl619e7ba2011-01-09 07:38:51 +0000620 # issue10869: do not increment lineno of root twice
Georg Brandlefb69022011-01-09 07:50:48 +0000621 src = ast.parse('1 + 1', mode='eval')
Georg Brandl619e7ba2011-01-09 07:38:51 +0000622 self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
623 self.assertEqual(ast.dump(src, include_attributes=True),
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300624 'Expression(body=BinOp(left=Constant(value=1, lineno=4, col_offset=0), '
625 'op=Add(), right=Constant(value=1, lineno=4, col_offset=4), lineno=4, '
Georg Brandl619e7ba2011-01-09 07:38:51 +0000626 'col_offset=0))'
627 )
Georg Brandl0c77a822008-06-10 16:37:50 +0000628
629 def test_iter_fields(self):
630 node = ast.parse('foo()', mode='eval')
631 d = dict(ast.iter_fields(node.body))
632 self.assertEqual(d.pop('func').id, 'foo')
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400633 self.assertEqual(d, {'keywords': [], 'args': []})
Georg Brandl0c77a822008-06-10 16:37:50 +0000634
635 def test_iter_child_nodes(self):
636 node = ast.parse("spam(23, 42, eggs='leek')", mode='eval')
637 self.assertEqual(len(list(ast.iter_child_nodes(node.body))), 4)
638 iterator = ast.iter_child_nodes(node.body)
639 self.assertEqual(next(iterator).id, 'spam')
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300640 self.assertEqual(next(iterator).value, 23)
641 self.assertEqual(next(iterator).value, 42)
Georg Brandl0c77a822008-06-10 16:37:50 +0000642 self.assertEqual(ast.dump(next(iterator)),
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300643 "keyword(arg='eggs', value=Constant(value='leek'))"
Georg Brandl0c77a822008-06-10 16:37:50 +0000644 )
645
646 def test_get_docstring(self):
Serhiy Storchaka08f127a2018-06-15 11:05:15 +0300647 node = ast.parse('"""line one\n line two"""')
648 self.assertEqual(ast.get_docstring(node),
649 'line one\nline two')
650
651 node = ast.parse('class foo:\n """line one\n line two"""')
652 self.assertEqual(ast.get_docstring(node.body[0]),
653 'line one\nline two')
654
Georg Brandl0c77a822008-06-10 16:37:50 +0000655 node = ast.parse('def foo():\n """line one\n line two"""')
656 self.assertEqual(ast.get_docstring(node.body[0]),
657 'line one\nline two')
658
Yury Selivanov2f07a662015-07-23 08:54:35 +0300659 node = ast.parse('async def foo():\n """spam\n ham"""')
660 self.assertEqual(ast.get_docstring(node.body[0]), 'spam\nham')
Serhiy Storchaka08f127a2018-06-15 11:05:15 +0300661
662 def test_get_docstring_none(self):
Matthias Bussonnier41cea702017-02-23 22:44:19 -0800663 self.assertIsNone(ast.get_docstring(ast.parse('')))
Serhiy Storchaka08f127a2018-06-15 11:05:15 +0300664 node = ast.parse('x = "not docstring"')
665 self.assertIsNone(ast.get_docstring(node))
666 node = ast.parse('def foo():\n pass')
667 self.assertIsNone(ast.get_docstring(node))
668
669 node = ast.parse('class foo:\n pass')
670 self.assertIsNone(ast.get_docstring(node.body[0]))
671 node = ast.parse('class foo:\n x = "not docstring"')
672 self.assertIsNone(ast.get_docstring(node.body[0]))
673 node = ast.parse('class foo:\n def bar(self): pass')
674 self.assertIsNone(ast.get_docstring(node.body[0]))
675
676 node = ast.parse('def foo():\n pass')
677 self.assertIsNone(ast.get_docstring(node.body[0]))
678 node = ast.parse('def foo():\n x = "not docstring"')
679 self.assertIsNone(ast.get_docstring(node.body[0]))
680
681 node = ast.parse('async def foo():\n pass')
682 self.assertIsNone(ast.get_docstring(node.body[0]))
683 node = ast.parse('async def foo():\n x = "not docstring"')
684 self.assertIsNone(ast.get_docstring(node.body[0]))
Yury Selivanov2f07a662015-07-23 08:54:35 +0300685
Georg Brandl0c77a822008-06-10 16:37:50 +0000686 def test_literal_eval(self):
687 self.assertEqual(ast.literal_eval('[1, 2, 3]'), [1, 2, 3])
688 self.assertEqual(ast.literal_eval('{"foo": 42}'), {"foo": 42})
689 self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None))
Benjamin Peterson3e742892010-07-11 12:59:24 +0000690 self.assertEqual(ast.literal_eval('{1, 2, 3}'), {1, 2, 3})
Benjamin Peterson5ef96e52010-07-11 23:06:06 +0000691 self.assertEqual(ast.literal_eval('b"hi"'), b"hi")
Georg Brandl0c77a822008-06-10 16:37:50 +0000692 self.assertRaises(ValueError, ast.literal_eval, 'foo()')
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +0200693 self.assertEqual(ast.literal_eval('6'), 6)
694 self.assertEqual(ast.literal_eval('+6'), 6)
Raymond Hettingerbc959732010-10-08 00:47:45 +0000695 self.assertEqual(ast.literal_eval('-6'), -6)
Raymond Hettingerbc959732010-10-08 00:47:45 +0000696 self.assertEqual(ast.literal_eval('3.25'), 3.25)
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +0200697 self.assertEqual(ast.literal_eval('+3.25'), 3.25)
698 self.assertEqual(ast.literal_eval('-3.25'), -3.25)
699 self.assertEqual(repr(ast.literal_eval('-0.0')), '-0.0')
700 self.assertRaises(ValueError, ast.literal_eval, '++6')
701 self.assertRaises(ValueError, ast.literal_eval, '+True')
702 self.assertRaises(ValueError, ast.literal_eval, '2+3')
Georg Brandl0c77a822008-06-10 16:37:50 +0000703
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +0200704 def test_literal_eval_complex(self):
705 # Issue #4907
706 self.assertEqual(ast.literal_eval('6j'), 6j)
707 self.assertEqual(ast.literal_eval('-6j'), -6j)
708 self.assertEqual(ast.literal_eval('6.75j'), 6.75j)
709 self.assertEqual(ast.literal_eval('-6.75j'), -6.75j)
710 self.assertEqual(ast.literal_eval('3+6j'), 3+6j)
711 self.assertEqual(ast.literal_eval('-3+6j'), -3+6j)
712 self.assertEqual(ast.literal_eval('3-6j'), 3-6j)
713 self.assertEqual(ast.literal_eval('-3-6j'), -3-6j)
714 self.assertEqual(ast.literal_eval('3.25+6.75j'), 3.25+6.75j)
715 self.assertEqual(ast.literal_eval('-3.25+6.75j'), -3.25+6.75j)
716 self.assertEqual(ast.literal_eval('3.25-6.75j'), 3.25-6.75j)
717 self.assertEqual(ast.literal_eval('-3.25-6.75j'), -3.25-6.75j)
718 self.assertEqual(ast.literal_eval('(3+6j)'), 3+6j)
719 self.assertRaises(ValueError, ast.literal_eval, '-6j+3')
720 self.assertRaises(ValueError, ast.literal_eval, '-6j+3j')
721 self.assertRaises(ValueError, ast.literal_eval, '3+-6j')
722 self.assertRaises(ValueError, ast.literal_eval, '3+(0+6j)')
723 self.assertRaises(ValueError, ast.literal_eval, '-(3+6j)')
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000724
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100725 def test_bad_integer(self):
726 # issue13436: Bad error message with invalid numeric values
727 body = [ast.ImportFrom(module='time',
728 names=[ast.alias(name='sleep')],
729 level=None,
730 lineno=None, col_offset=None)]
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300731 mod = ast.Module(body)
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100732 with self.assertRaises(ValueError) as cm:
733 compile(mod, 'test', 'exec')
734 self.assertIn("invalid integer value: None", str(cm.exception))
735
Berker Peksag0a5bd512016-04-29 19:50:02 +0300736 def test_level_as_none(self):
737 body = [ast.ImportFrom(module='time',
738 names=[ast.alias(name='sleep')],
739 level=None,
740 lineno=0, col_offset=0)]
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300741 mod = ast.Module(body)
Berker Peksag0a5bd512016-04-29 19:50:02 +0300742 code = compile(mod, 'test', 'exec')
743 ns = {}
744 exec(code, ns)
745 self.assertIn('sleep', ns)
746
Georg Brandl0c77a822008-06-10 16:37:50 +0000747
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500748class ASTValidatorTests(unittest.TestCase):
749
750 def mod(self, mod, msg=None, mode="exec", *, exc=ValueError):
751 mod.lineno = mod.col_offset = 0
752 ast.fix_missing_locations(mod)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300753 if msg is None:
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500754 compile(mod, "<test>", mode)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300755 else:
756 with self.assertRaises(exc) as cm:
757 compile(mod, "<test>", mode)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500758 self.assertIn(msg, str(cm.exception))
759
760 def expr(self, node, msg=None, *, exc=ValueError):
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300761 mod = ast.Module([ast.Expr(node)])
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500762 self.mod(mod, msg, exc=exc)
763
764 def stmt(self, stmt, msg=None):
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300765 mod = ast.Module([stmt])
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500766 self.mod(mod, msg)
767
768 def test_module(self):
769 m = ast.Interactive([ast.Expr(ast.Name("x", ast.Store()))])
770 self.mod(m, "must have Load context", "single")
771 m = ast.Expression(ast.Name("x", ast.Store()))
772 self.mod(m, "must have Load context", "eval")
773
774 def _check_arguments(self, fac, check):
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700775 def arguments(args=None, vararg=None,
776 kwonlyargs=None, kwarg=None,
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500777 defaults=None, kw_defaults=None):
778 if args is None:
779 args = []
780 if kwonlyargs is None:
781 kwonlyargs = []
782 if defaults is None:
783 defaults = []
784 if kw_defaults is None:
785 kw_defaults = []
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700786 args = ast.arguments(args, vararg, kwonlyargs, kw_defaults,
787 kwarg, defaults)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500788 return fac(args)
789 args = [ast.arg("x", ast.Name("x", ast.Store()))]
790 check(arguments(args=args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500791 check(arguments(kwonlyargs=args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500792 check(arguments(defaults=[ast.Num(3)]),
793 "more positional defaults than args")
794 check(arguments(kw_defaults=[ast.Num(4)]),
795 "length of kwonlyargs is not the same as kw_defaults")
796 args = [ast.arg("x", ast.Name("x", ast.Load()))]
797 check(arguments(args=args, defaults=[ast.Name("x", ast.Store())]),
798 "must have Load context")
799 args = [ast.arg("a", ast.Name("x", ast.Load())),
800 ast.arg("b", ast.Name("y", ast.Load()))]
801 check(arguments(kwonlyargs=args,
802 kw_defaults=[None, ast.Name("x", ast.Store())]),
803 "must have Load context")
804
805 def test_funcdef(self):
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700806 a = ast.arguments([], None, [], [], None, [])
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300807 f = ast.FunctionDef("x", a, [], [], None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500808 self.stmt(f, "empty body on FunctionDef")
809 f = ast.FunctionDef("x", a, [ast.Pass()], [ast.Name("x", ast.Store())],
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300810 None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500811 self.stmt(f, "must have Load context")
812 f = ast.FunctionDef("x", a, [ast.Pass()], [],
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300813 ast.Name("x", ast.Store()))
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500814 self.stmt(f, "must have Load context")
815 def fac(args):
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300816 return ast.FunctionDef("x", args, [ast.Pass()], [], None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500817 self._check_arguments(fac, self.stmt)
818
819 def test_classdef(self):
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400820 def cls(bases=None, keywords=None, body=None, decorator_list=None):
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500821 if bases is None:
822 bases = []
823 if keywords is None:
824 keywords = []
825 if body is None:
826 body = [ast.Pass()]
827 if decorator_list is None:
828 decorator_list = []
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400829 return ast.ClassDef("myclass", bases, keywords,
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300830 body, decorator_list)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500831 self.stmt(cls(bases=[ast.Name("x", ast.Store())]),
832 "must have Load context")
833 self.stmt(cls(keywords=[ast.keyword("x", ast.Name("x", ast.Store()))]),
834 "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500835 self.stmt(cls(body=[]), "empty body on ClassDef")
836 self.stmt(cls(body=[None]), "None disallowed")
837 self.stmt(cls(decorator_list=[ast.Name("x", ast.Store())]),
838 "must have Load context")
839
840 def test_delete(self):
841 self.stmt(ast.Delete([]), "empty targets on Delete")
842 self.stmt(ast.Delete([None]), "None disallowed")
843 self.stmt(ast.Delete([ast.Name("x", ast.Load())]),
844 "must have Del context")
845
846 def test_assign(self):
847 self.stmt(ast.Assign([], ast.Num(3)), "empty targets on Assign")
848 self.stmt(ast.Assign([None], ast.Num(3)), "None disallowed")
849 self.stmt(ast.Assign([ast.Name("x", ast.Load())], ast.Num(3)),
850 "must have Store context")
851 self.stmt(ast.Assign([ast.Name("x", ast.Store())],
852 ast.Name("y", ast.Store())),
853 "must have Load context")
854
855 def test_augassign(self):
856 aug = ast.AugAssign(ast.Name("x", ast.Load()), ast.Add(),
857 ast.Name("y", ast.Load()))
858 self.stmt(aug, "must have Store context")
859 aug = ast.AugAssign(ast.Name("x", ast.Store()), ast.Add(),
860 ast.Name("y", ast.Store()))
861 self.stmt(aug, "must have Load context")
862
863 def test_for(self):
864 x = ast.Name("x", ast.Store())
865 y = ast.Name("y", ast.Load())
866 p = ast.Pass()
867 self.stmt(ast.For(x, y, [], []), "empty body on For")
868 self.stmt(ast.For(ast.Name("x", ast.Load()), y, [p], []),
869 "must have Store context")
870 self.stmt(ast.For(x, ast.Name("y", ast.Store()), [p], []),
871 "must have Load context")
872 e = ast.Expr(ast.Name("x", ast.Store()))
873 self.stmt(ast.For(x, y, [e], []), "must have Load context")
874 self.stmt(ast.For(x, y, [p], [e]), "must have Load context")
875
876 def test_while(self):
877 self.stmt(ast.While(ast.Num(3), [], []), "empty body on While")
878 self.stmt(ast.While(ast.Name("x", ast.Store()), [ast.Pass()], []),
879 "must have Load context")
880 self.stmt(ast.While(ast.Num(3), [ast.Pass()],
881 [ast.Expr(ast.Name("x", ast.Store()))]),
882 "must have Load context")
883
884 def test_if(self):
885 self.stmt(ast.If(ast.Num(3), [], []), "empty body on If")
886 i = ast.If(ast.Name("x", ast.Store()), [ast.Pass()], [])
887 self.stmt(i, "must have Load context")
888 i = ast.If(ast.Num(3), [ast.Expr(ast.Name("x", ast.Store()))], [])
889 self.stmt(i, "must have Load context")
890 i = ast.If(ast.Num(3), [ast.Pass()],
891 [ast.Expr(ast.Name("x", ast.Store()))])
892 self.stmt(i, "must have Load context")
893
894 def test_with(self):
895 p = ast.Pass()
896 self.stmt(ast.With([], [p]), "empty items on With")
897 i = ast.withitem(ast.Num(3), None)
898 self.stmt(ast.With([i], []), "empty body on With")
899 i = ast.withitem(ast.Name("x", ast.Store()), None)
900 self.stmt(ast.With([i], [p]), "must have Load context")
901 i = ast.withitem(ast.Num(3), ast.Name("x", ast.Load()))
902 self.stmt(ast.With([i], [p]), "must have Store context")
903
904 def test_raise(self):
905 r = ast.Raise(None, ast.Num(3))
906 self.stmt(r, "Raise with cause but no exception")
907 r = ast.Raise(ast.Name("x", ast.Store()), None)
908 self.stmt(r, "must have Load context")
909 r = ast.Raise(ast.Num(4), ast.Name("x", ast.Store()))
910 self.stmt(r, "must have Load context")
911
912 def test_try(self):
913 p = ast.Pass()
914 t = ast.Try([], [], [], [p])
915 self.stmt(t, "empty body on Try")
916 t = ast.Try([ast.Expr(ast.Name("x", ast.Store()))], [], [], [p])
917 self.stmt(t, "must have Load context")
918 t = ast.Try([p], [], [], [])
919 self.stmt(t, "Try has neither except handlers nor finalbody")
920 t = ast.Try([p], [], [p], [p])
921 self.stmt(t, "Try has orelse but no except handlers")
922 t = ast.Try([p], [ast.ExceptHandler(None, "x", [])], [], [])
923 self.stmt(t, "empty body on ExceptHandler")
924 e = [ast.ExceptHandler(ast.Name("x", ast.Store()), "y", [p])]
925 self.stmt(ast.Try([p], e, [], []), "must have Load context")
926 e = [ast.ExceptHandler(None, "x", [p])]
927 t = ast.Try([p], e, [ast.Expr(ast.Name("x", ast.Store()))], [p])
928 self.stmt(t, "must have Load context")
929 t = ast.Try([p], e, [p], [ast.Expr(ast.Name("x", ast.Store()))])
930 self.stmt(t, "must have Load context")
931
932 def test_assert(self):
933 self.stmt(ast.Assert(ast.Name("x", ast.Store()), None),
934 "must have Load context")
935 assrt = ast.Assert(ast.Name("x", ast.Load()),
936 ast.Name("y", ast.Store()))
937 self.stmt(assrt, "must have Load context")
938
939 def test_import(self):
940 self.stmt(ast.Import([]), "empty names on Import")
941
942 def test_importfrom(self):
943 imp = ast.ImportFrom(None, [ast.alias("x", None)], -42)
Serhiy Storchaka7de28402016-06-27 23:40:43 +0300944 self.stmt(imp, "Negative ImportFrom level")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500945 self.stmt(ast.ImportFrom(None, [], 0), "empty names on ImportFrom")
946
947 def test_global(self):
948 self.stmt(ast.Global([]), "empty names on Global")
949
950 def test_nonlocal(self):
951 self.stmt(ast.Nonlocal([]), "empty names on Nonlocal")
952
953 def test_expr(self):
954 e = ast.Expr(ast.Name("x", ast.Store()))
955 self.stmt(e, "must have Load context")
956
957 def test_boolop(self):
958 b = ast.BoolOp(ast.And(), [])
959 self.expr(b, "less than 2 values")
960 b = ast.BoolOp(ast.And(), [ast.Num(3)])
961 self.expr(b, "less than 2 values")
962 b = ast.BoolOp(ast.And(), [ast.Num(4), None])
963 self.expr(b, "None disallowed")
964 b = ast.BoolOp(ast.And(), [ast.Num(4), ast.Name("x", ast.Store())])
965 self.expr(b, "must have Load context")
966
967 def test_unaryop(self):
968 u = ast.UnaryOp(ast.Not(), ast.Name("x", ast.Store()))
969 self.expr(u, "must have Load context")
970
971 def test_lambda(self):
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700972 a = ast.arguments([], None, [], [], None, [])
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500973 self.expr(ast.Lambda(a, ast.Name("x", ast.Store())),
974 "must have Load context")
975 def fac(args):
976 return ast.Lambda(args, ast.Name("x", ast.Load()))
977 self._check_arguments(fac, self.expr)
978
979 def test_ifexp(self):
980 l = ast.Name("x", ast.Load())
981 s = ast.Name("y", ast.Store())
982 for args in (s, l, l), (l, s, l), (l, l, s):
Benjamin Peterson71ce8972011-08-09 16:17:12 -0500983 self.expr(ast.IfExp(*args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500984
985 def test_dict(self):
986 d = ast.Dict([], [ast.Name("x", ast.Load())])
987 self.expr(d, "same number of keys as values")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500988 d = ast.Dict([ast.Name("x", ast.Load())], [None])
989 self.expr(d, "None disallowed")
990
991 def test_set(self):
992 self.expr(ast.Set([None]), "None disallowed")
993 s = ast.Set([ast.Name("x", ast.Store())])
994 self.expr(s, "must have Load context")
995
996 def _check_comprehension(self, fac):
997 self.expr(fac([]), "comprehension with no generators")
998 g = ast.comprehension(ast.Name("x", ast.Load()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700999 ast.Name("x", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001000 self.expr(fac([g]), "must have Store context")
1001 g = ast.comprehension(ast.Name("x", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001002 ast.Name("x", ast.Store()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001003 self.expr(fac([g]), "must have Load context")
1004 x = ast.Name("x", ast.Store())
1005 y = ast.Name("y", ast.Load())
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001006 g = ast.comprehension(x, y, [None], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001007 self.expr(fac([g]), "None disallowed")
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001008 g = ast.comprehension(x, y, [ast.Name("x", ast.Store())], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001009 self.expr(fac([g]), "must have Load context")
1010
1011 def _simple_comp(self, fac):
1012 g = ast.comprehension(ast.Name("x", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001013 ast.Name("x", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001014 self.expr(fac(ast.Name("x", ast.Store()), [g]),
1015 "must have Load context")
1016 def wrap(gens):
1017 return fac(ast.Name("x", ast.Store()), gens)
1018 self._check_comprehension(wrap)
1019
1020 def test_listcomp(self):
1021 self._simple_comp(ast.ListComp)
1022
1023 def test_setcomp(self):
1024 self._simple_comp(ast.SetComp)
1025
1026 def test_generatorexp(self):
1027 self._simple_comp(ast.GeneratorExp)
1028
1029 def test_dictcomp(self):
1030 g = ast.comprehension(ast.Name("y", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001031 ast.Name("p", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001032 c = ast.DictComp(ast.Name("x", ast.Store()),
1033 ast.Name("y", ast.Load()), [g])
1034 self.expr(c, "must have Load context")
1035 c = ast.DictComp(ast.Name("x", ast.Load()),
1036 ast.Name("y", ast.Store()), [g])
1037 self.expr(c, "must have Load context")
1038 def factory(comps):
1039 k = ast.Name("x", ast.Load())
1040 v = ast.Name("y", ast.Load())
1041 return ast.DictComp(k, v, comps)
1042 self._check_comprehension(factory)
1043
1044 def test_yield(self):
Benjamin Peterson527c6222012-01-14 08:58:23 -05001045 self.expr(ast.Yield(ast.Name("x", ast.Store())), "must have Load")
1046 self.expr(ast.YieldFrom(ast.Name("x", ast.Store())), "must have Load")
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001047
1048 def test_compare(self):
1049 left = ast.Name("x", ast.Load())
1050 comp = ast.Compare(left, [ast.In()], [])
1051 self.expr(comp, "no comparators")
1052 comp = ast.Compare(left, [ast.In()], [ast.Num(4), ast.Num(5)])
1053 self.expr(comp, "different number of comparators and operands")
1054 comp = ast.Compare(ast.Num("blah"), [ast.In()], [left])
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001055 self.expr(comp)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001056 comp = ast.Compare(left, [ast.In()], [ast.Num("blah")])
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001057 self.expr(comp)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001058
1059 def test_call(self):
1060 func = ast.Name("x", ast.Load())
1061 args = [ast.Name("y", ast.Load())]
1062 keywords = [ast.keyword("w", ast.Name("z", ast.Load()))]
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001063 call = ast.Call(ast.Name("x", ast.Store()), args, keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001064 self.expr(call, "must have Load context")
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001065 call = ast.Call(func, [None], keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001066 self.expr(call, "None disallowed")
1067 bad_keywords = [ast.keyword("w", ast.Name("z", ast.Store()))]
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001068 call = ast.Call(func, args, bad_keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001069 self.expr(call, "must have Load context")
1070
1071 def test_num(self):
1072 class subint(int):
1073 pass
1074 class subfloat(float):
1075 pass
1076 class subcomplex(complex):
1077 pass
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001078 for obj in "0", "hello":
1079 self.expr(ast.Num(obj))
1080 for obj in subint(), subfloat(), subcomplex():
1081 self.expr(ast.Num(obj), "invalid type", exc=TypeError)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001082
1083 def test_attribute(self):
1084 attr = ast.Attribute(ast.Name("x", ast.Store()), "y", ast.Load())
1085 self.expr(attr, "must have Load context")
1086
1087 def test_subscript(self):
1088 sub = ast.Subscript(ast.Name("x", ast.Store()), ast.Index(ast.Num(3)),
1089 ast.Load())
1090 self.expr(sub, "must have Load context")
1091 x = ast.Name("x", ast.Load())
1092 sub = ast.Subscript(x, ast.Index(ast.Name("y", ast.Store())),
1093 ast.Load())
1094 self.expr(sub, "must have Load context")
1095 s = ast.Name("x", ast.Store())
1096 for args in (s, None, None), (None, s, None), (None, None, s):
1097 sl = ast.Slice(*args)
1098 self.expr(ast.Subscript(x, sl, ast.Load()),
1099 "must have Load context")
1100 sl = ast.ExtSlice([])
1101 self.expr(ast.Subscript(x, sl, ast.Load()), "empty dims on ExtSlice")
1102 sl = ast.ExtSlice([ast.Index(s)])
1103 self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context")
1104
1105 def test_starred(self):
1106 left = ast.List([ast.Starred(ast.Name("x", ast.Load()), ast.Store())],
1107 ast.Store())
1108 assign = ast.Assign([left], ast.Num(4))
1109 self.stmt(assign, "must have Store context")
1110
1111 def _sequence(self, fac):
1112 self.expr(fac([None], ast.Load()), "None disallowed")
1113 self.expr(fac([ast.Name("x", ast.Store())], ast.Load()),
1114 "must have Load context")
1115
1116 def test_list(self):
1117 self._sequence(ast.List)
1118
1119 def test_tuple(self):
1120 self._sequence(ast.Tuple)
1121
Benjamin Peterson442f2092012-12-06 17:41:04 -05001122 def test_nameconstant(self):
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001123 self.expr(ast.NameConstant(4))
Benjamin Peterson442f2092012-12-06 17:41:04 -05001124
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001125 def test_stdlib_validates(self):
1126 stdlib = os.path.dirname(ast.__file__)
1127 tests = [fn for fn in os.listdir(stdlib) if fn.endswith(".py")]
1128 tests.extend(["test/test_grammar.py", "test/test_unpack_ex.py"])
1129 for module in tests:
1130 fn = os.path.join(stdlib, module)
1131 with open(fn, "r", encoding="utf-8") as fp:
1132 source = fp.read()
Victor Stinnerd502a072013-03-22 00:06:20 +01001133 mod = ast.parse(source, fn)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001134 compile(mod, fn, "exec")
1135
1136
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001137class ConstantTests(unittest.TestCase):
1138 """Tests on the ast.Constant node type."""
1139
1140 def compile_constant(self, value):
1141 tree = ast.parse("x = 123")
1142
1143 node = tree.body[0].value
1144 new_node = ast.Constant(value=value)
1145 ast.copy_location(new_node, node)
1146 tree.body[0].value = new_node
1147
1148 code = compile(tree, "<string>", "exec")
1149
1150 ns = {}
1151 exec(code, ns)
1152 return ns['x']
1153
Victor Stinnerbe59d142016-01-27 00:39:12 +01001154 def test_validation(self):
1155 with self.assertRaises(TypeError) as cm:
1156 self.compile_constant([1, 2, 3])
1157 self.assertEqual(str(cm.exception),
1158 "got an invalid type in Constant: list")
1159
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001160 def test_singletons(self):
1161 for const in (None, False, True, Ellipsis, b'', frozenset()):
1162 with self.subTest(const=const):
1163 value = self.compile_constant(const)
1164 self.assertIs(value, const)
1165
1166 def test_values(self):
1167 nested_tuple = (1,)
1168 nested_frozenset = frozenset({1})
1169 for level in range(3):
1170 nested_tuple = (nested_tuple, 2)
1171 nested_frozenset = frozenset({nested_frozenset, 2})
1172 values = (123, 123.0, 123j,
1173 "unicode", b'bytes',
1174 tuple("tuple"), frozenset("frozenset"),
1175 nested_tuple, nested_frozenset)
1176 for value in values:
1177 with self.subTest(value=value):
1178 result = self.compile_constant(value)
1179 self.assertEqual(result, value)
1180
1181 def test_assign_to_constant(self):
1182 tree = ast.parse("x = 1")
1183
1184 target = tree.body[0].targets[0]
1185 new_target = ast.Constant(value=1)
1186 ast.copy_location(new_target, target)
1187 tree.body[0].targets[0] = new_target
1188
1189 with self.assertRaises(ValueError) as cm:
1190 compile(tree, "string", "exec")
1191 self.assertEqual(str(cm.exception),
1192 "expression which can't be assigned "
1193 "to in Store context")
1194
1195 def test_get_docstring(self):
1196 tree = ast.parse("'docstring'\nx = 1")
1197 self.assertEqual(ast.get_docstring(tree), 'docstring')
1198
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001199 def get_load_const(self, tree):
1200 # Compile to bytecode, disassemble and get parameter of LOAD_CONST
1201 # instructions
1202 co = compile(tree, '<string>', 'exec')
1203 consts = []
1204 for instr in dis.get_instructions(co):
1205 if instr.opname == 'LOAD_CONST':
1206 consts.append(instr.argval)
1207 return consts
1208
1209 @support.cpython_only
1210 def test_load_const(self):
1211 consts = [None,
1212 True, False,
1213 124,
1214 2.0,
1215 3j,
1216 "unicode",
1217 b'bytes',
1218 (1, 2, 3)]
1219
Victor Stinnera2724092016-02-08 18:17:58 +01001220 code = '\n'.join(['x={!r}'.format(const) for const in consts])
1221 code += '\nx = ...'
1222 consts.extend((Ellipsis, None))
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001223
1224 tree = ast.parse(code)
Victor Stinnera2724092016-02-08 18:17:58 +01001225 self.assertEqual(self.get_load_const(tree),
1226 consts)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001227
1228 # Replace expression nodes with constants
Victor Stinnera2724092016-02-08 18:17:58 +01001229 for assign, const in zip(tree.body, consts):
1230 assert isinstance(assign, ast.Assign), ast.dump(assign)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001231 new_node = ast.Constant(value=const)
Victor Stinnera2724092016-02-08 18:17:58 +01001232 ast.copy_location(new_node, assign.value)
1233 assign.value = new_node
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001234
Victor Stinnera2724092016-02-08 18:17:58 +01001235 self.assertEqual(self.get_load_const(tree),
1236 consts)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001237
1238 def test_literal_eval(self):
1239 tree = ast.parse("1 + 2")
1240 binop = tree.body[0].value
1241
1242 new_left = ast.Constant(value=10)
1243 ast.copy_location(new_left, binop.left)
1244 binop.left = new_left
1245
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +02001246 new_right = ast.Constant(value=20j)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001247 ast.copy_location(new_right, binop.right)
1248 binop.right = new_right
1249
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +02001250 self.assertEqual(ast.literal_eval(binop), 10+20j)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001251
1252
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001253def main():
1254 if __name__ != '__main__':
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001255 return
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001256 if sys.argv[1:] == ['-g']:
1257 for statements, kind in ((exec_tests, "exec"), (single_tests, "single"),
1258 (eval_tests, "eval")):
1259 print(kind+"_results = [")
Victor Stinnerf0891962016-02-08 17:15:21 +01001260 for statement in statements:
1261 tree = ast.parse(statement, "?", kind)
1262 print("%r," % (to_tuple(tree),))
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001263 print("]")
1264 print("main()")
1265 raise SystemExit
Brett Cannon3e9a9ae2013-06-12 21:25:59 -04001266 unittest.main()
Tim Peters400cbc32006-02-28 18:44:41 +00001267
1268#### EVERYTHING BELOW IS GENERATED #####
1269exec_results = [
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001270('Module', [('Expr', (1, 0), ('Constant', (1, 0), None))]),
1271('Module', [('Expr', (1, 0), ('Constant', (1, 0), 'module docstring'))]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001272('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [('Pass', (1, 9))], [], None)]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001273('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [('Expr', (1, 9), ('Constant', (1, 9), 'function docstring'))], [], None)]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001274('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None)], None, [], [], None, []), [('Pass', (1, 10))], [], None)]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001275('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 +03001276('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], ('arg', (1, 7), 'args', None), [], [], None, []), [('Pass', (1, 14))], [], None)]),
1277('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], ('arg', (1, 8), 'kwargs', None), []), [('Pass', (1, 17))], [], None)]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001278('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 +03001279('Module', [('ClassDef', (1, 0), 'C', [], [], [('Pass', (1, 8))], [])]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001280('Module', [('ClassDef', (1, 0), 'C', [], [], [('Expr', (1, 9), ('Constant', (1, 9), 'docstring for class C'))], [])]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001281('Module', [('ClassDef', (1, 0), 'C', [('Name', (1, 8), 'object', ('Load',))], [], [('Pass', (1, 17))], [])]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001282('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [('Return', (1, 8), ('Constant', (1, 15), 1))], [], None)]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001283('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001284('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Constant', (1, 4), 1))]),
Serhiy Storchakab619b092018-11-27 09:40:29 +02001285('Module', [('Assign', (1, 0), [('Tuple', (1, 0), [('Name', (1, 0), 'a', ('Store',)), ('Name', (1, 2), 'b', ('Store',))], ('Store',))], ('Name', (1, 6), 'c', ('Load',)))]),
1286('Module', [('Assign', (1, 0), [('Tuple', (1, 0), [('Name', (1, 1), 'a', ('Store',)), ('Name', (1, 3), 'b', ('Store',))], ('Store',))], ('Name', (1, 8), 'c', ('Load',)))]),
1287('Module', [('Assign', (1, 0), [('List', (1, 0), [('Name', (1, 1), 'a', ('Store',)), ('Name', (1, 3), 'b', ('Store',))], ('Store',))], ('Name', (1, 8), 'c', ('Load',)))]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001288('Module', [('AugAssign', (1, 0), ('Name', (1, 0), 'v', ('Store',)), ('Add',), ('Constant', (1, 5), 1))]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001289('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Pass', (1, 11))], [])]),
1290('Module', [('While', (1, 0), ('Name', (1, 6), 'v', ('Load',)), [('Pass', (1, 8))], [])]),
1291('Module', [('If', (1, 0), ('Name', (1, 3), 'v', ('Load',)), [('Pass', (1, 5))], [])]),
1292('Module', [('With', (1, 0), [('withitem', ('Name', (1, 5), 'x', ('Load',)), ('Name', (1, 10), 'y', ('Store',)))], [('Pass', (1, 13))])]),
1293('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 +03001294('Module', [('Raise', (1, 0), ('Call', (1, 6), ('Name', (1, 6), 'Exception', ('Load',)), [('Constant', (1, 16), 'string')], []), None)]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001295('Module', [('Try', (1, 0), [('Pass', (2, 2))], [('ExceptHandler', (3, 0), ('Name', (3, 7), 'Exception', ('Load',)), None, [('Pass', (4, 2))])], [], [])]),
1296('Module', [('Try', (1, 0), [('Pass', (2, 2))], [], [], [('Pass', (4, 2))])]),
1297('Module', [('Assert', (1, 0), ('Name', (1, 7), 'v', ('Load',)), None)]),
1298('Module', [('Import', (1, 0), [('alias', 'sys', None)])]),
1299('Module', [('ImportFrom', (1, 0), 'sys', [('alias', 'v', None)], 0)]),
1300('Module', [('Global', (1, 0), ['v'])]),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001301('Module', [('Expr', (1, 0), ('Constant', (1, 0), 1))]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001302('Module', [('Pass', (1, 0))]),
1303('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Break', (1, 11))], [])]),
1304('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Continue', (1, 11))], [])]),
1305('Module', [('For', (1, 0), ('Tuple', (1, 4), [('Name', (1, 4), 'a', ('Store',)), ('Name', (1, 6), 'b', ('Store',))], ('Store',)), ('Name', (1, 11), 'c', ('Load',)), [('Pass', (1, 14))], [])]),
Serhiy Storchakab619b092018-11-27 09:40:29 +02001306('Module', [('For', (1, 0), ('Tuple', (1, 4), [('Name', (1, 5), 'a', ('Store',)), ('Name', (1, 7), 'b', ('Store',))], ('Store',)), ('Name', (1, 13), 'c', ('Load',)), [('Pass', (1, 16))], [])]),
1307('Module', [('For', (1, 0), ('List', (1, 4), [('Name', (1, 5), 'a', ('Store',)), ('Name', (1, 7), 'b', ('Store',))], ('Store',)), ('Name', (1, 13), 'c', ('Load',)), [('Pass', (1, 16))], [])]),
1308('Module', [('Expr', (1, 0), ('GeneratorExp', (1, 0), ('Tuple', (2, 4), [('Name', (3, 4), 'Aa', ('Load',)), ('Name', (5, 7), 'Bb', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (8, 4), [('Name', (8, 4), 'Aa', ('Store',)), ('Name', (10, 4), 'Bb', ('Store',))], ('Store',)), ('Name', (10, 10), 'Cc', ('Load',)), [], 0)]))]),
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001309('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)]))]),
1310('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)]))]),
1311('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)]))]),
1312('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 +03001313('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)]),
1314('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)]),
1315('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)]),
1316('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)]))]),
1317('Module', [('Expr', (1, 0), ('Set', (1, 0), [('Starred', (1, 1), ('Set', (1, 2), [('Constant', (1, 3), 1), ('Constant', (1, 6), 2)]), ('Load',)), ('Constant', (1, 10), 3)]))]),
Serhiy Storchakab619b092018-11-27 09:40:29 +02001318('Module', [('AsyncFunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [('Expr', (2, 1), ('ListComp', (2, 1), ('Name', (2, 2), 'i', ('Load',)), [('comprehension', ('Name', (2, 14), 'b', ('Store',)), ('Name', (2, 19), 'c', ('Load',)), [], 1)]))], [], None)]),
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02001319('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)]),
1320('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)]),
1321('Module', [('ClassDef', (3, 0), 'C', [], [], [('Pass', (3, 9))], [('Name', (1, 1), 'deco1', ('Load',)), ('Call', (2, 0), ('Name', (2, 1), 'deco2', ('Load',)), [], [])])]),
Serhiy Storchakab619b092018-11-27 09:40:29 +02001322('Module', [('FunctionDef', (2, 0), 'f', ('arguments', [], None, [], [], None, []), [('Pass', (2, 9))], [('Call', (1, 1), ('Name', (1, 1), 'deco', ('Load',)), [('GeneratorExp', (1, 5), ('Name', (1, 6), 'a', ('Load',)), [('comprehension', ('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 17), 'b', ('Load',)), [], 0)])], [])], None)]),
Tim Peters400cbc32006-02-28 18:44:41 +00001323]
1324single_results = [
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001325('Interactive', [('Expr', (1, 0), ('BinOp', (1, 0), ('Constant', (1, 0), 1), ('Add',), ('Constant', (1, 2), 2)))]),
Tim Peters400cbc32006-02-28 18:44:41 +00001326]
1327eval_results = [
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001328('Expression', ('Constant', (1, 0), None)),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001329('Expression', ('BoolOp', (1, 0), ('And',), [('Name', (1, 0), 'a', ('Load',)), ('Name', (1, 6), 'b', ('Load',))])),
1330('Expression', ('BinOp', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Add',), ('Name', (1, 4), 'b', ('Load',)))),
1331('Expression', ('UnaryOp', (1, 0), ('Not',), ('Name', (1, 4), 'v', ('Load',)))),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001332('Expression', ('Lambda', (1, 0), ('arguments', [], None, [], [], None, []), ('Constant', (1, 7), None))),
1333('Expression', ('Dict', (1, 0), [('Constant', (1, 2), 1)], [('Constant', (1, 4), 2)])),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001334('Expression', ('Dict', (1, 0), [], [])),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001335('Expression', ('Set', (1, 0), [('Constant', (1, 1), None)])),
1336('Expression', ('Dict', (1, 0), [('Constant', (2, 6), 1)], [('Constant', (4, 10), 2)])),
Serhiy Storchakab619b092018-11-27 09:40:29 +02001337('Expression', ('ListComp', (1, 0), ('Name', (1, 1), 'a', ('Load',)), [('comprehension', ('Name', (1, 7), 'b', ('Store',)), ('Name', (1, 12), 'c', ('Load',)), [('Name', (1, 17), 'd', ('Load',))], 0)])),
1338('Expression', ('GeneratorExp', (1, 0), ('Name', (1, 1), 'a', ('Load',)), [('comprehension', ('Name', (1, 7), 'b', ('Store',)), ('Name', (1, 12), 'c', ('Load',)), [('Name', (1, 17), 'd', ('Load',))], 0)])),
1339('Expression', ('ListComp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'a', ('Store',)), ('Name', (1, 13), 'b', ('Store',))], ('Store',)), ('Name', (1, 18), 'c', ('Load',)), [], 0)])),
1340('Expression', ('ListComp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [], 0)])),
1341('Expression', ('ListComp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('List', (1, 11), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [], 0)])),
1342('Expression', ('SetComp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'a', ('Store',)), ('Name', (1, 13), 'b', ('Store',))], ('Store',)), ('Name', (1, 18), 'c', ('Load',)), [], 0)])),
1343('Expression', ('SetComp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [], 0)])),
1344('Expression', ('SetComp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('List', (1, 11), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [], 0)])),
1345('Expression', ('GeneratorExp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'a', ('Store',)), ('Name', (1, 13), 'b', ('Store',))], ('Store',)), ('Name', (1, 18), 'c', ('Load',)), [], 0)])),
1346('Expression', ('GeneratorExp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [], 0)])),
1347('Expression', ('GeneratorExp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('List', (1, 11), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [], 0)])),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001348('Expression', ('Compare', (1, 0), ('Constant', (1, 0), 1), [('Lt',), ('Lt',)], [('Constant', (1, 4), 2), ('Constant', (1, 8), 3)])),
1349('Expression', ('Call', (1, 0), ('Name', (1, 0), 'f', ('Load',)), [('Constant', (1, 2), 1), ('Constant', (1, 4), 2), ('Starred', (1, 10), ('Name', (1, 11), 'd', ('Load',)), ('Load',))], [('keyword', 'c', ('Constant', (1, 8), 3)), ('keyword', None, ('Name', (1, 15), 'e', ('Load',)))])),
Serhiy Storchakab619b092018-11-27 09:40:29 +02001350('Expression', ('Call', (1, 0), ('Name', (1, 0), 'f', ('Load',)), [('GeneratorExp', (1, 1), ('Name', (1, 2), 'a', ('Load',)), [('comprehension', ('Name', (1, 8), 'a', ('Store',)), ('Name', (1, 13), 'b', ('Load',)), [], 0)])], [])),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001351('Expression', ('Constant', (1, 0), 10)),
1352('Expression', ('Constant', (1, 0), 'string')),
Benjamin Peterson7a66fc22015-02-02 10:51:20 -05001353('Expression', ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',))),
1354('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 +00001355('Expression', ('Name', (1, 0), 'v', ('Load',))),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001356('Expression', ('List', (1, 0), [('Constant', (1, 1), 1), ('Constant', (1, 3), 2), ('Constant', (1, 5), 3)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001357('Expression', ('List', (1, 0), [], ('Load',))),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001358('Expression', ('Tuple', (1, 0), [('Constant', (1, 0), 1), ('Constant', (1, 2), 2), ('Constant', (1, 4), 3)], ('Load',))),
Serhiy Storchakab619b092018-11-27 09:40:29 +02001359('Expression', ('Tuple', (1, 0), [('Constant', (1, 1), 1), ('Constant', (1, 3), 2), ('Constant', (1, 5), 3)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001360('Expression', ('Tuple', (1, 0), [], ('Load',))),
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001361('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 +00001362]
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001363main()