blob: a533f8693bc4312274fb714810f23941b795e5d4 [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"
Ezio Melotti85a86292013-08-17 16:57:41 +030025# There should be at least one test per statement
Tim Peters400cbc32006-02-28 18:44:41 +000026exec_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
Benjamin Petersone84fde92014-02-13 19:22:14 -050040 "def f(a, b=1, c=None, d=[], e={}, *args, f=42, **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 Peterson7a66fc22015-02-02 10:51:20 -0500183 def _assertTrueorder(self, ast_node, parent_pos):
Georg Brandl0c77a822008-06-10 16:37:50 +0000184 if not isinstance(ast_node, ast.AST) or ast_node._fields is None:
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000185 return
Georg Brandl0c77a822008-06-10 16:37:50 +0000186 if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000187 node_pos = (ast_node.lineno, ast_node.col_offset)
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500188 self.assertTrue(node_pos >= parent_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000189 parent_pos = (ast_node.lineno, ast_node.col_offset)
190 for name in ast_node._fields:
191 value = getattr(ast_node, name)
192 if isinstance(value, list):
193 for child in value:
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500194 self._assertTrueorder(child, parent_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000195 elif value is not None:
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500196 self._assertTrueorder(value, parent_pos)
Tim Peters5ddfe412006-03-01 23:02:57 +0000197
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500198 def test_AST_objects(self):
199 x = ast.AST()
200 self.assertEqual(x._fields, ())
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700201 x.foobar = 42
202 self.assertEqual(x.foobar, 42)
203 self.assertEqual(x.__dict__["foobar"], 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500204
205 with self.assertRaises(AttributeError):
206 x.vararg
207
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500208 with self.assertRaises(TypeError):
209 # "_ast.AST constructor takes 0 positional arguments"
210 ast.AST(2)
211
Benjamin Peterson9ed37432012-07-08 11:13:36 -0700212 def test_AST_garbage_collection(self):
213 class X:
214 pass
215 a = ast.AST()
216 a.x = X()
217 a.x.a = a
218 ref = weakref.ref(a.x)
219 del a
220 support.gc_collect()
221 self.assertIsNone(ref())
222
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000223 def test_snippets(self):
224 for input, output, kind in ((exec_tests, exec_results, "exec"),
225 (single_tests, single_results, "single"),
226 (eval_tests, eval_results, "eval")):
227 for i, o in zip(input, output):
Georg Brandl0c77a822008-06-10 16:37:50 +0000228 ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000229 self.assertEqual(to_tuple(ast_tree), o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000230 self._assertTrueorder(ast_tree, (0, 0))
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000231
Benjamin Peterson78565b22009-06-28 19:19:51 +0000232 def test_slice(self):
233 slc = ast.parse("x[::]").body[0].value.slice
234 self.assertIsNone(slc.upper)
235 self.assertIsNone(slc.lower)
236 self.assertIsNone(slc.step)
237
238 def test_from_import(self):
239 im = ast.parse("from . import y").body[0]
240 self.assertIsNone(im.module)
241
Benjamin Petersona4e4e352012-03-22 08:19:04 -0400242 def test_non_interned_future_from_ast(self):
243 mod = ast.parse("from __future__ import division")
244 self.assertIsInstance(mod.body[0], ast.ImportFrom)
245 mod.body[0].module = " __future__ ".strip()
246 compile(mod, "<test>", "exec")
247
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000248 def test_base_classes(self):
249 self.assertTrue(issubclass(ast.For, ast.stmt))
250 self.assertTrue(issubclass(ast.Name, ast.expr))
251 self.assertTrue(issubclass(ast.stmt, ast.AST))
252 self.assertTrue(issubclass(ast.expr, ast.AST))
253 self.assertTrue(issubclass(ast.comprehension, ast.AST))
254 self.assertTrue(issubclass(ast.Gt, ast.AST))
255
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500256 def test_field_attr_existence(self):
257 for name, item in ast.__dict__.items():
258 if isinstance(item, type) and name != 'AST' and name[0].isupper():
259 x = item()
260 if isinstance(x, ast.AST):
261 self.assertEqual(type(x._fields), tuple)
262
263 def test_arguments(self):
264 x = ast.arguments()
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500265 self.assertEqual(x._fields, ('args', 'vararg', 'kwonlyargs',
266 'kw_defaults', 'kwarg', 'defaults'))
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500267
268 with self.assertRaises(AttributeError):
269 x.vararg
270
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700271 x = ast.arguments(*range(1, 7))
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500272 self.assertEqual(x.vararg, 2)
273
274 def test_field_attr_writable(self):
275 x = ast.Num()
276 # We can assign to _fields
277 x._fields = 666
278 self.assertEqual(x._fields, 666)
279
280 def test_classattrs(self):
281 x = ast.Num()
282 self.assertEqual(x._fields, ('n',))
283
284 with self.assertRaises(AttributeError):
285 x.n
286
287 x = ast.Num(42)
288 self.assertEqual(x.n, 42)
289
290 with self.assertRaises(AttributeError):
291 x.lineno
292
293 with self.assertRaises(AttributeError):
294 x.foobar
295
296 x = ast.Num(lineno=2)
297 self.assertEqual(x.lineno, 2)
298
299 x = ast.Num(42, lineno=0)
300 self.assertEqual(x.lineno, 0)
301 self.assertEqual(x._fields, ('n',))
302 self.assertEqual(x.n, 42)
303
304 self.assertRaises(TypeError, ast.Num, 1, 2)
305 self.assertRaises(TypeError, ast.Num, 1, 2, lineno=0)
306
307 def test_module(self):
308 body = [ast.Num(42)]
309 x = ast.Module(body)
310 self.assertEqual(x.body, body)
311
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000312 def test_nodeclasses(self):
Florent Xicluna992d9e02011-11-11 19:35:42 +0100313 # Zero arguments constructor explicitly allowed
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500314 x = ast.BinOp()
315 self.assertEqual(x._fields, ('left', 'op', 'right'))
316
317 # Random attribute allowed too
318 x.foobarbaz = 5
319 self.assertEqual(x.foobarbaz, 5)
320
321 n1 = ast.Num(1)
322 n3 = ast.Num(3)
323 addop = ast.Add()
324 x = ast.BinOp(n1, addop, n3)
325 self.assertEqual(x.left, n1)
326 self.assertEqual(x.op, addop)
327 self.assertEqual(x.right, n3)
Benjamin Peterson68b543a2011-06-27 17:51:18 -0500328
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500329 x = ast.BinOp(1, 2, 3)
330 self.assertEqual(x.left, 1)
331 self.assertEqual(x.op, 2)
332 self.assertEqual(x.right, 3)
333
Georg Brandl0c77a822008-06-10 16:37:50 +0000334 x = ast.BinOp(1, 2, 3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000335 self.assertEqual(x.left, 1)
336 self.assertEqual(x.op, 2)
337 self.assertEqual(x.right, 3)
338 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000339
340 # node raises exception when not given enough arguments
Georg Brandl0c77a822008-06-10 16:37:50 +0000341 self.assertRaises(TypeError, ast.BinOp, 1, 2)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500342 # node raises exception when given too many arguments
343 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4)
344 # node raises exception when not given enough arguments
345 self.assertRaises(TypeError, ast.BinOp, 1, 2, lineno=0)
346 # node raises exception when given too many arguments
347 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4, lineno=0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000348
349 # can set attributes through kwargs too
Georg Brandl0c77a822008-06-10 16:37:50 +0000350 x = ast.BinOp(left=1, op=2, right=3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000351 self.assertEqual(x.left, 1)
352 self.assertEqual(x.op, 2)
353 self.assertEqual(x.right, 3)
354 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000355
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500356 # Random kwargs also allowed
357 x = ast.BinOp(1, 2, 3, foobarbaz=42)
358 self.assertEqual(x.foobarbaz, 42)
359
360 def test_no_fields(self):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000361 # this used to fail because Sub._fields was None
Georg Brandl0c77a822008-06-10 16:37:50 +0000362 x = ast.Sub()
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500363 self.assertEqual(x._fields, ())
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000364
365 def test_pickling(self):
366 import pickle
367 mods = [pickle]
368 try:
369 import cPickle
370 mods.append(cPickle)
371 except ImportError:
372 pass
373 protocols = [0, 1, 2]
374 for mod in mods:
375 for protocol in protocols:
376 for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests):
377 ast2 = mod.loads(mod.dumps(ast, protocol))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000378 self.assertEqual(to_tuple(ast2), to_tuple(ast))
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000379
Benjamin Peterson5b066812010-11-20 01:38:49 +0000380 def test_invalid_sum(self):
381 pos = dict(lineno=2, col_offset=3)
382 m = ast.Module([ast.Expr(ast.expr(**pos), **pos)])
383 with self.assertRaises(TypeError) as cm:
384 compile(m, "<test>", "exec")
385 self.assertIn("but got <_ast.expr", str(cm.exception))
386
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500387 def test_invalid_identitifer(self):
388 m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))])
389 ast.fix_missing_locations(m)
390 with self.assertRaises(TypeError) as cm:
391 compile(m, "<test>", "exec")
392 self.assertIn("identifier must be of type str", str(cm.exception))
393
394 def test_invalid_string(self):
395 m = ast.Module([ast.Expr(ast.Str(42))])
396 ast.fix_missing_locations(m)
397 with self.assertRaises(TypeError) as cm:
398 compile(m, "<test>", "exec")
399 self.assertIn("string must be of type str", str(cm.exception))
400
Mark Dickinsonded35ae2012-11-25 14:36:26 +0000401 def test_empty_yield_from(self):
402 # Issue 16546: yield from value is not optional.
403 empty_yield_from = ast.parse("def f():\n yield from g()")
404 empty_yield_from.body[0].body[0].value.value = None
405 with self.assertRaises(ValueError) as cm:
406 compile(empty_yield_from, "<test>", "exec")
407 self.assertIn("field value is required", str(cm.exception))
408
Georg Brandl0c77a822008-06-10 16:37:50 +0000409
410class ASTHelpers_Test(unittest.TestCase):
411
412 def test_parse(self):
413 a = ast.parse('foo(1 + 1)')
414 b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST)
415 self.assertEqual(ast.dump(a), ast.dump(b))
416
Benjamin Peterson2e2c9032012-09-02 14:23:15 -0400417 def test_parse_in_error(self):
418 try:
419 1/0
420 except Exception:
Benjamin Petersonbd0df502012-09-02 15:04:51 -0400421 with self.assertRaises(SyntaxError) as e:
422 ast.literal_eval(r"'\U'")
423 self.assertIsNotNone(e.exception.__context__)
Benjamin Peterson2e2c9032012-09-02 14:23:15 -0400424
Georg Brandl0c77a822008-06-10 16:37:50 +0000425 def test_dump(self):
426 node = ast.parse('spam(eggs, "and cheese")')
427 self.assertEqual(ast.dump(node),
428 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
429 "args=[Name(id='eggs', ctx=Load()), Str(s='and cheese')], "
430 "keywords=[], starargs=None, kwargs=None))])"
431 )
432 self.assertEqual(ast.dump(node, annotate_fields=False),
433 "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
434 "Str('and cheese')], [], None, None))])"
435 )
436 self.assertEqual(ast.dump(node, include_attributes=True),
437 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
438 "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), "
439 "lineno=1, col_offset=5), Str(s='and cheese', lineno=1, "
440 "col_offset=11)], keywords=[], starargs=None, kwargs=None, "
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500441 "lineno=1, col_offset=0), lineno=1, col_offset=0)])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000442 )
443
444 def test_copy_location(self):
445 src = ast.parse('1 + 1', mode='eval')
446 src.body.right = ast.copy_location(ast.Num(2), src.body.right)
447 self.assertEqual(ast.dump(src, include_attributes=True),
448 'Expression(body=BinOp(left=Num(n=1, lineno=1, col_offset=0), '
449 'op=Add(), right=Num(n=2, lineno=1, col_offset=4), lineno=1, '
450 'col_offset=0))'
451 )
452
453 def test_fix_missing_locations(self):
454 src = ast.parse('write("spam")')
455 src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()),
456 [ast.Str('eggs')], [], None, None)))
457 self.assertEqual(src, ast.fix_missing_locations(src))
458 self.assertEqual(ast.dump(src, include_attributes=True),
459 "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), "
460 "lineno=1, col_offset=0), args=[Str(s='spam', lineno=1, "
461 "col_offset=6)], keywords=[], starargs=None, kwargs=None, "
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500462 "lineno=1, col_offset=0), lineno=1, col_offset=0), "
Georg Brandl0c77a822008-06-10 16:37:50 +0000463 "Expr(value=Call(func=Name(id='spam', ctx=Load(), lineno=1, "
464 "col_offset=0), args=[Str(s='eggs', lineno=1, col_offset=0)], "
465 "keywords=[], starargs=None, kwargs=None, lineno=1, "
466 "col_offset=0), lineno=1, col_offset=0)])"
467 )
468
469 def test_increment_lineno(self):
470 src = ast.parse('1 + 1', mode='eval')
471 self.assertEqual(ast.increment_lineno(src, n=3), src)
472 self.assertEqual(ast.dump(src, include_attributes=True),
473 'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
474 'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
475 'col_offset=0))'
476 )
Georg Brandl619e7ba2011-01-09 07:38:51 +0000477 # issue10869: do not increment lineno of root twice
Georg Brandlefb69022011-01-09 07:50:48 +0000478 src = ast.parse('1 + 1', mode='eval')
Georg Brandl619e7ba2011-01-09 07:38:51 +0000479 self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
480 self.assertEqual(ast.dump(src, include_attributes=True),
481 'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
482 'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
483 'col_offset=0))'
484 )
Georg Brandl0c77a822008-06-10 16:37:50 +0000485
486 def test_iter_fields(self):
487 node = ast.parse('foo()', mode='eval')
488 d = dict(ast.iter_fields(node.body))
489 self.assertEqual(d.pop('func').id, 'foo')
490 self.assertEqual(d, {'keywords': [], 'kwargs': None,
491 'args': [], 'starargs': None})
492
493 def test_iter_child_nodes(self):
494 node = ast.parse("spam(23, 42, eggs='leek')", mode='eval')
495 self.assertEqual(len(list(ast.iter_child_nodes(node.body))), 4)
496 iterator = ast.iter_child_nodes(node.body)
497 self.assertEqual(next(iterator).id, 'spam')
498 self.assertEqual(next(iterator).n, 23)
499 self.assertEqual(next(iterator).n, 42)
500 self.assertEqual(ast.dump(next(iterator)),
501 "keyword(arg='eggs', value=Str(s='leek'))"
502 )
503
504 def test_get_docstring(self):
505 node = ast.parse('def foo():\n """line one\n line two"""')
506 self.assertEqual(ast.get_docstring(node.body[0]),
507 'line one\nline two')
508
509 def test_literal_eval(self):
510 self.assertEqual(ast.literal_eval('[1, 2, 3]'), [1, 2, 3])
511 self.assertEqual(ast.literal_eval('{"foo": 42}'), {"foo": 42})
512 self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None))
Benjamin Peterson3e742892010-07-11 12:59:24 +0000513 self.assertEqual(ast.literal_eval('{1, 2, 3}'), {1, 2, 3})
Benjamin Peterson5ef96e52010-07-11 23:06:06 +0000514 self.assertEqual(ast.literal_eval('b"hi"'), b"hi")
Georg Brandl0c77a822008-06-10 16:37:50 +0000515 self.assertRaises(ValueError, ast.literal_eval, 'foo()')
Raymond Hettingerbc959732010-10-08 00:47:45 +0000516 self.assertEqual(ast.literal_eval('-6'), -6)
517 self.assertEqual(ast.literal_eval('-6j+3'), 3-6j)
518 self.assertEqual(ast.literal_eval('3.25'), 3.25)
Georg Brandl0c77a822008-06-10 16:37:50 +0000519
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000520 def test_literal_eval_issue4907(self):
521 self.assertEqual(ast.literal_eval('2j'), 2j)
522 self.assertEqual(ast.literal_eval('10 + 2j'), 10 + 2j)
523 self.assertEqual(ast.literal_eval('1.5 - 2j'), 1.5 - 2j)
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000524
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100525 def test_bad_integer(self):
526 # issue13436: Bad error message with invalid numeric values
527 body = [ast.ImportFrom(module='time',
528 names=[ast.alias(name='sleep')],
529 level=None,
530 lineno=None, col_offset=None)]
531 mod = ast.Module(body)
532 with self.assertRaises(ValueError) as cm:
533 compile(mod, 'test', 'exec')
534 self.assertIn("invalid integer value: None", str(cm.exception))
535
Georg Brandl0c77a822008-06-10 16:37:50 +0000536
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500537class ASTValidatorTests(unittest.TestCase):
538
539 def mod(self, mod, msg=None, mode="exec", *, exc=ValueError):
540 mod.lineno = mod.col_offset = 0
541 ast.fix_missing_locations(mod)
542 with self.assertRaises(exc) as cm:
543 compile(mod, "<test>", mode)
544 if msg is not None:
545 self.assertIn(msg, str(cm.exception))
546
547 def expr(self, node, msg=None, *, exc=ValueError):
548 mod = ast.Module([ast.Expr(node)])
549 self.mod(mod, msg, exc=exc)
550
551 def stmt(self, stmt, msg=None):
552 mod = ast.Module([stmt])
553 self.mod(mod, msg)
554
555 def test_module(self):
556 m = ast.Interactive([ast.Expr(ast.Name("x", ast.Store()))])
557 self.mod(m, "must have Load context", "single")
558 m = ast.Expression(ast.Name("x", ast.Store()))
559 self.mod(m, "must have Load context", "eval")
560
561 def _check_arguments(self, fac, check):
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700562 def arguments(args=None, vararg=None,
563 kwonlyargs=None, kwarg=None,
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500564 defaults=None, kw_defaults=None):
565 if args is None:
566 args = []
567 if kwonlyargs is None:
568 kwonlyargs = []
569 if defaults is None:
570 defaults = []
571 if kw_defaults is None:
572 kw_defaults = []
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700573 args = ast.arguments(args, vararg, kwonlyargs, kw_defaults,
574 kwarg, defaults)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500575 return fac(args)
576 args = [ast.arg("x", ast.Name("x", ast.Store()))]
577 check(arguments(args=args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500578 check(arguments(kwonlyargs=args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500579 check(arguments(defaults=[ast.Num(3)]),
580 "more positional defaults than args")
581 check(arguments(kw_defaults=[ast.Num(4)]),
582 "length of kwonlyargs is not the same as kw_defaults")
583 args = [ast.arg("x", ast.Name("x", ast.Load()))]
584 check(arguments(args=args, defaults=[ast.Name("x", ast.Store())]),
585 "must have Load context")
586 args = [ast.arg("a", ast.Name("x", ast.Load())),
587 ast.arg("b", ast.Name("y", ast.Load()))]
588 check(arguments(kwonlyargs=args,
589 kw_defaults=[None, ast.Name("x", ast.Store())]),
590 "must have Load context")
591
592 def test_funcdef(self):
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700593 a = ast.arguments([], None, [], [], None, [])
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500594 f = ast.FunctionDef("x", a, [], [], None)
595 self.stmt(f, "empty body on FunctionDef")
596 f = ast.FunctionDef("x", a, [ast.Pass()], [ast.Name("x", ast.Store())],
597 None)
598 self.stmt(f, "must have Load context")
599 f = ast.FunctionDef("x", a, [ast.Pass()], [],
600 ast.Name("x", ast.Store()))
601 self.stmt(f, "must have Load context")
602 def fac(args):
603 return ast.FunctionDef("x", args, [ast.Pass()], [], None)
604 self._check_arguments(fac, self.stmt)
605
606 def test_classdef(self):
607 def cls(bases=None, keywords=None, starargs=None, kwargs=None,
608 body=None, decorator_list=None):
609 if bases is None:
610 bases = []
611 if keywords is None:
612 keywords = []
613 if body is None:
614 body = [ast.Pass()]
615 if decorator_list is None:
616 decorator_list = []
617 return ast.ClassDef("myclass", bases, keywords, starargs,
618 kwargs, body, decorator_list)
619 self.stmt(cls(bases=[ast.Name("x", ast.Store())]),
620 "must have Load context")
621 self.stmt(cls(keywords=[ast.keyword("x", ast.Name("x", ast.Store()))]),
622 "must have Load context")
623 self.stmt(cls(starargs=ast.Name("x", ast.Store())),
624 "must have Load context")
625 self.stmt(cls(kwargs=ast.Name("x", ast.Store())),
626 "must have Load context")
627 self.stmt(cls(body=[]), "empty body on ClassDef")
628 self.stmt(cls(body=[None]), "None disallowed")
629 self.stmt(cls(decorator_list=[ast.Name("x", ast.Store())]),
630 "must have Load context")
631
632 def test_delete(self):
633 self.stmt(ast.Delete([]), "empty targets on Delete")
634 self.stmt(ast.Delete([None]), "None disallowed")
635 self.stmt(ast.Delete([ast.Name("x", ast.Load())]),
636 "must have Del context")
637
638 def test_assign(self):
639 self.stmt(ast.Assign([], ast.Num(3)), "empty targets on Assign")
640 self.stmt(ast.Assign([None], ast.Num(3)), "None disallowed")
641 self.stmt(ast.Assign([ast.Name("x", ast.Load())], ast.Num(3)),
642 "must have Store context")
643 self.stmt(ast.Assign([ast.Name("x", ast.Store())],
644 ast.Name("y", ast.Store())),
645 "must have Load context")
646
647 def test_augassign(self):
648 aug = ast.AugAssign(ast.Name("x", ast.Load()), ast.Add(),
649 ast.Name("y", ast.Load()))
650 self.stmt(aug, "must have Store context")
651 aug = ast.AugAssign(ast.Name("x", ast.Store()), ast.Add(),
652 ast.Name("y", ast.Store()))
653 self.stmt(aug, "must have Load context")
654
655 def test_for(self):
656 x = ast.Name("x", ast.Store())
657 y = ast.Name("y", ast.Load())
658 p = ast.Pass()
659 self.stmt(ast.For(x, y, [], []), "empty body on For")
660 self.stmt(ast.For(ast.Name("x", ast.Load()), y, [p], []),
661 "must have Store context")
662 self.stmt(ast.For(x, ast.Name("y", ast.Store()), [p], []),
663 "must have Load context")
664 e = ast.Expr(ast.Name("x", ast.Store()))
665 self.stmt(ast.For(x, y, [e], []), "must have Load context")
666 self.stmt(ast.For(x, y, [p], [e]), "must have Load context")
667
668 def test_while(self):
669 self.stmt(ast.While(ast.Num(3), [], []), "empty body on While")
670 self.stmt(ast.While(ast.Name("x", ast.Store()), [ast.Pass()], []),
671 "must have Load context")
672 self.stmt(ast.While(ast.Num(3), [ast.Pass()],
673 [ast.Expr(ast.Name("x", ast.Store()))]),
674 "must have Load context")
675
676 def test_if(self):
677 self.stmt(ast.If(ast.Num(3), [], []), "empty body on If")
678 i = ast.If(ast.Name("x", ast.Store()), [ast.Pass()], [])
679 self.stmt(i, "must have Load context")
680 i = ast.If(ast.Num(3), [ast.Expr(ast.Name("x", ast.Store()))], [])
681 self.stmt(i, "must have Load context")
682 i = ast.If(ast.Num(3), [ast.Pass()],
683 [ast.Expr(ast.Name("x", ast.Store()))])
684 self.stmt(i, "must have Load context")
685
686 def test_with(self):
687 p = ast.Pass()
688 self.stmt(ast.With([], [p]), "empty items on With")
689 i = ast.withitem(ast.Num(3), None)
690 self.stmt(ast.With([i], []), "empty body on With")
691 i = ast.withitem(ast.Name("x", ast.Store()), None)
692 self.stmt(ast.With([i], [p]), "must have Load context")
693 i = ast.withitem(ast.Num(3), ast.Name("x", ast.Load()))
694 self.stmt(ast.With([i], [p]), "must have Store context")
695
696 def test_raise(self):
697 r = ast.Raise(None, ast.Num(3))
698 self.stmt(r, "Raise with cause but no exception")
699 r = ast.Raise(ast.Name("x", ast.Store()), None)
700 self.stmt(r, "must have Load context")
701 r = ast.Raise(ast.Num(4), ast.Name("x", ast.Store()))
702 self.stmt(r, "must have Load context")
703
704 def test_try(self):
705 p = ast.Pass()
706 t = ast.Try([], [], [], [p])
707 self.stmt(t, "empty body on Try")
708 t = ast.Try([ast.Expr(ast.Name("x", ast.Store()))], [], [], [p])
709 self.stmt(t, "must have Load context")
710 t = ast.Try([p], [], [], [])
711 self.stmt(t, "Try has neither except handlers nor finalbody")
712 t = ast.Try([p], [], [p], [p])
713 self.stmt(t, "Try has orelse but no except handlers")
714 t = ast.Try([p], [ast.ExceptHandler(None, "x", [])], [], [])
715 self.stmt(t, "empty body on ExceptHandler")
716 e = [ast.ExceptHandler(ast.Name("x", ast.Store()), "y", [p])]
717 self.stmt(ast.Try([p], e, [], []), "must have Load context")
718 e = [ast.ExceptHandler(None, "x", [p])]
719 t = ast.Try([p], e, [ast.Expr(ast.Name("x", ast.Store()))], [p])
720 self.stmt(t, "must have Load context")
721 t = ast.Try([p], e, [p], [ast.Expr(ast.Name("x", ast.Store()))])
722 self.stmt(t, "must have Load context")
723
724 def test_assert(self):
725 self.stmt(ast.Assert(ast.Name("x", ast.Store()), None),
726 "must have Load context")
727 assrt = ast.Assert(ast.Name("x", ast.Load()),
728 ast.Name("y", ast.Store()))
729 self.stmt(assrt, "must have Load context")
730
731 def test_import(self):
732 self.stmt(ast.Import([]), "empty names on Import")
733
734 def test_importfrom(self):
735 imp = ast.ImportFrom(None, [ast.alias("x", None)], -42)
736 self.stmt(imp, "level less than -1")
737 self.stmt(ast.ImportFrom(None, [], 0), "empty names on ImportFrom")
738
739 def test_global(self):
740 self.stmt(ast.Global([]), "empty names on Global")
741
742 def test_nonlocal(self):
743 self.stmt(ast.Nonlocal([]), "empty names on Nonlocal")
744
745 def test_expr(self):
746 e = ast.Expr(ast.Name("x", ast.Store()))
747 self.stmt(e, "must have Load context")
748
749 def test_boolop(self):
750 b = ast.BoolOp(ast.And(), [])
751 self.expr(b, "less than 2 values")
752 b = ast.BoolOp(ast.And(), [ast.Num(3)])
753 self.expr(b, "less than 2 values")
754 b = ast.BoolOp(ast.And(), [ast.Num(4), None])
755 self.expr(b, "None disallowed")
756 b = ast.BoolOp(ast.And(), [ast.Num(4), ast.Name("x", ast.Store())])
757 self.expr(b, "must have Load context")
758
759 def test_unaryop(self):
760 u = ast.UnaryOp(ast.Not(), ast.Name("x", ast.Store()))
761 self.expr(u, "must have Load context")
762
763 def test_lambda(self):
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700764 a = ast.arguments([], None, [], [], None, [])
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500765 self.expr(ast.Lambda(a, ast.Name("x", ast.Store())),
766 "must have Load context")
767 def fac(args):
768 return ast.Lambda(args, ast.Name("x", ast.Load()))
769 self._check_arguments(fac, self.expr)
770
771 def test_ifexp(self):
772 l = ast.Name("x", ast.Load())
773 s = ast.Name("y", ast.Store())
774 for args in (s, l, l), (l, s, l), (l, l, s):
Benjamin Peterson71ce8972011-08-09 16:17:12 -0500775 self.expr(ast.IfExp(*args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500776
777 def test_dict(self):
778 d = ast.Dict([], [ast.Name("x", ast.Load())])
779 self.expr(d, "same number of keys as values")
780 d = ast.Dict([None], [ast.Name("x", ast.Load())])
781 self.expr(d, "None disallowed")
782 d = ast.Dict([ast.Name("x", ast.Load())], [None])
783 self.expr(d, "None disallowed")
784
785 def test_set(self):
786 self.expr(ast.Set([None]), "None disallowed")
787 s = ast.Set([ast.Name("x", ast.Store())])
788 self.expr(s, "must have Load context")
789
790 def _check_comprehension(self, fac):
791 self.expr(fac([]), "comprehension with no generators")
792 g = ast.comprehension(ast.Name("x", ast.Load()),
793 ast.Name("x", ast.Load()), [])
794 self.expr(fac([g]), "must have Store context")
795 g = ast.comprehension(ast.Name("x", ast.Store()),
796 ast.Name("x", ast.Store()), [])
797 self.expr(fac([g]), "must have Load context")
798 x = ast.Name("x", ast.Store())
799 y = ast.Name("y", ast.Load())
800 g = ast.comprehension(x, y, [None])
801 self.expr(fac([g]), "None disallowed")
802 g = ast.comprehension(x, y, [ast.Name("x", ast.Store())])
803 self.expr(fac([g]), "must have Load context")
804
805 def _simple_comp(self, fac):
806 g = ast.comprehension(ast.Name("x", ast.Store()),
807 ast.Name("x", ast.Load()), [])
808 self.expr(fac(ast.Name("x", ast.Store()), [g]),
809 "must have Load context")
810 def wrap(gens):
811 return fac(ast.Name("x", ast.Store()), gens)
812 self._check_comprehension(wrap)
813
814 def test_listcomp(self):
815 self._simple_comp(ast.ListComp)
816
817 def test_setcomp(self):
818 self._simple_comp(ast.SetComp)
819
820 def test_generatorexp(self):
821 self._simple_comp(ast.GeneratorExp)
822
823 def test_dictcomp(self):
824 g = ast.comprehension(ast.Name("y", ast.Store()),
825 ast.Name("p", ast.Load()), [])
826 c = ast.DictComp(ast.Name("x", ast.Store()),
827 ast.Name("y", ast.Load()), [g])
828 self.expr(c, "must have Load context")
829 c = ast.DictComp(ast.Name("x", ast.Load()),
830 ast.Name("y", ast.Store()), [g])
831 self.expr(c, "must have Load context")
832 def factory(comps):
833 k = ast.Name("x", ast.Load())
834 v = ast.Name("y", ast.Load())
835 return ast.DictComp(k, v, comps)
836 self._check_comprehension(factory)
837
838 def test_yield(self):
Benjamin Peterson527c6222012-01-14 08:58:23 -0500839 self.expr(ast.Yield(ast.Name("x", ast.Store())), "must have Load")
840 self.expr(ast.YieldFrom(ast.Name("x", ast.Store())), "must have Load")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500841
842 def test_compare(self):
843 left = ast.Name("x", ast.Load())
844 comp = ast.Compare(left, [ast.In()], [])
845 self.expr(comp, "no comparators")
846 comp = ast.Compare(left, [ast.In()], [ast.Num(4), ast.Num(5)])
847 self.expr(comp, "different number of comparators and operands")
848 comp = ast.Compare(ast.Num("blah"), [ast.In()], [left])
849 self.expr(comp, "non-numeric", exc=TypeError)
850 comp = ast.Compare(left, [ast.In()], [ast.Num("blah")])
851 self.expr(comp, "non-numeric", exc=TypeError)
852
853 def test_call(self):
854 func = ast.Name("x", ast.Load())
855 args = [ast.Name("y", ast.Load())]
856 keywords = [ast.keyword("w", ast.Name("z", ast.Load()))]
857 stararg = ast.Name("p", ast.Load())
858 kwarg = ast.Name("q", ast.Load())
859 call = ast.Call(ast.Name("x", ast.Store()), args, keywords, stararg,
860 kwarg)
861 self.expr(call, "must have Load context")
862 call = ast.Call(func, [None], keywords, stararg, kwarg)
863 self.expr(call, "None disallowed")
864 bad_keywords = [ast.keyword("w", ast.Name("z", ast.Store()))]
865 call = ast.Call(func, args, bad_keywords, stararg, kwarg)
866 self.expr(call, "must have Load context")
867 call = ast.Call(func, args, keywords, ast.Name("z", ast.Store()), kwarg)
868 self.expr(call, "must have Load context")
869 call = ast.Call(func, args, keywords, stararg,
870 ast.Name("w", ast.Store()))
871 self.expr(call, "must have Load context")
872
873 def test_num(self):
874 class subint(int):
875 pass
876 class subfloat(float):
877 pass
878 class subcomplex(complex):
879 pass
880 for obj in "0", "hello", subint(), subfloat(), subcomplex():
881 self.expr(ast.Num(obj), "non-numeric", exc=TypeError)
882
883 def test_attribute(self):
884 attr = ast.Attribute(ast.Name("x", ast.Store()), "y", ast.Load())
885 self.expr(attr, "must have Load context")
886
887 def test_subscript(self):
888 sub = ast.Subscript(ast.Name("x", ast.Store()), ast.Index(ast.Num(3)),
889 ast.Load())
890 self.expr(sub, "must have Load context")
891 x = ast.Name("x", ast.Load())
892 sub = ast.Subscript(x, ast.Index(ast.Name("y", ast.Store())),
893 ast.Load())
894 self.expr(sub, "must have Load context")
895 s = ast.Name("x", ast.Store())
896 for args in (s, None, None), (None, s, None), (None, None, s):
897 sl = ast.Slice(*args)
898 self.expr(ast.Subscript(x, sl, ast.Load()),
899 "must have Load context")
900 sl = ast.ExtSlice([])
901 self.expr(ast.Subscript(x, sl, ast.Load()), "empty dims on ExtSlice")
902 sl = ast.ExtSlice([ast.Index(s)])
903 self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context")
904
905 def test_starred(self):
906 left = ast.List([ast.Starred(ast.Name("x", ast.Load()), ast.Store())],
907 ast.Store())
908 assign = ast.Assign([left], ast.Num(4))
909 self.stmt(assign, "must have Store context")
910
911 def _sequence(self, fac):
912 self.expr(fac([None], ast.Load()), "None disallowed")
913 self.expr(fac([ast.Name("x", ast.Store())], ast.Load()),
914 "must have Load context")
915
916 def test_list(self):
917 self._sequence(ast.List)
918
919 def test_tuple(self):
920 self._sequence(ast.Tuple)
921
Benjamin Peterson442f2092012-12-06 17:41:04 -0500922 def test_nameconstant(self):
923 self.expr(ast.NameConstant(4), "singleton must be True, False, or None")
924
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500925 def test_stdlib_validates(self):
926 stdlib = os.path.dirname(ast.__file__)
927 tests = [fn for fn in os.listdir(stdlib) if fn.endswith(".py")]
928 tests.extend(["test/test_grammar.py", "test/test_unpack_ex.py"])
929 for module in tests:
930 fn = os.path.join(stdlib, module)
931 with open(fn, "r", encoding="utf-8") as fp:
932 source = fp.read()
Victor Stinnerd502a072013-03-22 00:06:20 +0100933 mod = ast.parse(source, fn)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500934 compile(mod, fn, "exec")
935
936
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000937def main():
938 if __name__ != '__main__':
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000939 return
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000940 if sys.argv[1:] == ['-g']:
941 for statements, kind in ((exec_tests, "exec"), (single_tests, "single"),
942 (eval_tests, "eval")):
943 print(kind+"_results = [")
944 for s in statements:
945 print(repr(to_tuple(compile(s, "?", kind, 0x400)))+",")
946 print("]")
947 print("main()")
948 raise SystemExit
Brett Cannon3e9a9ae2013-06-12 21:25:59 -0400949 unittest.main()
Tim Peters400cbc32006-02-28 18:44:41 +0000950
951#### EVERYTHING BELOW IS GENERATED #####
952exec_results = [
Benjamin Peterson442f2092012-12-06 17:41:04 -0500953('Module', [('Expr', (1, 0), ('NameConstant', (1, 0), None))]),
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700954('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [('Pass', (1, 9))], [], None)]),
955('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None)], None, [], [], None, []), [('Pass', (1, 10))], [], None)]),
956('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None)], None, [], [], None, [('Num', (1, 8), 0)]), [('Pass', (1, 12))], [], None)]),
957('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], ('arg', (1, 7), 'args', None), [], [], None, []), [('Pass', (1, 14))], [], None)]),
958('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], ('arg', (1, 8), 'kwargs', None), []), [('Pass', (1, 17))], [], None)]),
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500959('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)], [('Num', (1, 43), 42)], ('arg', (1, 49), 'kwargs', None), [('Num', (1, 11), 1), ('NameConstant', (1, 16), None), ('List', (1, 24), [], ('Load',)), ('Dict', (1, 30), [], [])]), [('Pass', (1, 58))], [], None)]),
Neal Norwitzad74aa82008-03-31 05:14:30 +0000960('Module', [('ClassDef', (1, 0), 'C', [], [], None, None, [('Pass', (1, 8))], [])]),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500961('Module', [('ClassDef', (1, 0), 'C', [('Name', (1, 8), 'object', ('Load',))], [], None, None, [('Pass', (1, 17))], [])]),
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700962('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 +0000963('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]),
964('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Num', (1, 4), 1))]),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000965('Module', [('AugAssign', (1, 0), ('Name', (1, 0), 'v', ('Store',)), ('Add',), ('Num', (1, 5), 1))]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000966('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Pass', (1, 11))], [])]),
967('Module', [('While', (1, 0), ('Name', (1, 6), 'v', ('Load',)), [('Pass', (1, 8))], [])]),
968('Module', [('If', (1, 0), ('Name', (1, 3), 'v', ('Load',)), [('Pass', (1, 5))], [])]),
Benjamin Petersonaeabd5f2011-05-27 15:02:03 -0500969('Module', [('With', (1, 0), [('withitem', ('Name', (1, 5), 'x', ('Load',)), ('Name', (1, 10), 'y', ('Store',)))], [('Pass', (1, 13))])]),
970('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 Peterson7a66fc22015-02-02 10:51:20 -0500971('Module', [('Raise', (1, 0), ('Call', (1, 6), ('Name', (1, 6), 'Exception', ('Load',)), [('Str', (1, 16), 'string')], [], None, None), None)]),
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500972('Module', [('Try', (1, 0), [('Pass', (2, 2))], [('ExceptHandler', (3, 0), ('Name', (3, 7), 'Exception', ('Load',)), None, [('Pass', (4, 2))])], [], [])]),
973('Module', [('Try', (1, 0), [('Pass', (2, 2))], [], [], [('Pass', (4, 2))])]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000974('Module', [('Assert', (1, 0), ('Name', (1, 7), 'v', ('Load',)), None)]),
975('Module', [('Import', (1, 0), [('alias', 'sys', None)])]),
976('Module', [('ImportFrom', (1, 0), 'sys', [('alias', 'v', None)], 0)]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000977('Module', [('Global', (1, 0), ['v'])]),
978('Module', [('Expr', (1, 0), ('Num', (1, 0), 1))]),
979('Module', [('Pass', (1, 0))]),
980('Module', [('Break', (1, 0))]),
981('Module', [('Continue', (1, 0))]),
Benjamin Peterson2e4b0e12009-09-11 22:36:20 +0000982('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))], [])]),
983('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',)), [])]))]),
984('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 -0500985('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',)), [])]))]),
986('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',)), [])]))]),
987('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',))])]))]),
988('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',)), [])]))]),
989('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',))])]))]),
990('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 +0000991]
992single_results = [
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000993('Interactive', [('Expr', (1, 0), ('BinOp', (1, 0), ('Num', (1, 0), 1), ('Add',), ('Num', (1, 2), 2)))]),
Tim Peters400cbc32006-02-28 18:44:41 +0000994]
995eval_results = [
Benjamin Peterson442f2092012-12-06 17:41:04 -0500996('Expression', ('NameConstant', (1, 0), None)),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000997('Expression', ('BoolOp', (1, 0), ('And',), [('Name', (1, 0), 'a', ('Load',)), ('Name', (1, 6), 'b', ('Load',))])),
998('Expression', ('BinOp', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Add',), ('Name', (1, 4), 'b', ('Load',)))),
999('Expression', ('UnaryOp', (1, 0), ('Not',), ('Name', (1, 4), 'v', ('Load',)))),
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001000('Expression', ('Lambda', (1, 0), ('arguments', [], None, [], [], None, []), ('NameConstant', (1, 7), None))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001001('Expression', ('Dict', (1, 0), [('Num', (1, 2), 1)], [('Num', (1, 4), 2)])),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001002('Expression', ('Dict', (1, 0), [], [])),
Benjamin Peterson442f2092012-12-06 17:41:04 -05001003('Expression', ('Set', (1, 0), [('NameConstant', (1, 1), None)])),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001004('Expression', ('Dict', (1, 0), [('Num', (2, 6), 1)], [('Num', (4, 10), 2)])),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001005('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',))])])),
1006('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',))])])),
1007('Expression', ('Compare', (1, 0), ('Num', (1, 0), 1), [('Lt',), ('Lt',)], [('Num', (1, 4), 2), ('Num', (1, 8), 3)])),
Benjamin Peterson7a66fc22015-02-02 10:51:20 -05001008('Expression', ('Call', (1, 0), ('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 +00001009('Expression', ('Num', (1, 0), 10)),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001010('Expression', ('Str', (1, 0), 'string')),
Benjamin Peterson7a66fc22015-02-02 10:51:20 -05001011('Expression', ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',))),
1012('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 +00001013('Expression', ('Name', (1, 0), 'v', ('Load',))),
1014('Expression', ('List', (1, 0), [('Num', (1, 1), 1), ('Num', (1, 3), 2), ('Num', (1, 5), 3)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001015('Expression', ('List', (1, 0), [], ('Load',))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001016('Expression', ('Tuple', (1, 0), [('Num', (1, 0), 1), ('Num', (1, 2), 2), ('Num', (1, 4), 3)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001017('Expression', ('Tuple', (1, 1), [('Num', (1, 1), 1), ('Num', (1, 3), 2), ('Num', (1, 5), 3)], ('Load',))),
1018('Expression', ('Tuple', (1, 0), [], ('Load',))),
Benjamin Peterson7a66fc22015-02-02 10:51:20 -05001019('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', ('Num', (1, 12), 1), ('Num', (1, 14), 2), None), ('Load',))], [], None, None)),
Tim Peters400cbc32006-02-28 18:44:41 +00001020]
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001021main()