Debian Codegraph @

rpython/rlib/parsing/test/test_pythonparse.py

raw symbols SCIP
1 """ test file to experiment with a an adapted CPython grammar """
2
3 import py
4 from rpython.rlib.parsing.lexer import Lexer, SourcePos, Token
5 from rpython.rlib.parsing.deterministic import LexerError
6 from rpython.rlib.parsing.tree import Nonterminal, Symbol, RPythonVisitor
7 from rpython.rlib.parsing.parsing import PackratParser, Symbol, ParseError, Rule
8 from rpython.rlib.parsing.ebnfparse import parse_ebnf, make_parse_function
9
10 grammar = py.path.local(__file__).dirpath().join("pygrammar.txt").read(mode='rt')
11
12
13 def test_parse_grammar():
14 _, rules, ToAST = parse_ebnf(grammar)
15
16 def test_parse_python_args():
17 regexs, rules, ToAST = parse_ebnf("""
18 IGNORE: " ";
19 NAME: "[a-zA-Z_]*";
20 NUMBER: "0|[1-9][0-9]*";
21 parameters: ["("] >varargslist<? [")"];
22 varargslist: (fpdef ("=" test)? [","])* star_or_starstarargs |
23 fpdef ("=" test)? ([","] fpdef ("=" test)?)* [","]?;
24 star_or_starstarargs: "*" NAME [","] "**" NAME | "*" NAME | "**" NAME;
25 fpdef: <NAME> | "(" <fplist> ")";
26 fplist: fpdef ([","] fpdef)* [","]?;
27 test: NUMBER;
28 """)
29 parse = make_parse_function(regexs, rules)
30 t = parse("(a)").visit(ToAST())[0]
31 t = parse("(a,)").visit(ToAST())[0]
32 t = parse("(a,b,c,d)").visit(ToAST())[0]
33 t = parse("(a,b,c,d,)").visit(ToAST())[0]
34 t = parse("((a, b, c),b,c,d,)").visit(ToAST())[0]
35 t = parse("((a, b, (d, e, (f, g))), b, *args, **kwargs)").visit(ToAST())[0]
36 t = parse("((a, b, c),b,c,d,*args)").visit(ToAST())[0]
37 t = parse("((a, b, c),b,c,d,**kwargs)").visit(ToAST())[0]
38 t = parse("((a, b, c),b,c,d,*args, **args)").visit(ToAST())[0]
39 t = parse("()").visit(ToAST())[0]
40 t = parse("(*args, **args)").visit(ToAST())[0]
41 t = parse("(a=1)").visit(ToAST())[0]
42 t = parse("(a=2,)").visit(ToAST())[0]
43 t = parse("(a,b,c,d=3)").visit(ToAST())[0]
44 t = parse("(a,b,c,d=4,)").visit(ToAST())[0]
45 t = parse("((a, b, c),b,c,(c, d)=1,)").visit(ToAST())[0]
46 t = parse("((a, b, c),b,c,d=1,*args)").visit(ToAST())[0]
47 t = parse("((a, b, c),b,c,d=2,**kwargs)").visit(ToAST())[0]
48 t = parse("((a, b, c),b,c,(c, d)=4,*args, **args)").visit(ToAST())[0]
49 t = parse("(self, a, b, args)").visit(ToAST())[0]
50
51 def test_parse_funcdef():
52 regexs, rules, ToAST = parse_ebnf("""
53 IGNORE: " ";
54 NAME: "[a-zA-Z_]*";
55 NUMBER: "0|[1-9][0-9]*";
56 funcdef: "def" NAME parameters ":" suite;
57 parameters: ["("] >varargslist< [")"] | ["("] [")"];
58 varargslist: (fpdef ("=" test)? ",")* star_or_starstarargs |
59 fpdef ("=" test)? ("," fpdef ("=" test)?)* ","?;
60 star_or_starstarargs: "*" NAME "," "**" NAME | "*" NAME | "**" NAME;
61 fpdef: NAME | "(" fplist ")";
62 fplist: fpdef ("," fpdef)* ","?;
63 test: NUMBER;
64 suite: simple_stmt | ["NEWLINE"] ["INDENT"] stmt+ ["DEDENT"];
65 simple_stmt: stmt;
66 stmt: "pass";
67 """)
68 parse = make_parse_function(regexs, rules)
69 t = parse("def f(a): NEWLINE INDENT pass DEDENT").visit(ToAST())[0]
70
71
72 class TestParser(object):
73 def setup_class(cls):
74 from rpython.rlib.parsing.parsing import PackratParser
75 regexs, rules, ToAST = parse_ebnf(grammar)
76 cls.ToAST = ToAST()
77 cls.parser = PackratParser(rules, rules[0].nonterminal)
78 cls.regexs = regexs
79 names, regexs = zip(*regexs)
80 cls.lexer = Lexer(list(regexs), list(names))
81
82 def parse(self, source):
83 tokens = list(self.tokenize(source))
84 s = self.parser.parse(tokens)
85 return s
86
87 def tokenize(self, source):
88 # use tokenize module but rewrite tokens slightly
89 import tokenize, cStringIO
90 pos = 0
91 readline = cStringIO.StringIO(source).readline
92 for token in tokenize.generate_tokens(readline):
93 typ, s, (row, col), _, line = token
94 row -= 1
95 pos += len(s)
96 typ = tokenize.tok_name[typ]
97 if typ == "ENDMARKER":
98 typ = s = "EOF"
99 elif typ == "NL":
100 continue
101 elif typ == "COMMENT":
102 continue
103 try:
104 tokens = self.lexer.tokenize(s, eof=False)
105 if len(tokens) == 1:
106 yield tokens[0]
107 continue
108 except LexerError:
109 pass
110 yield Token(typ, s, SourcePos(pos, row, col))
111
112
113 def test_simple(self):
114 t = self.parse("""
115 def f(x, null=0):
116 if x >= null:
117 return null + x
118 else:
119 pass
120 return null - x
121 """)
122 t = self.ToAST.transform(t)
123
124 def test_class(self):
125 t = self.parse("""
126 class A(object):
127 def __init__(self, a, b, *args):
128 self.a = a
129 self.b = b
130 if args:
131 self.len = len(args)
132 self.args = [a, b] + list(args)
133
134 def diagonal(self):
135 return (self.a ** 2 + self.b ** 2) ** 0.5
136 """)
137 t = self.ToAST.transform(t)
138
139 def test_while(self):
140 t = self.parse("""
141 def f(x, null=0):
142 i = null
143 result = 0
144 while i < x:
145 result += i
146 i += 1
147 if result % 625 == 13:
148 break
149 else:
150 return result - 15
151 return result
152 """)
153 t = self.ToAST.transform(t)
154
155 def test_comment(self):
156 t = self.parse("""
157 def f(x):
158 # this does some fancy stuff
159 return x
160 """)
161 t = self.ToAST.transform(t)
162
163 def test_parse_print(self):
164 t = self.parse("""
165 print >> f, a, b, c,
166 print >> f, a, b
167 print >> f
168 print
169 print 1
170 print 1, 2
171 print 1, 2,
172 """)
173 t = self.ToAST.transform(t)
174
175 def test_assignment(self):
176 t = self.parse("""
177 a = 1
178 a = b = c
179 (a, b) = c
180 a += 1
181 b //= 3
182 """)
183 t = self.ToAST.transform(t)
184
185 def test_lists(self):
186 t = self.parse("""
187 l0 = [1, 2, [3, 4, [5, []]]]
188 l1 = [i for i in range(10)]
189 l1 = [i for i in range(10) if i ** 2 % 3 == 0]
190 l2 = [ ]
191 l3 = [ ]
192 l4 = []
193 """)
194 t = self.ToAST.transform(t)
195
196 def test_dicts(self):
197 t = self.parse("""
198 {1: 2, 2: {1: 3},}
199 {}
200 """)
201 t = self.ToAST.transform(t)
202
203 def test_calls(self):
204 #XXX horrible trees
205 t = self.parse("""
206 f(a)(b)(c)
207 f() ** 2
208 f(x) * 2
209 f(x, y, z, *args) + 2
210 f(x, y, abc=34, *arg, **kwargs)
211 """)
212 t = self.ToAST.transform(t)
213
214 def test_trailers(self):
215 py.test.skip("in progress")
216 t = self.parse("""
217 (a + b).foo[1 + i - j:](32, *args)
218 """)
219 t = self.ToAST.transform(t)
220
221 def test_errors(self):
222 source = """
223 def f(x):
224 if a:
225 pass
226 else:
227 pass
228 else:
229 pass
230 """
231 excinfo = py.test.raises(ParseError, self.parse, source)
232 error = excinfo.value.errorinformation
233 msg = excinfo.value.nice_error_message("<stdin>", source)
234
235 def test_precedence(self):
236 source = """
237 a = 1 - 2 - 3
238 """
239 t = self.parse(source)
240 t = self.ToAST.transform(t)
241
242 def test_parse_this(self):
243 filename = __file__
244 if filename.lower().endswith('.pyc'):
245 filename = filename[:-1]
246 s = py.path.local(filename).read()
247 t = self.parse(s)
248 t = self.ToAST.transform(t)
249
250 def test_parsing(self):
251 s = py.path.local(__file__).dirpath().dirpath().join("parsing.py").read()
252 t = self.parse(s)
253 t = self.ToAST.transform(t)
254