blob: c45326f4b4e2ee777e4cdde722c16c445cd1b92e [file] [log] [blame]
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001import os
2import sys
3import unittest
Georg Brandl0c77a822008-06-10 16:37:50 +00004import ast
Benjamin Peterson9ed37432012-07-08 11:13:36 -07005import weakref
6
7from test import support
Tim Peters400cbc32006-02-28 18:44:41 +00008
9def to_tuple(t):
Guido van Rossum3172c5d2007-10-16 18:12:55 +000010 if t is None or isinstance(t, (str, int, complex)):
Tim Peters400cbc32006-02-28 18:44:41 +000011 return t
12 elif isinstance(t, list):
13 return [to_tuple(e) for e in t]
14 result = [t.__class__.__name__]
Martin v. Löwis49c5da12006-03-01 22:49:05 +000015 if hasattr(t, 'lineno') and hasattr(t, 'col_offset'):
16 result.append((t.lineno, t.col_offset))
Tim Peters400cbc32006-02-28 18:44:41 +000017 if t._fields is None:
18 return tuple(result)
19 for f in t._fields:
20 result.append(to_tuple(getattr(t, f)))
21 return tuple(result)
22
Neal Norwitzee9b10a2008-03-31 05:29:39 +000023
Tim Peters400cbc32006-02-28 18:44:41 +000024# These tests are compiled through "exec"
25# There should be atleast one test per statement
26exec_tests = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050027 # None
28 "None",
Tim Peters400cbc32006-02-28 18:44:41 +000029 # FunctionDef
30 "def f(): pass",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050031 # FunctionDef with arg
32 "def f(a): pass",
33 # FunctionDef with arg and default value
34 "def f(a=0): pass",
35 # FunctionDef with varargs
36 "def f(*args): pass",
37 # FunctionDef with kwargs
38 "def f(**kwargs): pass",
39 # FunctionDef with all kind of args
40 "def f(a, b=1, c=None, d=[], e={}, *args, **kwargs): pass",
Tim Peters400cbc32006-02-28 18:44:41 +000041 # ClassDef
42 "class C:pass",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050043 # ClassDef, new style class
44 "class C(object): pass",
Tim Peters400cbc32006-02-28 18:44:41 +000045 # Return
46 "def f():return 1",
47 # Delete
48 "del v",
49 # Assign
50 "v = 1",
51 # AugAssign
52 "v += 1",
Tim Peters400cbc32006-02-28 18:44:41 +000053 # For
54 "for v in v:pass",
55 # While
56 "while v:pass",
57 # If
58 "if v:pass",
Benjamin Petersonaeabd5f2011-05-27 15:02:03 -050059 # With
60 "with x as y: pass",
61 "with x as y, z as q: pass",
Tim Peters400cbc32006-02-28 18:44:41 +000062 # Raise
Collin Winter828f04a2007-08-31 00:04:24 +000063 "raise Exception('string')",
Tim Peters400cbc32006-02-28 18:44:41 +000064 # TryExcept
65 "try:\n pass\nexcept Exception:\n pass",
66 # TryFinally
67 "try:\n pass\nfinally:\n pass",
68 # Assert
69 "assert v",
70 # Import
71 "import sys",
72 # ImportFrom
73 "from sys import v",
Tim Peters400cbc32006-02-28 18:44:41 +000074 # Global
75 "global v",
76 # Expr
77 "1",
78 # Pass,
79 "pass",
80 # Break
81 "break",
82 # Continue
83 "continue",
Benjamin Peterson2e4b0e12009-09-11 22:36:20 +000084 # for statements with naked tuples (see http://bugs.python.org/issue6704)
85 "for a,b in c: pass",
86 "[(a,b) for a,b in c]",
87 "((a,b) for a,b in c)",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050088 "((a,b) for (a,b) in c)",
89 # Multiline generator expression (test for .lineno & .col_offset)
90 """(
91 (
92 Aa
93 ,
94 Bb
95 )
96 for
97 Aa
98 ,
99 Bb in Cc
100 )""",
101 # dictcomp
102 "{a : b for w in x for m in p if g}",
103 # dictcomp with naked tuple
104 "{a : b for v,w in x}",
105 # setcomp
106 "{r for l in x if g}",
107 # setcomp with naked tuple
108 "{r for l,m in x}",
Tim Peters400cbc32006-02-28 18:44:41 +0000109]
110
111# These are compiled through "single"
112# because of overlap with "eval", it just tests what
113# can't be tested with "eval"
114single_tests = [
115 "1+2"
116]
117
118# These are compiled through "eval"
119# It should test all expressions
120eval_tests = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500121 # None
122 "None",
Tim Peters400cbc32006-02-28 18:44:41 +0000123 # BoolOp
124 "a and b",
125 # BinOp
126 "a + b",
127 # UnaryOp
128 "not v",
129 # Lambda
130 "lambda:None",
131 # Dict
132 "{ 1:2 }",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500133 # Empty dict
134 "{}",
135 # Set
136 "{None,}",
137 # Multiline dict (test for .lineno & .col_offset)
138 """{
139 1
140 :
141 2
142 }""",
Tim Peters400cbc32006-02-28 18:44:41 +0000143 # ListComp
144 "[a for b in c if d]",
145 # GeneratorExp
146 "(a for b in c if d)",
147 # Yield - yield expressions can't work outside a function
148 #
149 # Compare
150 "1 < 2 < 3",
151 # Call
152 "f(1,2,c=3,*d,**e)",
Tim Peters400cbc32006-02-28 18:44:41 +0000153 # Num
Guido van Rossume2a383d2007-01-15 16:59:06 +0000154 "10",
Tim Peters400cbc32006-02-28 18:44:41 +0000155 # Str
156 "'string'",
157 # Attribute
158 "a.b",
159 # Subscript
160 "a[b:c]",
161 # Name
162 "v",
163 # List
164 "[1,2,3]",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500165 # Empty list
166 "[]",
Tim Peters400cbc32006-02-28 18:44:41 +0000167 # Tuple
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000168 "1,2,3",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500169 # Tuple
170 "(1,2,3)",
171 # Empty tuple
172 "()",
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000173 # Combination
174 "a.b.c.d(a.b[1:2])",
175
Tim Peters400cbc32006-02-28 18:44:41 +0000176]
177
178# TODO: expr_context, slice, boolop, operator, unaryop, cmpop, comprehension
179# excepthandler, arguments, keywords, alias
180
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000181class AST_Tests(unittest.TestCase):
Tim Peters400cbc32006-02-28 18:44:41 +0000182
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700183 def _assertTrueorder(self, ast_node, parent_pos, reverse_check = False):
184 def should_reverse_check(parent, child):
185 # In some situations, the children of nodes occur before
186 # their parents, for example in a.b.c, a occurs before b
187 # but a is a child of b.
188 if isinstance(parent, ast.Call):
189 if parent.func == child:
190 return True
191 if isinstance(parent, (ast.Attribute, ast.Subscript)):
192 return True
193 return False
194
Georg Brandl0c77a822008-06-10 16:37:50 +0000195 if not isinstance(ast_node, ast.AST) or ast_node._fields is None:
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000196 return
Georg Brandl0c77a822008-06-10 16:37:50 +0000197 if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000198 node_pos = (ast_node.lineno, ast_node.col_offset)
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700199 if reverse_check:
200 self.assertTrue(node_pos <= parent_pos)
201 else:
202 self.assertTrue(node_pos >= parent_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000203 parent_pos = (ast_node.lineno, ast_node.col_offset)
204 for name in ast_node._fields:
205 value = getattr(ast_node, name)
206 if isinstance(value, list):
207 for child in value:
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700208 self._assertTrueorder(child, parent_pos,
209 should_reverse_check(ast_node, child))
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000210 elif value is not None:
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700211 self._assertTrueorder(value, parent_pos,
212 should_reverse_check(ast_node, value))
Tim Peters5ddfe412006-03-01 23:02:57 +0000213
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500214 def test_AST_objects(self):
215 x = ast.AST()
216 self.assertEqual(x._fields, ())
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700217 x.foobar = 42
218 self.assertEqual(x.foobar, 42)
219 self.assertEqual(x.__dict__["foobar"], 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500220
221 with self.assertRaises(AttributeError):
222 x.vararg
223
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500224 with self.assertRaises(TypeError):
225 # "_ast.AST constructor takes 0 positional arguments"
226 ast.AST(2)
227
Benjamin Peterson9ed37432012-07-08 11:13:36 -0700228 def test_AST_garbage_collection(self):
229 class X:
230 pass
231 a = ast.AST()
232 a.x = X()
233 a.x.a = a
234 ref = weakref.ref(a.x)
235 del a
236 support.gc_collect()
237 self.assertIsNone(ref())
238
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000239 def test_snippets(self):
240 for input, output, kind in ((exec_tests, exec_results, "exec"),
241 (single_tests, single_results, "single"),
242 (eval_tests, eval_results, "eval")):
243 for i, o in zip(input, output):
Georg Brandl0c77a822008-06-10 16:37:50 +0000244 ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000245 self.assertEqual(to_tuple(ast_tree), o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000246 self._assertTrueorder(ast_tree, (0, 0))
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000247
Benjamin Peterson78565b22009-06-28 19:19:51 +0000248 def test_slice(self):
249 slc = ast.parse("x[::]").body[0].value.slice
250 self.assertIsNone(slc.upper)
251 self.assertIsNone(slc.lower)
252 self.assertIsNone(slc.step)
253
254 def test_from_import(self):
255 im = ast.parse("from . import y").body[0]
256 self.assertIsNone(im.module)
257
Benjamin Petersona4e4e352012-03-22 08:19:04 -0400258 def test_non_interned_future_from_ast(self):
259 mod = ast.parse("from __future__ import division")
260 self.assertIsInstance(mod.body[0], ast.ImportFrom)
261 mod.body[0].module = " __future__ ".strip()
262 compile(mod, "<test>", "exec")
263
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000264 def test_base_classes(self):
265 self.assertTrue(issubclass(ast.For, ast.stmt))
266 self.assertTrue(issubclass(ast.Name, ast.expr))
267 self.assertTrue(issubclass(ast.stmt, ast.AST))
268 self.assertTrue(issubclass(ast.expr, ast.AST))
269 self.assertTrue(issubclass(ast.comprehension, ast.AST))
270 self.assertTrue(issubclass(ast.Gt, ast.AST))
271
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500272 def test_field_attr_existence(self):
273 for name, item in ast.__dict__.items():
274 if isinstance(item, type) and name != 'AST' and name[0].isupper():
275 x = item()
276 if isinstance(x, ast.AST):
277 self.assertEqual(type(x._fields), tuple)
278
279 def test_arguments(self):
280 x = ast.arguments()
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700281 self.assertEqual(x._fields, ('args', 'vararg',
282 'kwonlyargs', 'kw_defaults',
283 'kwarg', 'defaults'))
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500284
285 with self.assertRaises(AttributeError):
286 x.vararg
287
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700288 x = ast.arguments(*range(1, 7))
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500289 self.assertEqual(x.vararg, 2)
290
291 def test_field_attr_writable(self):
292 x = ast.Num()
293 # We can assign to _fields
294 x._fields = 666
295 self.assertEqual(x._fields, 666)
296
297 def test_classattrs(self):
298 x = ast.Num()
299 self.assertEqual(x._fields, ('n',))
300
301 with self.assertRaises(AttributeError):
302 x.n
303
304 x = ast.Num(42)
305 self.assertEqual(x.n, 42)
306
307 with self.assertRaises(AttributeError):
308 x.lineno
309
310 with self.assertRaises(AttributeError):
311 x.foobar
312
313 x = ast.Num(lineno=2)
314 self.assertEqual(x.lineno, 2)
315
316 x = ast.Num(42, lineno=0)
317 self.assertEqual(x.lineno, 0)
318 self.assertEqual(x._fields, ('n',))
319 self.assertEqual(x.n, 42)
320
321 self.assertRaises(TypeError, ast.Num, 1, 2)
322 self.assertRaises(TypeError, ast.Num, 1, 2, lineno=0)
323
324 def test_module(self):
325 body = [ast.Num(42)]
326 x = ast.Module(body)
327 self.assertEqual(x.body, body)
328
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000329 def test_nodeclasses(self):
Florent Xicluna992d9e02011-11-11 19:35:42 +0100330 # Zero arguments constructor explicitly allowed
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500331 x = ast.BinOp()
332 self.assertEqual(x._fields, ('left', 'op', 'right'))
333
334 # Random attribute allowed too
335 x.foobarbaz = 5
336 self.assertEqual(x.foobarbaz, 5)
337
338 n1 = ast.Num(1)
339 n3 = ast.Num(3)
340 addop = ast.Add()
341 x = ast.BinOp(n1, addop, n3)
342 self.assertEqual(x.left, n1)
343 self.assertEqual(x.op, addop)
344 self.assertEqual(x.right, n3)
Benjamin Peterson68b543a2011-06-27 17:51:18 -0500345
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500346 x = ast.BinOp(1, 2, 3)
347 self.assertEqual(x.left, 1)
348 self.assertEqual(x.op, 2)
349 self.assertEqual(x.right, 3)
350
Georg Brandl0c77a822008-06-10 16:37:50 +0000351 x = ast.BinOp(1, 2, 3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000352 self.assertEqual(x.left, 1)
353 self.assertEqual(x.op, 2)
354 self.assertEqual(x.right, 3)
355 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000356
357 # node raises exception when not given enough arguments
Georg Brandl0c77a822008-06-10 16:37:50 +0000358 self.assertRaises(TypeError, ast.BinOp, 1, 2)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500359 # node raises exception when given too many arguments
360 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4)
361 # node raises exception when not given enough arguments
362 self.assertRaises(TypeError, ast.BinOp, 1, 2, lineno=0)
363 # node raises exception when given too many arguments
364 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4, lineno=0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000365
366 # can set attributes through kwargs too
Georg Brandl0c77a822008-06-10 16:37:50 +0000367 x = ast.BinOp(left=1, op=2, right=3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000368 self.assertEqual(x.left, 1)
369 self.assertEqual(x.op, 2)
370 self.assertEqual(x.right, 3)
371 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000372
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500373 # Random kwargs also allowed
374 x = ast.BinOp(1, 2, 3, foobarbaz=42)
375 self.assertEqual(x.foobarbaz, 42)
376
377 def test_no_fields(self):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000378 # this used to fail because Sub._fields was None
Georg Brandl0c77a822008-06-10 16:37:50 +0000379 x = ast.Sub()
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500380 self.assertEqual(x._fields, ())
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000381
382 def test_pickling(self):
383 import pickle
384 mods = [pickle]
385 try:
386 import cPickle
387 mods.append(cPickle)
388 except ImportError:
389 pass
390 protocols = [0, 1, 2]
391 for mod in mods:
392 for protocol in protocols:
393 for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests):
394 ast2 = mod.loads(mod.dumps(ast, protocol))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000395 self.assertEqual(to_tuple(ast2), to_tuple(ast))
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000396
Benjamin Peterson5b066812010-11-20 01:38:49 +0000397 def test_invalid_sum(self):
398 pos = dict(lineno=2, col_offset=3)
399 m = ast.Module([ast.Expr(ast.expr(**pos), **pos)])
400 with self.assertRaises(TypeError) as cm:
401 compile(m, "<test>", "exec")
402 self.assertIn("but got <_ast.expr", str(cm.exception))
403
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500404 def test_invalid_identitifer(self):
405 m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))])
406 ast.fix_missing_locations(m)
407 with self.assertRaises(TypeError) as cm:
408 compile(m, "<test>", "exec")
409 self.assertIn("identifier must be of type str", str(cm.exception))
410
411 def test_invalid_string(self):
412 m = ast.Module([ast.Expr(ast.Str(42))])
413 ast.fix_missing_locations(m)
414 with self.assertRaises(TypeError) as cm:
415 compile(m, "<test>", "exec")
416 self.assertIn("string must be of type str", str(cm.exception))
417
Mark Dickinsonded35ae2012-11-25 14:36:26 +0000418 def test_empty_yield_from(self):
419 # Issue 16546: yield from value is not optional.
420 empty_yield_from = ast.parse("def f():\n yield from g()")
421 empty_yield_from.body[0].body[0].value.value = None
422 with self.assertRaises(ValueError) as cm:
423 compile(empty_yield_from, "<test>", "exec")
424 self.assertIn("field value is required", str(cm.exception))
425
Georg Brandl0c77a822008-06-10 16:37:50 +0000426
427class ASTHelpers_Test(unittest.TestCase):
428
429 def test_parse(self):
430 a = ast.parse('foo(1 + 1)')
431 b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST)
432 self.assertEqual(ast.dump(a), ast.dump(b))
433
Benjamin Peterson2e2c9032012-09-02 14:23:15 -0400434 def test_parse_in_error(self):
435 try:
436 1/0
437 except Exception:
Benjamin Petersonbd0df502012-09-02 15:04:51 -0400438 with self.assertRaises(SyntaxError) as e:
439 ast.literal_eval(r"'\U'")
440 self.assertIsNotNone(e.exception.__context__)
Benjamin Peterson2e2c9032012-09-02 14:23:15 -0400441
Georg Brandl0c77a822008-06-10 16:37:50 +0000442 def test_dump(self):
443 node = ast.parse('spam(eggs, "and cheese")')
444 self.assertEqual(ast.dump(node),
445 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
446 "args=[Name(id='eggs', ctx=Load()), Str(s='and cheese')], "
447 "keywords=[], starargs=None, kwargs=None))])"
448 )
449 self.assertEqual(ast.dump(node, annotate_fields=False),
450 "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
451 "Str('and cheese')], [], None, None))])"
452 )
453 self.assertEqual(ast.dump(node, include_attributes=True),
454 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
455 "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), "
456 "lineno=1, col_offset=5), Str(s='and cheese', lineno=1, "
457 "col_offset=11)], keywords=[], starargs=None, kwargs=None, "
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700458 "lineno=1, col_offset=4), lineno=1, col_offset=0)])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000459 )
460
461 def test_copy_location(self):
462 src = ast.parse('1 + 1', mode='eval')
463 src.body.right = ast.copy_location(ast.Num(2), src.body.right)
464 self.assertEqual(ast.dump(src, include_attributes=True),
465 'Expression(body=BinOp(left=Num(n=1, lineno=1, col_offset=0), '
466 'op=Add(), right=Num(n=2, lineno=1, col_offset=4), lineno=1, '
467 'col_offset=0))'
468 )
469
470 def test_fix_missing_locations(self):
471 src = ast.parse('write("spam")')
472 src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()),
473 [ast.Str('eggs')], [], None, None)))
474 self.assertEqual(src, ast.fix_missing_locations(src))
475 self.assertEqual(ast.dump(src, include_attributes=True),
476 "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), "
477 "lineno=1, col_offset=0), args=[Str(s='spam', lineno=1, "
478 "col_offset=6)], keywords=[], starargs=None, kwargs=None, "
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700479 "lineno=1, col_offset=5), lineno=1, col_offset=0), "
Georg Brandl0c77a822008-06-10 16:37:50 +0000480 "Expr(value=Call(func=Name(id='spam', ctx=Load(), lineno=1, "
481 "col_offset=0), args=[Str(s='eggs', lineno=1, col_offset=0)], "
482 "keywords=[], starargs=None, kwargs=None, lineno=1, "
483 "col_offset=0), lineno=1, col_offset=0)])"
484 )
485
486 def test_increment_lineno(self):
487 src = ast.parse('1 + 1', mode='eval')
488 self.assertEqual(ast.increment_lineno(src, n=3), src)
489 self.assertEqual(ast.dump(src, include_attributes=True),
490 'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
491 'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
492 'col_offset=0))'
493 )
Georg Brandl619e7ba2011-01-09 07:38:51 +0000494 # issue10869: do not increment lineno of root twice
Georg Brandlefb69022011-01-09 07:50:48 +0000495 src = ast.parse('1 + 1', mode='eval')
Georg Brandl619e7ba2011-01-09 07:38:51 +0000496 self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
497 self.assertEqual(ast.dump(src, include_attributes=True),
498 'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
499 'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
500 'col_offset=0))'
501 )
Georg Brandl0c77a822008-06-10 16:37:50 +0000502
503 def test_iter_fields(self):
504 node = ast.parse('foo()', mode='eval')
505 d = dict(ast.iter_fields(node.body))
506 self.assertEqual(d.pop('func').id, 'foo')
507 self.assertEqual(d, {'keywords': [], 'kwargs': None,
508 'args': [], 'starargs': None})
509
510 def test_iter_child_nodes(self):
511 node = ast.parse("spam(23, 42, eggs='leek')", mode='eval')
512 self.assertEqual(len(list(ast.iter_child_nodes(node.body))), 4)
513 iterator = ast.iter_child_nodes(node.body)
514 self.assertEqual(next(iterator).id, 'spam')
515 self.assertEqual(next(iterator).n, 23)
516 self.assertEqual(next(iterator).n, 42)
517 self.assertEqual(ast.dump(next(iterator)),
518 "keyword(arg='eggs', value=Str(s='leek'))"
519 )
520
521 def test_get_docstring(self):
522 node = ast.parse('def foo():\n """line one\n line two"""')
523 self.assertEqual(ast.get_docstring(node.body[0]),
524 'line one\nline two')
525
526 def test_literal_eval(self):
527 self.assertEqual(ast.literal_eval('[1, 2, 3]'), [1, 2, 3])
528 self.assertEqual(ast.literal_eval('{"foo": 42}'), {"foo": 42})
529 self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None))
Benjamin Peterson3e742892010-07-11 12:59:24 +0000530 self.assertEqual(ast.literal_eval('{1, 2, 3}'), {1, 2, 3})
Benjamin Peterson5ef96e52010-07-11 23:06:06 +0000531 self.assertEqual(ast.literal_eval('b"hi"'), b"hi")
Georg Brandl0c77a822008-06-10 16:37:50 +0000532 self.assertRaises(ValueError, ast.literal_eval, 'foo()')
Raymond Hettingerbc959732010-10-08 00:47:45 +0000533 self.assertEqual(ast.literal_eval('-6'), -6)
534 self.assertEqual(ast.literal_eval('-6j+3'), 3-6j)
535 self.assertEqual(ast.literal_eval('3.25'), 3.25)
Georg Brandl0c77a822008-06-10 16:37:50 +0000536
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000537 def test_literal_eval_issue4907(self):
538 self.assertEqual(ast.literal_eval('2j'), 2j)
539 self.assertEqual(ast.literal_eval('10 + 2j'), 10 + 2j)
540 self.assertEqual(ast.literal_eval('1.5 - 2j'), 1.5 - 2j)
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000541
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100542 def test_bad_integer(self):
543 # issue13436: Bad error message with invalid numeric values
544 body = [ast.ImportFrom(module='time',
545 names=[ast.alias(name='sleep')],
546 level=None,
547 lineno=None, col_offset=None)]
548 mod = ast.Module(body)
549 with self.assertRaises(ValueError) as cm:
550 compile(mod, 'test', 'exec')
551 self.assertIn("invalid integer value: None", str(cm.exception))
552
Georg Brandl0c77a822008-06-10 16:37:50 +0000553
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500554class ASTValidatorTests(unittest.TestCase):
555
556 def mod(self, mod, msg=None, mode="exec", *, exc=ValueError):
557 mod.lineno = mod.col_offset = 0
558 ast.fix_missing_locations(mod)
559 with self.assertRaises(exc) as cm:
560 compile(mod, "<test>", mode)
561 if msg is not None:
562 self.assertIn(msg, str(cm.exception))
563
564 def expr(self, node, msg=None, *, exc=ValueError):
565 mod = ast.Module([ast.Expr(node)])
566 self.mod(mod, msg, exc=exc)
567
568 def stmt(self, stmt, msg=None):
569 mod = ast.Module([stmt])
570 self.mod(mod, msg)
571
572 def test_module(self):
573 m = ast.Interactive([ast.Expr(ast.Name("x", ast.Store()))])
574 self.mod(m, "must have Load context", "single")
575 m = ast.Expression(ast.Name("x", ast.Store()))
576 self.mod(m, "must have Load context", "eval")
577
578 def _check_arguments(self, fac, check):
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700579 def arguments(args=None, vararg=None,
580 kwonlyargs=None, kwarg=None,
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500581 defaults=None, kw_defaults=None):
582 if args is None:
583 args = []
584 if kwonlyargs is None:
585 kwonlyargs = []
586 if defaults is None:
587 defaults = []
588 if kw_defaults is None:
589 kw_defaults = []
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700590 args = ast.arguments(args, vararg, kwonlyargs, kw_defaults,
591 kwarg, defaults)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500592 return fac(args)
593 args = [ast.arg("x", ast.Name("x", ast.Store()))]
594 check(arguments(args=args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500595 check(arguments(kwonlyargs=args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500596 check(arguments(defaults=[ast.Num(3)]),
597 "more positional defaults than args")
598 check(arguments(kw_defaults=[ast.Num(4)]),
599 "length of kwonlyargs is not the same as kw_defaults")
600 args = [ast.arg("x", ast.Name("x", ast.Load()))]
601 check(arguments(args=args, defaults=[ast.Name("x", ast.Store())]),
602 "must have Load context")
603 args = [ast.arg("a", ast.Name("x", ast.Load())),
604 ast.arg("b", ast.Name("y", ast.Load()))]
605 check(arguments(kwonlyargs=args,
606 kw_defaults=[None, ast.Name("x", ast.Store())]),
607 "must have Load context")
608
609 def test_funcdef(self):
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700610 a = ast.arguments([], None, [], [], None, [])
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500611 f = ast.FunctionDef("x", a, [], [], None)
612 self.stmt(f, "empty body on FunctionDef")
613 f = ast.FunctionDef("x", a, [ast.Pass()], [ast.Name("x", ast.Store())],
614 None)
615 self.stmt(f, "must have Load context")
616 f = ast.FunctionDef("x", a, [ast.Pass()], [],
617 ast.Name("x", ast.Store()))
618 self.stmt(f, "must have Load context")
619 def fac(args):
620 return ast.FunctionDef("x", args, [ast.Pass()], [], None)
621 self._check_arguments(fac, self.stmt)
622
623 def test_classdef(self):
624 def cls(bases=None, keywords=None, starargs=None, kwargs=None,
625 body=None, decorator_list=None):
626 if bases is None:
627 bases = []
628 if keywords is None:
629 keywords = []
630 if body is None:
631 body = [ast.Pass()]
632 if decorator_list is None:
633 decorator_list = []
634 return ast.ClassDef("myclass", bases, keywords, starargs,
635 kwargs, body, decorator_list)
636 self.stmt(cls(bases=[ast.Name("x", ast.Store())]),
637 "must have Load context")
638 self.stmt(cls(keywords=[ast.keyword("x", ast.Name("x", ast.Store()))]),
639 "must have Load context")
640 self.stmt(cls(starargs=ast.Name("x", ast.Store())),
641 "must have Load context")
642 self.stmt(cls(kwargs=ast.Name("x", ast.Store())),
643 "must have Load context")
644 self.stmt(cls(body=[]), "empty body on ClassDef")
645 self.stmt(cls(body=[None]), "None disallowed")
646 self.stmt(cls(decorator_list=[ast.Name("x", ast.Store())]),
647 "must have Load context")
648
649 def test_delete(self):
650 self.stmt(ast.Delete([]), "empty targets on Delete")
651 self.stmt(ast.Delete([None]), "None disallowed")
652 self.stmt(ast.Delete([ast.Name("x", ast.Load())]),
653 "must have Del context")
654
655 def test_assign(self):
656 self.stmt(ast.Assign([], ast.Num(3)), "empty targets on Assign")
657 self.stmt(ast.Assign([None], ast.Num(3)), "None disallowed")
658 self.stmt(ast.Assign([ast.Name("x", ast.Load())], ast.Num(3)),
659 "must have Store context")
660 self.stmt(ast.Assign([ast.Name("x", ast.Store())],
661 ast.Name("y", ast.Store())),
662 "must have Load context")
663
664 def test_augassign(self):
665 aug = ast.AugAssign(ast.Name("x", ast.Load()), ast.Add(),
666 ast.Name("y", ast.Load()))
667 self.stmt(aug, "must have Store context")
668 aug = ast.AugAssign(ast.Name("x", ast.Store()), ast.Add(),
669 ast.Name("y", ast.Store()))
670 self.stmt(aug, "must have Load context")
671
672 def test_for(self):
673 x = ast.Name("x", ast.Store())
674 y = ast.Name("y", ast.Load())
675 p = ast.Pass()
676 self.stmt(ast.For(x, y, [], []), "empty body on For")
677 self.stmt(ast.For(ast.Name("x", ast.Load()), y, [p], []),
678 "must have Store context")
679 self.stmt(ast.For(x, ast.Name("y", ast.Store()), [p], []),
680 "must have Load context")
681 e = ast.Expr(ast.Name("x", ast.Store()))
682 self.stmt(ast.For(x, y, [e], []), "must have Load context")
683 self.stmt(ast.For(x, y, [p], [e]), "must have Load context")
684
685 def test_while(self):
686 self.stmt(ast.While(ast.Num(3), [], []), "empty body on While")
687 self.stmt(ast.While(ast.Name("x", ast.Store()), [ast.Pass()], []),
688 "must have Load context")
689 self.stmt(ast.While(ast.Num(3), [ast.Pass()],
690 [ast.Expr(ast.Name("x", ast.Store()))]),
691 "must have Load context")
692
693 def test_if(self):
694 self.stmt(ast.If(ast.Num(3), [], []), "empty body on If")
695 i = ast.If(ast.Name("x", ast.Store()), [ast.Pass()], [])
696 self.stmt(i, "must have Load context")
697 i = ast.If(ast.Num(3), [ast.Expr(ast.Name("x", ast.Store()))], [])
698 self.stmt(i, "must have Load context")
699 i = ast.If(ast.Num(3), [ast.Pass()],
700 [ast.Expr(ast.Name("x", ast.Store()))])
701 self.stmt(i, "must have Load context")
702
703 def test_with(self):
704 p = ast.Pass()
705 self.stmt(ast.With([], [p]), "empty items on With")
706 i = ast.withitem(ast.Num(3), None)
707 self.stmt(ast.With([i], []), "empty body on With")
708 i = ast.withitem(ast.Name("x", ast.Store()), None)
709 self.stmt(ast.With([i], [p]), "must have Load context")
710 i = ast.withitem(ast.Num(3), ast.Name("x", ast.Load()))
711 self.stmt(ast.With([i], [p]), "must have Store context")
712
713 def test_raise(self):
714 r = ast.Raise(None, ast.Num(3))
715 self.stmt(r, "Raise with cause but no exception")
716 r = ast.Raise(ast.Name("x", ast.Store()), None)
717 self.stmt(r, "must have Load context")
718 r = ast.Raise(ast.Num(4), ast.Name("x", ast.Store()))
719 self.stmt(r, "must have Load context")
720
721 def test_try(self):
722 p = ast.Pass()
723 t = ast.Try([], [], [], [p])
724 self.stmt(t, "empty body on Try")
725 t = ast.Try([ast.Expr(ast.Name("x", ast.Store()))], [], [], [p])
726 self.stmt(t, "must have Load context")
727 t = ast.Try([p], [], [], [])
728 self.stmt(t, "Try has neither except handlers nor finalbody")
729 t = ast.Try([p], [], [p], [p])
730 self.stmt(t, "Try has orelse but no except handlers")
731 t = ast.Try([p], [ast.ExceptHandler(None, "x", [])], [], [])
732 self.stmt(t, "empty body on ExceptHandler")
733 e = [ast.ExceptHandler(ast.Name("x", ast.Store()), "y", [p])]
734 self.stmt(ast.Try([p], e, [], []), "must have Load context")
735 e = [ast.ExceptHandler(None, "x", [p])]
736 t = ast.Try([p], e, [ast.Expr(ast.Name("x", ast.Store()))], [p])
737 self.stmt(t, "must have Load context")
738 t = ast.Try([p], e, [p], [ast.Expr(ast.Name("x", ast.Store()))])
739 self.stmt(t, "must have Load context")
740
741 def test_assert(self):
742 self.stmt(ast.Assert(ast.Name("x", ast.Store()), None),
743 "must have Load context")
744 assrt = ast.Assert(ast.Name("x", ast.Load()),
745 ast.Name("y", ast.Store()))
746 self.stmt(assrt, "must have Load context")
747
748 def test_import(self):
749 self.stmt(ast.Import([]), "empty names on Import")
750
751 def test_importfrom(self):
752 imp = ast.ImportFrom(None, [ast.alias("x", None)], -42)
753 self.stmt(imp, "level less than -1")
754 self.stmt(ast.ImportFrom(None, [], 0), "empty names on ImportFrom")
755
756 def test_global(self):
757 self.stmt(ast.Global([]), "empty names on Global")
758
759 def test_nonlocal(self):
760 self.stmt(ast.Nonlocal([]), "empty names on Nonlocal")
761
762 def test_expr(self):
763 e = ast.Expr(ast.Name("x", ast.Store()))
764 self.stmt(e, "must have Load context")
765
766 def test_boolop(self):
767 b = ast.BoolOp(ast.And(), [])
768 self.expr(b, "less than 2 values")
769 b = ast.BoolOp(ast.And(), [ast.Num(3)])
770 self.expr(b, "less than 2 values")
771 b = ast.BoolOp(ast.And(), [ast.Num(4), None])
772 self.expr(b, "None disallowed")
773 b = ast.BoolOp(ast.And(), [ast.Num(4), ast.Name("x", ast.Store())])
774 self.expr(b, "must have Load context")
775
776 def test_unaryop(self):
777 u = ast.UnaryOp(ast.Not(), ast.Name("x", ast.Store()))
778 self.expr(u, "must have Load context")
779
780 def test_lambda(self):
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700781 a = ast.arguments([], None, [], [], None, [])
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500782 self.expr(ast.Lambda(a, ast.Name("x", ast.Store())),
783 "must have Load context")
784 def fac(args):
785 return ast.Lambda(args, ast.Name("x", ast.Load()))
786 self._check_arguments(fac, self.expr)
787
788 def test_ifexp(self):
789 l = ast.Name("x", ast.Load())
790 s = ast.Name("y", ast.Store())
791 for args in (s, l, l), (l, s, l), (l, l, s):
Benjamin Peterson71ce8972011-08-09 16:17:12 -0500792 self.expr(ast.IfExp(*args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500793
794 def test_dict(self):
795 d = ast.Dict([], [ast.Name("x", ast.Load())])
796 self.expr(d, "same number of keys as values")
797 d = ast.Dict([None], [ast.Name("x", ast.Load())])
798 self.expr(d, "None disallowed")
799 d = ast.Dict([ast.Name("x", ast.Load())], [None])
800 self.expr(d, "None disallowed")
801
802 def test_set(self):
803 self.expr(ast.Set([None]), "None disallowed")
804 s = ast.Set([ast.Name("x", ast.Store())])
805 self.expr(s, "must have Load context")
806
807 def _check_comprehension(self, fac):
808 self.expr(fac([]), "comprehension with no generators")
809 g = ast.comprehension(ast.Name("x", ast.Load()),
810 ast.Name("x", ast.Load()), [])
811 self.expr(fac([g]), "must have Store context")
812 g = ast.comprehension(ast.Name("x", ast.Store()),
813 ast.Name("x", ast.Store()), [])
814 self.expr(fac([g]), "must have Load context")
815 x = ast.Name("x", ast.Store())
816 y = ast.Name("y", ast.Load())
817 g = ast.comprehension(x, y, [None])
818 self.expr(fac([g]), "None disallowed")
819 g = ast.comprehension(x, y, [ast.Name("x", ast.Store())])
820 self.expr(fac([g]), "must have Load context")
821
822 def _simple_comp(self, fac):
823 g = ast.comprehension(ast.Name("x", ast.Store()),
824 ast.Name("x", ast.Load()), [])
825 self.expr(fac(ast.Name("x", ast.Store()), [g]),
826 "must have Load context")
827 def wrap(gens):
828 return fac(ast.Name("x", ast.Store()), gens)
829 self._check_comprehension(wrap)
830
831 def test_listcomp(self):
832 self._simple_comp(ast.ListComp)
833
834 def test_setcomp(self):
835 self._simple_comp(ast.SetComp)
836
837 def test_generatorexp(self):
838 self._simple_comp(ast.GeneratorExp)
839
840 def test_dictcomp(self):
841 g = ast.comprehension(ast.Name("y", ast.Store()),
842 ast.Name("p", ast.Load()), [])
843 c = ast.DictComp(ast.Name("x", ast.Store()),
844 ast.Name("y", ast.Load()), [g])
845 self.expr(c, "must have Load context")
846 c = ast.DictComp(ast.Name("x", ast.Load()),
847 ast.Name("y", ast.Store()), [g])
848 self.expr(c, "must have Load context")
849 def factory(comps):
850 k = ast.Name("x", ast.Load())
851 v = ast.Name("y", ast.Load())
852 return ast.DictComp(k, v, comps)
853 self._check_comprehension(factory)
854
855 def test_yield(self):
Benjamin Peterson527c6222012-01-14 08:58:23 -0500856 self.expr(ast.Yield(ast.Name("x", ast.Store())), "must have Load")
857 self.expr(ast.YieldFrom(ast.Name("x", ast.Store())), "must have Load")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500858
859 def test_compare(self):
860 left = ast.Name("x", ast.Load())
861 comp = ast.Compare(left, [ast.In()], [])
862 self.expr(comp, "no comparators")
863 comp = ast.Compare(left, [ast.In()], [ast.Num(4), ast.Num(5)])
864 self.expr(comp, "different number of comparators and operands")
865 comp = ast.Compare(ast.Num("blah"), [ast.In()], [left])
866 self.expr(comp, "non-numeric", exc=TypeError)
867 comp = ast.Compare(left, [ast.In()], [ast.Num("blah")])
868 self.expr(comp, "non-numeric", exc=TypeError)
869
870 def test_call(self):
871 func = ast.Name("x", ast.Load())
872 args = [ast.Name("y", ast.Load())]
873 keywords = [ast.keyword("w", ast.Name("z", ast.Load()))]
874 stararg = ast.Name("p", ast.Load())
875 kwarg = ast.Name("q", ast.Load())
876 call = ast.Call(ast.Name("x", ast.Store()), args, keywords, stararg,
877 kwarg)
878 self.expr(call, "must have Load context")
879 call = ast.Call(func, [None], keywords, stararg, kwarg)
880 self.expr(call, "None disallowed")
881 bad_keywords = [ast.keyword("w", ast.Name("z", ast.Store()))]
882 call = ast.Call(func, args, bad_keywords, stararg, kwarg)
883 self.expr(call, "must have Load context")
884 call = ast.Call(func, args, keywords, ast.Name("z", ast.Store()), kwarg)
885 self.expr(call, "must have Load context")
886 call = ast.Call(func, args, keywords, stararg,
887 ast.Name("w", ast.Store()))
888 self.expr(call, "must have Load context")
889
890 def test_num(self):
891 class subint(int):
892 pass
893 class subfloat(float):
894 pass
895 class subcomplex(complex):
896 pass
897 for obj in "0", "hello", subint(), subfloat(), subcomplex():
898 self.expr(ast.Num(obj), "non-numeric", exc=TypeError)
899
900 def test_attribute(self):
901 attr = ast.Attribute(ast.Name("x", ast.Store()), "y", ast.Load())
902 self.expr(attr, "must have Load context")
903
904 def test_subscript(self):
905 sub = ast.Subscript(ast.Name("x", ast.Store()), ast.Index(ast.Num(3)),
906 ast.Load())
907 self.expr(sub, "must have Load context")
908 x = ast.Name("x", ast.Load())
909 sub = ast.Subscript(x, ast.Index(ast.Name("y", ast.Store())),
910 ast.Load())
911 self.expr(sub, "must have Load context")
912 s = ast.Name("x", ast.Store())
913 for args in (s, None, None), (None, s, None), (None, None, s):
914 sl = ast.Slice(*args)
915 self.expr(ast.Subscript(x, sl, ast.Load()),
916 "must have Load context")
917 sl = ast.ExtSlice([])
918 self.expr(ast.Subscript(x, sl, ast.Load()), "empty dims on ExtSlice")
919 sl = ast.ExtSlice([ast.Index(s)])
920 self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context")
921
922 def test_starred(self):
923 left = ast.List([ast.Starred(ast.Name("x", ast.Load()), ast.Store())],
924 ast.Store())
925 assign = ast.Assign([left], ast.Num(4))
926 self.stmt(assign, "must have Store context")
927
928 def _sequence(self, fac):
929 self.expr(fac([None], ast.Load()), "None disallowed")
930 self.expr(fac([ast.Name("x", ast.Store())], ast.Load()),
931 "must have Load context")
932
933 def test_list(self):
934 self._sequence(ast.List)
935
936 def test_tuple(self):
937 self._sequence(ast.Tuple)
938
Benjamin Peterson442f2092012-12-06 17:41:04 -0500939 def test_nameconstant(self):
940 self.expr(ast.NameConstant(4), "singleton must be True, False, or None")
941
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500942 def test_stdlib_validates(self):
943 stdlib = os.path.dirname(ast.__file__)
944 tests = [fn for fn in os.listdir(stdlib) if fn.endswith(".py")]
945 tests.extend(["test/test_grammar.py", "test/test_unpack_ex.py"])
946 for module in tests:
947 fn = os.path.join(stdlib, module)
948 with open(fn, "r", encoding="utf-8") as fp:
949 source = fp.read()
Victor Stinnerd502a072013-03-22 00:06:20 +0100950 mod = ast.parse(source, fn)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500951 compile(mod, fn, "exec")
952
953
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000954def test_main():
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500955 support.run_unittest(AST_Tests, ASTHelpers_Test, ASTValidatorTests)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000956
957def main():
958 if __name__ != '__main__':
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000959 return
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000960 if sys.argv[1:] == ['-g']:
961 for statements, kind in ((exec_tests, "exec"), (single_tests, "single"),
962 (eval_tests, "eval")):
963 print(kind+"_results = [")
964 for s in statements:
965 print(repr(to_tuple(compile(s, "?", kind, 0x400)))+",")
966 print("]")
967 print("main()")
968 raise SystemExit
969 test_main()
Tim Peters400cbc32006-02-28 18:44:41 +0000970
971#### EVERYTHING BELOW IS GENERATED #####
972exec_results = [
Benjamin Peterson442f2092012-12-06 17:41:04 -0500973('Module', [('Expr', (1, 0), ('NameConstant', (1, 0), None))]),
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700974('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [('Pass', (1, 9))], [], None)]),
975('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None)], None, [], [], None, []), [('Pass', (1, 10))], [], None)]),
976('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None)], None, [], [], None, [('Num', (1, 8), 0)]), [('Pass', (1, 12))], [], None)]),
977('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], ('arg', (1, 7), 'args', None), [], [], None, []), [('Pass', (1, 14))], [], None)]),
978('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], ('arg', (1, 8), 'kwargs', None), []), [('Pass', (1, 17))], [], None)]),
979('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, 43), 'kwargs', None), [('Num', (1, 11), 1), ('NameConstant', (1, 16), None), ('List', (1, 24), [], ('Load',)), ('Dict', (1, 30), [], [])]), [('Pass', (1, 52))], [], None)]),
Neal Norwitzad74aa82008-03-31 05:14:30 +0000980('Module', [('ClassDef', (1, 0), 'C', [], [], None, None, [('Pass', (1, 8))], [])]),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500981('Module', [('ClassDef', (1, 0), 'C', [('Name', (1, 8), 'object', ('Load',))], [], None, None, [('Pass', (1, 17))], [])]),
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700982('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [('Return', (1, 8), ('Num', (1, 15), 1))], [], None)]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000983('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]),
984('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Num', (1, 4), 1))]),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000985('Module', [('AugAssign', (1, 0), ('Name', (1, 0), 'v', ('Store',)), ('Add',), ('Num', (1, 5), 1))]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000986('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Pass', (1, 11))], [])]),
987('Module', [('While', (1, 0), ('Name', (1, 6), 'v', ('Load',)), [('Pass', (1, 8))], [])]),
988('Module', [('If', (1, 0), ('Name', (1, 3), 'v', ('Load',)), [('Pass', (1, 5))], [])]),
Benjamin Petersonaeabd5f2011-05-27 15:02:03 -0500989('Module', [('With', (1, 0), [('withitem', ('Name', (1, 5), 'x', ('Load',)), ('Name', (1, 10), 'y', ('Store',)))], [('Pass', (1, 13))])]),
990('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))])]),
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700991('Module', [('Raise', (1, 0), ('Call', (1, 15), ('Name', (1, 6), 'Exception', ('Load',)), [('Str', (1, 16), 'string')], [], None, None), None)]),
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500992('Module', [('Try', (1, 0), [('Pass', (2, 2))], [('ExceptHandler', (3, 0), ('Name', (3, 7), 'Exception', ('Load',)), None, [('Pass', (4, 2))])], [], [])]),
993('Module', [('Try', (1, 0), [('Pass', (2, 2))], [], [], [('Pass', (4, 2))])]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000994('Module', [('Assert', (1, 0), ('Name', (1, 7), 'v', ('Load',)), None)]),
995('Module', [('Import', (1, 0), [('alias', 'sys', None)])]),
996('Module', [('ImportFrom', (1, 0), 'sys', [('alias', 'v', None)], 0)]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000997('Module', [('Global', (1, 0), ['v'])]),
998('Module', [('Expr', (1, 0), ('Num', (1, 0), 1))]),
999('Module', [('Pass', (1, 0))]),
1000('Module', [('Break', (1, 0))]),
1001('Module', [('Continue', (1, 0))]),
Benjamin Peterson2e4b0e12009-09-11 22:36:20 +00001002('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))], [])]),
1003('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',)), [])]))]),
1004('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',)), [])]))]),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001005('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',)), [])]))]),
1006('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',)), [])]))]),
1007('Module', [('Expr', (1, 0), ('DictComp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), ('Name', (1, 5), 'b', ('Load',)), [('comprehension', ('Name', (1, 11), 'w', ('Store',)), ('Name', (1, 16), 'x', ('Load',)), []), ('comprehension', ('Name', (1, 22), 'm', ('Store',)), ('Name', (1, 27), 'p', ('Load',)), [('Name', (1, 32), 'g', ('Load',))])]))]),
1008('Module', [('Expr', (1, 0), ('DictComp', (1, 1), ('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',)), [])]))]),
1009('Module', [('Expr', (1, 0), ('SetComp', (1, 1), ('Name', (1, 1), 'r', ('Load',)), [('comprehension', ('Name', (1, 7), 'l', ('Store',)), ('Name', (1, 12), 'x', ('Load',)), [('Name', (1, 17), 'g', ('Load',))])]))]),
1010('Module', [('Expr', (1, 0), ('SetComp', (1, 1), ('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',)), [])]))]),
Tim Peters400cbc32006-02-28 18:44:41 +00001011]
1012single_results = [
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001013('Interactive', [('Expr', (1, 0), ('BinOp', (1, 0), ('Num', (1, 0), 1), ('Add',), ('Num', (1, 2), 2)))]),
Tim Peters400cbc32006-02-28 18:44:41 +00001014]
1015eval_results = [
Benjamin Peterson442f2092012-12-06 17:41:04 -05001016('Expression', ('NameConstant', (1, 0), None)),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001017('Expression', ('BoolOp', (1, 0), ('And',), [('Name', (1, 0), 'a', ('Load',)), ('Name', (1, 6), 'b', ('Load',))])),
1018('Expression', ('BinOp', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Add',), ('Name', (1, 4), 'b', ('Load',)))),
1019('Expression', ('UnaryOp', (1, 0), ('Not',), ('Name', (1, 4), 'v', ('Load',)))),
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001020('Expression', ('Lambda', (1, 0), ('arguments', [], None, [], [], None, []), ('NameConstant', (1, 7), None))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001021('Expression', ('Dict', (1, 0), [('Num', (1, 2), 1)], [('Num', (1, 4), 2)])),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001022('Expression', ('Dict', (1, 0), [], [])),
Benjamin Peterson442f2092012-12-06 17:41:04 -05001023('Expression', ('Set', (1, 0), [('NameConstant', (1, 1), None)])),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001024('Expression', ('Dict', (1, 0), [('Num', (2, 6), 1)], [('Num', (4, 10), 2)])),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001025('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',))])])),
1026('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',))])])),
1027('Expression', ('Compare', (1, 0), ('Num', (1, 0), 1), [('Lt',), ('Lt',)], [('Num', (1, 4), 2), ('Num', (1, 8), 3)])),
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001028('Expression', ('Call', (1, 1), ('Name', (1, 0), 'f', ('Load',)), [('Num', (1, 2), 1), ('Num', (1, 4), 2)], [('keyword', 'c', ('Num', (1, 8), 3))], ('Name', (1, 11), 'd', ('Load',)), ('Name', (1, 15), 'e', ('Load',)))),
Neal Norwitzc1505362006-12-28 06:47:50 +00001029('Expression', ('Num', (1, 0), 10)),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001030('Expression', ('Str', (1, 0), 'string')),
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001031('Expression', ('Attribute', (1, 2), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',))),
1032('Expression', ('Subscript', (1, 2), ('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 +00001033('Expression', ('Name', (1, 0), 'v', ('Load',))),
1034('Expression', ('List', (1, 0), [('Num', (1, 1), 1), ('Num', (1, 3), 2), ('Num', (1, 5), 3)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001035('Expression', ('List', (1, 0), [], ('Load',))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001036('Expression', ('Tuple', (1, 0), [('Num', (1, 0), 1), ('Num', (1, 2), 2), ('Num', (1, 4), 3)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001037('Expression', ('Tuple', (1, 1), [('Num', (1, 1), 1), ('Num', (1, 3), 2), ('Num', (1, 5), 3)], ('Load',))),
1038('Expression', ('Tuple', (1, 0), [], ('Load',))),
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001039('Expression', ('Call', (1, 7), ('Attribute', (1, 6), ('Attribute', (1, 4), ('Attribute', (1, 2), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',)), 'c', ('Load',)), 'd', ('Load',)), [('Subscript', (1, 12), ('Attribute', (1, 10), ('Name', (1, 8), 'a', ('Load',)), 'b', ('Load',)), ('Slice', ('Num', (1, 12), 1), ('Num', (1, 14), 2), None), ('Load',))], [], None, None)),
Tim Peters400cbc32006-02-28 18:44:41 +00001040]
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001041main()