Debian Codegraph @

pypy/interpreter/astcompiler/tools/asdl.py

raw symbols SCIP
1 #-------------------------------------------------------------------------------
2 # Parser for ASDL [1] definition files. Reads in an ASDL description and parses
3 # it into an AST that describes it.
4 #
5 # The EBNF we're parsing here: Figure 1 of the paper [1]. Extended to support
6 # modules and attributes after a product. Words starting with Capital letters
7 # are terminals. Literal tokens are in "double quotes". Others are
8 # non-terminals. Id is either TokenId or ConstructorId.
9 #
10 # module ::= "module" Id "{" [definitions] "}"
11 # definitions ::= { TypeId "=" type }
12 # type ::= product | sum
13 # product ::= fields ["attributes" fields]
14 # fields ::= "(" { field, "," } field ")"
15 # field ::= TypeId ["?" | "*"] [Id]
16 # sum ::= constructor { "|" constructor } ["attributes" fields]
17 # constructor ::= ConstructorId [fields]
18 #
19 # [1] "The Zephyr Abstract Syntax Description Language" by Wang, et. al. See
20 # http://asdl.sourceforge.net/
21 #-------------------------------------------------------------------------------
22 from collections import namedtuple
23 import re
24
25 __all__ = [
26 'builtin_types', 'parse', 'AST', 'Module', 'Type', 'Constructor',
27 'Field', 'Sum', 'Product', 'VisitorBase', 'Check', 'check']
28
29 # The following classes define nodes into which the ASDL description is parsed.
30 # Note: this is a "meta-AST". ASDL files (such as Python.asdl) describe the AST
31 # structure used by a programming language. But ASDL files themselves need to be
32 # parsed. This module parses ASDL files and uses a simple AST to represent them.
33 # See the EBNF at the top of the file to understand the logical connection
34 # between the various node types.
35
36 builtin_types = {'identifier', 'string', 'bytes', 'int', 'bool', 'object',
37 'singleton', 'constant'}
38
39 class AST:
40 def __repr__(self):
41 raise NotImplementedError
42
43 class Module(AST):
44 def __init__(self, name, dfns):
45 self.name = name
46 self.dfns = dfns
47 self.types = {type.name: type.value for type in dfns}
48
49 def __repr__(self):
50 return 'Module({0.name}, {0.dfns})'.format(self)
51
52 class Type(AST):
53 def __init__(self, name, value):
54 self.name = name
55 self.value = value
56
57 def __repr__(self):
58 return 'Type({0.name}, {0.value})'.format(self)
59
60 class Constructor(AST):
61 def __init__(self, name, fields=None):
62 self.name = name
63 self.fields = fields or []
64
65 def __repr__(self):
66 return 'Constructor({0.name}, {0.fields})'.format(self)
67
68 class Field(AST):
69 def __init__(self, type, name=None, seq=False, opt=False):
70 self.type = type
71 self.name = name
72 self.seq = seq
73 self.opt = opt
74
75 def __repr__(self):
76 if self.seq:
77 extra = ", seq=True"
78 elif self.opt:
79 extra = ", opt=True"
80 else:
81 extra = ""
82 if self.name is None:
83 return 'Field({0.type}{1})'.format(self, extra)
84 else:
85 return 'Field({0.type}, {0.name}{1})'.format(self, extra)
86
87 def __str__(self):
88 if self.seq:
89 extra = "*"
90 elif self.opt:
91 extra = "?"
92 else:
93 extra = ""
94
95 return "{}{} {}".format(self.type, extra, self.name)
96
97
98 class Sum(AST):
99 def __init__(self, types, attributes=None):
100 self.types = types
101 self.attributes = attributes or []
102
103 def __repr__(self):
104 if self.attributes:
105 return 'Sum({0.types}, {0.attributes})'.format(self)
106 else:
107 return 'Sum({0.types})'.format(self)
108
109 class Product(AST):
110 def __init__(self, fields, attributes=None):
111 self.fields = fields
112 self.attributes = attributes or []
113
114 def __repr__(self):
115 if self.attributes:
116 return 'Product({0.fields}, {0.attributes})'.format(self)
117 else:
118 return 'Product({0.fields})'.format(self)
119
120 # A generic visitor for the meta-AST that describes ASDL. This can be used by
121 # emitters. Note that this visitor does not provide a generic visit method, so a
122 # subclass needs to define visit methods from visitModule to as deep as the
123 # interesting node.
124 # We also define a Check visitor that makes sure the parsed ASDL is well-formed.
125
126 class VisitorBase(object):
127 """Generic tree visitor for ASTs."""
128 def __init__(self):
129 self.cache = {}
130
131 def visit(self, obj, *args):
132 klass = obj.__class__
133 meth = self.cache.get(klass)
134 if meth is None:
135 methname = "visit" + klass.__name__
136 meth = getattr(self, methname, None)
137 self.cache[klass] = meth
138 if meth:
139 try:
140 meth(obj, *args)
141 except Exception as e:
142 print("Error visiting %r: %s" % (obj, e))
143 raise
144
145 class Check(VisitorBase):
146 """A visitor that checks a parsed ASDL tree for correctness.
147
148 Errors are printed and accumulated.
149 """
150 def __init__(self):
151 super(Check, self).__init__()
152 self.cons = {}
153 self.errors = 0
154 self.types = {}
155
156 def visitModule(self, mod):
157 for dfn in mod.dfns:
158 self.visit(dfn)
159
160 def visitType(self, type):
161 self.visit(type.value, str(type.name))
162
163 def visitSum(self, sum, name):
164 for t in sum.types:
165 self.visit(t, name)
166
167 def visitConstructor(self, cons, name):
168 key = str(cons.name)
169 conflict = self.cons.get(key)
170 if conflict is None:
171 self.cons[key] = name
172 else:
173 print('Redefinition of constructor {}'.format(key))
174 print('Defined in {} and {}'.format(conflict, name))
175 self.errors += 1
176 for f in cons.fields:
177 self.visit(f, key)
178
179 def visitField(self, field, name):
180 key = str(field.type)
181 l = self.types.setdefault(key, [])
182 l.append(name)
183
184 def visitProduct(self, prod, name):
185 for f in prod.fields:
186 self.visit(f, name)
187
188 def check(mod):
189 """Check the parsed ASDL tree for correctness.
190
191 Return True if success. For failure, the errors are printed out and False
192 is returned.
193 """
194 v = Check()
195 v.visit(mod)
196
197 for t in v.types:
198 if t not in mod.types and not t in builtin_types:
199 v.errors += 1
200 uses = ", ".join(v.types[t])
201 print('Undefined type {}, used in {}'.format(t, uses))
202 return not v.errors
203
204 # The ASDL parser itself comes next. The only interesting external interface
205 # here is the top-level parse function.
206
207 def parse(filename):
208 """Parse ASDL from the given file and return a Module node describing it."""
209 with open(filename) as f:
210 parser = ASDLParser()
211 return parser.parse(f.read())
212
213 # Types for describing tokens in an ASDL specification.
214 class TokenKind:
215 """TokenKind is provides a scope for enumerated token kinds."""
216 (ConstructorId, TypeId, Equals, Comma, Question, Pipe, Asterisk,
217 LParen, RParen, LBrace, RBrace) = range(11)
218
219 operator_table = {
220 '=': Equals, ',': Comma, '?': Question, '|': Pipe, '(': LParen,
221 ')': RParen, '*': Asterisk, '{': LBrace, '}': RBrace}
222
223 Token = namedtuple('Token', 'kind value lineno')
224
225 class ASDLSyntaxError(Exception):
226 def __init__(self, msg, lineno=None):
227 self.msg = msg
228 self.lineno = lineno or '<unknown>'
229
230 def __str__(self):
231 return 'Syntax error on line {0.lineno}: {0.msg}'.format(self)
232
233 def tokenize_asdl(buf):
234 """Tokenize the given buffer. Yield Token objects."""
235 for lineno, line in enumerate(buf.splitlines(), 1):
236 for m in re.finditer(r'\s*(\w+|--.*|.)', line.strip()):
237 c = m.group(1)
238 if c[0].isalpha():
239 # Some kind of identifier
240 if c[0].isupper():
241 yield Token(TokenKind.ConstructorId, c, lineno)
242 else:
243 yield Token(TokenKind.TypeId, c, lineno)
244 elif c[:2] == '--':
245 # Comment
246 break
247 else:
248 # Operators
249 try:
250 op_kind = TokenKind.operator_table[c]
251 except KeyError:
252 raise ASDLSyntaxError('Invalid operator %s' % c, lineno)
253 yield Token(op_kind, c, lineno)
254
255 class ASDLParser:
256 """Parser for ASDL files.
257
258 Create, then call the parse method on a buffer containing ASDL.
259 This is a simple recursive descent parser that uses tokenize_asdl for the
260 lexing.
261 """
262 def __init__(self):
263 self._tokenizer = None
264 self.cur_token = None
265
266 def parse(self, buf):
267 """Parse the ASDL in the buffer and return an AST with a Module root.
268 """
269 self._tokenizer = tokenize_asdl(buf)
270 self._advance()
271 return self._parse_module()
272
273 def _parse_module(self):
274 if self._at_keyword('module'):
275 self._advance()
276 else:
277 raise ASDLSyntaxError(
278 'Expected "module" (found {})'.format(self.cur_token.value),
279 self.cur_token.lineno)
280 name = self._match(self._id_kinds)
281 self._match(TokenKind.LBrace)
282 defs = self._parse_definitions()
283 self._match(TokenKind.RBrace)
284 return Module(name, defs)
285
286 def _parse_definitions(self):
287 defs = []
288 while self.cur_token.kind == TokenKind.TypeId:
289 typename = self._advance()
290 self._match(TokenKind.Equals)
291 type = self._parse_type()
292 defs.append(Type(typename, type))
293 return defs
294
295 def _parse_type(self):
296 if self.cur_token.kind == TokenKind.LParen:
297 # If we see a (, it's a product
298 return self._parse_product()
299 else:
300 # Otherwise it's a sum. Look for ConstructorId
301 sumlist = [Constructor(self._match(TokenKind.ConstructorId),
302 self._parse_optional_fields())]
303 while self.cur_token.kind == TokenKind.Pipe:
304 # More constructors
305 self._advance()
306 sumlist.append(Constructor(
307 self._match(TokenKind.ConstructorId),
308 self._parse_optional_fields()))
309 return Sum(sumlist, self._parse_optional_attributes())
310
311 def _parse_product(self):
312 return Product(self._parse_fields(), self._parse_optional_attributes())
313
314 def _parse_fields(self):
315 fields = []
316 self._match(TokenKind.LParen)
317 while self.cur_token.kind == TokenKind.TypeId:
318 typename = self._advance()
319 is_seq, is_opt = self._parse_optional_field_quantifier()
320 id = (self._advance() if self.cur_token.kind in self._id_kinds
321 else None)
322 fields.append(Field(typename, id, seq=is_seq, opt=is_opt))
323 if self.cur_token.kind == TokenKind.RParen:
324 break
325 elif self.cur_token.kind == TokenKind.Comma:
326 self._advance()
327 self._match(TokenKind.RParen)
328 return fields
329
330 def _parse_optional_fields(self):
331 if self.cur_token.kind == TokenKind.LParen:
332 return self._parse_fields()
333 else:
334 return None
335
336 def _parse_optional_attributes(self):
337 if self._at_keyword('attributes'):
338 self._advance()
339 return self._parse_fields()
340 else:
341 return None
342
343 def _parse_optional_field_quantifier(self):
344 is_seq, is_opt = False, False
345 if self.cur_token.kind == TokenKind.Asterisk:
346 is_seq = True
347 self._advance()
348 elif self.cur_token.kind == TokenKind.Question:
349 is_opt = True
350 self._advance()
351 return is_seq, is_opt
352
353 def _advance(self):
354 """ Return the value of the current token and read the next one into
355 self.cur_token.
356 """
357 cur_val = None if self.cur_token is None else self.cur_token.value
358 try:
359 self.cur_token = next(self._tokenizer)
360 except StopIteration:
361 self.cur_token = None
362 return cur_val
363
364 _id_kinds = (TokenKind.ConstructorId, TokenKind.TypeId)
365
366 def _match(self, kind):
367 """The 'match' primitive of RD parsers.
368
369 * Verifies that the current token is of the given kind (kind can
370 be a tuple, in which the kind must match one of its members).
371 * Returns the value of the current token
372 * Reads in the next token
373 """
374 if (isinstance(kind, tuple) and self.cur_token.kind in kind or
375 self.cur_token.kind == kind
376 ):
377 value = self.cur_token.value
378 self._advance()
379 return value
380 else:
381 raise ASDLSyntaxError(
382 'Unmatched {} (found {})'.format(kind, self.cur_token.kind),
383 self.cur_token.lineno)
384
385 def _at_keyword(self, keyword):
386 return (self.cur_token.kind == TokenKind.TypeId and
387 self.cur_token.value == keyword)