Debian Codegraph @

pypy/interpreter/astcompiler/test/test_unparse.py

raw symbols SCIP
1 import pytest
2 from pypy.interpreter.pyparser import pyparse
3 from pypy.interpreter.pyparser.error import SyntaxError
4 from pypy.interpreter.astcompiler import ast, consts
5 from pypy.interpreter.astcompiler.unparse import unparse, unparse_annotations
6
7
8 class TestAstUnparser:
9 def setup_class(cls):
10 cls.parser = pyparse.PegParser(cls.space)
11
12 def get_ast(self, source, p_mode="exec", flags=None):
13 if flags is None:
14 flags = consts.CO_FUTURE_WITH_STATEMENT
15 ec = self.space.getexecutioncontext()
16 ast_node = ec.compiler.compile_to_ast(source, "?", p_mode, flags)
17 return ast_node
18
19 def get_first_expr(self, source, p_mode="exec", flags=None):
20 mod = self.get_ast(source, p_mode, flags)
21 assert len(mod.body) == 1
22 expr = mod.body[0]
23 assert isinstance(expr, ast.Expr)
24 return expr.value
25
26 def check(self, expr, unparsed=None):
27 if unparsed is None:
28 unparsed = expr
29 ast = self.get_first_expr(expr)
30 assert unparse(self.space, ast) == unparsed
31 # should be stable
32 if expr != unparsed:
33 ast = self.get_first_expr(unparsed)
34 assert unparse(self.space, ast) == unparsed
35
36 def test_constant(self):
37 w_one = self.space.newint(1)
38 node = ast.Constant(w_one, self.space.w_None, 0, 0, 0, 0)
39 assert unparse(self.space, node) == "1"
40
41 def test_num(self):
42 self.check("1")
43 self.check("1.64")
44 import sys
45 infstr = "1e" + str(sys.float_info.max_10_exp + 1)
46 self.check("1e1000", infstr)
47 self.check("1e1000j", infstr + "j")
48
49 def test_str(self):
50 self.check("u'a'")
51
52 def test_bytes(self):
53 self.check("b'a'")
54
55 def test_name(self):
56 self.check('a')
57
58 def test_name_constant(self):
59 self.check('True')
60 self.check('False')
61 self.check('None')
62
63 def test_unaryop(self):
64 self.check('+a')
65 self.check('-a')
66 self.check('~a')
67 self.check('not a')
68
69 def test_binaryop(self):
70 self.check('b+a', "b + a")
71 self.check('c*(b+a)', "c * (b + a)")
72 self.check('c**(b+a)', "c ** (b + a)")
73 self.check('2**2**3', "2 ** 2 ** 3")
74 self.check('(2**2)**3', "(2 ** 2) ** 3")
75
76 self.check('2 << 2 << 3')
77 self.check('2<<(2<<3)', "2 << (2 << 3)")
78
79 def test_compare(self):
80 self.check('b == 5 == c == d')
81
82 def test_boolop(self):
83 self.check('b and a and c or d')
84
85 def test_if(self):
86 self.check('a if b else c')
87 self.check('0 if not x else 1 if x > 0 else -1')
88
89 def test_list(self):
90 self.check('[]')
91 self.check('[1, 2, 3, 4]')
92
93 def test_tuple(self):
94 self.check('()')
95 self.check('(a,)')
96 self.check('([1, 2], a + 6, 3, 4)')
97
98 def test_sets(self):
99 self.check('{1}')
100 self.check('{(1, 2), a + 6, 3, 4}')
101
102 def test_dict(self):
103 self.check('{}')
104 self.check('{a: b, c: d}')
105 self.check('{1: 2, **x}')
106
107 def test_list_comprehension(self):
108 self.check('[a for x in y if b if c]')
109
110 def test_genexp(self):
111 self.check('(a for x in y for z in b)')
112
113 def test_set_comprehension(self):
114 self.check('{a for x, in y for z in b}')
115
116 def test_dict_comprehension(self):
117 self.check('{a: b for x in y}')
118
119 def test_ellipsis(self):
120 self.check('...')
121
122 def test_index(self):
123 self.check('a[1]')
124 self.check('a[1:5]')
125 self.check('a[1:5, 7:12, :, 5]')
126 self.check('a[::1]')
127 self.check('dict[(str, int)]', 'dict[str, int]')
128
129 def test_attribute(self):
130 self.check('a.b.c')
131 self.check('1 .b')
132 self.check('1.5.b')
133
134 def test_call(self):
135 self.check('f()')
136 self.check('f(a)')
137 self.check('f(a, b, 1)')
138 self.check('f(a, b, 1, a=4, b=78)')
139 self.check('f(a, x=y, **b, **c)')
140 self.check('f(*a)')
141 self.check('f(x for y in z)')
142
143 def test_lambda(self):
144 self.check('lambda: 1')
145 self.check('lambda a: 1')
146 self.check('lambda a=1: 1')
147 self.check('lambda b, c: 1')
148 self.check('lambda *l: 1')
149 self.check('lambda *, m, l=5: 1')
150 self.check('lambda **foo: 1')
151 self.check('lambda a, **b: 45')
152 # positional-only parameters
153 self.check('lambda a, /: 1')
154 self.check('lambda a, /, b: 1')
155 self.check('lambda a=1, /: 1')
156 self.check('lambda a, /, b=2: 1')
157 self.check("lambda a, /, b, c=True, *vararg, d, e='str', **kwargs: a + b")
158
159 def test_fstrings(self):
160 self.check('f"abc"', "'abc'")
161 self.check("f'{{{a}'", "f'{{{a}'")
162 self.check("f'{{{a}'", "f'{{{a}'")
163 self.check("f'{x+1!a}'", "f'{x + 1!a}'")
164 self.check("f'{x+1:x}'", "f'{x + 1:x}'")
165 self.check("f'some f-string with {a} {few():.2f} {formatted.values!r}'")
166 self.check('''f"{f'{nested} inner'} outer"''')
167 self.check("f'space between opening braces: { {a for a in (1, 2, 3)}}'")
168 self.check("f'{(lambda x: x)}'")
169 self.check("f'{(None if a else lambda x: x)}'")
170
171 class TestAstUnparseAnnotations(object):
172 def setup_class(cls):
173 cls.parser = pyparse.PegParser(cls.space)
174
175 def get_ast(self, source, p_mode="exec", flags=None):
176 if flags is None:
177 flags = consts.CO_FUTURE_WITH_STATEMENT
178 ec = self.space.getexecutioncontext()
179 ast_node = ec.compiler.compile_to_ast(source, "?", p_mode, flags)
180 return ast_node
181
182 def test_function(self):
183 ast = self.get_ast("""def f(a: b) -> 1 + 2: return a + 12""")
184 func = ast.body[0]
185 res = unparse_annotations(self.space, func)
186 assert self.space.text_w(res.args.args[0].annotation.value) == "b"
187 assert self.space.text_w(res.returns.value) == "1 + 2"
188
189 def test_global(self):
190 ast = self.get_ast("""a: list[int]""")
191 res = unparse_annotations(self.space, ast)
192 assert self.space.text_w(res.body[0].annotation.value) == 'list[int]'
193
194 def test_await_not_allowed(self):
195 ast = self.get_ast("""def f() -> await x: pass""")
196 func = ast.body[0]
197 with pytest.raises(SyntaxError):
198 unparse_annotations(self.space, func)
199
200 def test_yield_not_allowed(self):
201 ast = self.get_ast("""def f():\n a: (yield)""")
202 func = ast.body[0]
203 with pytest.raises(SyntaxError):
204 unparse_annotations(self.space, func)
205
206 def test_yield_from_not_allowed(self):
207 ast = self.get_ast("""def f():\n a: (yield from x)""")
208 func = ast.body[0]
209 with pytest.raises(SyntaxError):
210 unparse_annotations(self.space, func)
211
212 def test_namedexpr_not_allowed(self):
213 ast = self.get_ast("""async def f() -> something((a := b)): pass""")
214 func = ast.body[0]
215 with pytest.raises(SyntaxError):
216 unparse_annotations(self.space, func)
217
218 def test_fstring_no_formatted_values_preserves_f_prefix(self):
219 ast = self.get_ast("""def f(x: f'just a string') -> None: pass""")
220 func = ast.body[0]
221 res = unparse_annotations(self.space, func)
222 annotation = res.args.args[0].annotation.value
223 assert self.space.text_w(annotation) == "f'just a string'"
224