blob: d6555d6d7252bd40c9bdba410d93c29a10c71c76 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001#! /usr/bin/env python
2"""Generate C code from an ASDL description."""
3
4# TO DO
5# handle fields that have a type but no name
6
Christian Heimes05e8be12008-02-23 18:30:17 +00007import os, sys
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00008
9import asdl
10
11TABSIZE = 8
12MAX_COL = 80
13
14def get_c_type(name):
15 """Return a string for the C name of the type.
16
17 This function special cases the default types provided by asdl:
Neal Norwitz3591bbe2007-02-26 19:04:49 +000018 identifier, string, int.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000019 """
20 # XXX ack! need to figure out where Id is useful and where string
21 if isinstance(name, asdl.Id):
22 name = name.value
23 if name in asdl.builtin_types:
24 return name
25 else:
26 return "%s_ty" % name
27
28def reflow_lines(s, depth):
29 """Reflow the line s indented depth tabs.
30
31 Return a sequence of lines where no line extends beyond MAX_COL
32 when properly indented. The first line is properly indented based
33 exclusively on depth * TABSIZE. All following lines -- these are
34 the reflowed lines generated by this function -- start at the same
35 column as the first character beyond the opening { in the first
36 line.
37 """
38 size = MAX_COL - depth * TABSIZE
39 if len(s) < size:
40 return [s]
41
42 lines = []
43 cur = s
44 padding = ""
45 while len(cur) > size:
46 i = cur.rfind(' ', 0, size)
47 # XXX this should be fixed for real
48 if i == -1 and 'GeneratorExp' in cur:
49 i = size + 3
Brett Cannonf0365512006-08-25 04:06:31 +000050 assert i != -1, "Impossible line %d to reflow: %r" % (size, s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000051 lines.append(padding + cur[:i])
52 if len(lines) == 1:
53 # find new size based on brace
54 j = cur.find('{', 0, i)
55 if j >= 0:
56 j += 2 # account for the brace and the space after it
57 size -= j
58 padding = " " * j
59 else:
60 j = cur.find('(', 0, i)
61 if j >= 0:
62 j += 1 # account for the paren (no space after it)
63 size -= j
64 padding = " " * j
65 cur = cur[i+1:]
66 else:
67 lines.append(padding + cur)
68 return lines
69
70def is_simple(sum):
71 """Return True if a sum is a simple.
72
73 A sum is simple if its types have no fields, e.g.
74 unaryop = Invert | Not | UAdd | USub
75 """
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000076 for t in sum.types:
77 if t.fields:
78 return False
79 return True
80
Martin v. Löwis618dc5e2008-03-30 20:03:44 +000081
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082class EmitVisitor(asdl.VisitorBase):
83 """Visit that emits lines"""
84
85 def __init__(self, file):
86 self.file = file
87 super(EmitVisitor, self).__init__()
88
Benjamin Peterson87c8d872009-06-11 22:54:11 +000089 def emit(self, s, depth, reflow=True):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000090 # XXX reflow long lines?
91 if reflow:
92 lines = reflow_lines(s, depth)
93 else:
94 lines = [s]
95 for line in lines:
96 line = (" " * TABSIZE * depth) + line + "\n"
97 self.file.write(line)
98
Martin v. Löwis618dc5e2008-03-30 20:03:44 +000099
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000100class TypeDefVisitor(EmitVisitor):
101 def visitModule(self, mod):
102 for dfn in mod.dfns:
103 self.visit(dfn)
104
105 def visitType(self, type, depth=0):
106 self.visit(type.value, type.name, depth)
107
108 def visitSum(self, sum, name, depth):
109 if is_simple(sum):
110 self.simple_sum(sum, name, depth)
111 else:
112 self.sum_with_constructors(sum, name, depth)
113
114 def simple_sum(self, sum, name, depth):
115 enum = []
116 for i in range(len(sum.types)):
117 type = sum.types[i]
118 enum.append("%s=%d" % (type.name, i + 1))
119 enums = ", ".join(enum)
120 ctype = get_c_type(name)
121 s = "typedef enum _%s { %s } %s;" % (name, enums, ctype)
122 self.emit(s, depth)
123 self.emit("", depth)
124
125 def sum_with_constructors(self, sum, name, depth):
126 ctype = get_c_type(name)
127 s = "typedef struct _%(name)s *%(ctype)s;" % locals()
128 self.emit(s, depth)
129 self.emit("", depth)
130
131 def visitProduct(self, product, name, depth):
132 ctype = get_c_type(name)
133 s = "typedef struct _%(name)s *%(ctype)s;" % locals()
134 self.emit(s, depth)
135 self.emit("", depth)
136
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000137
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000138class StructVisitor(EmitVisitor):
139 """Visitor to generate typdefs for AST."""
140
141 def visitModule(self, mod):
142 for dfn in mod.dfns:
143 self.visit(dfn)
144
145 def visitType(self, type, depth=0):
146 self.visit(type.value, type.name, depth)
147
148 def visitSum(self, sum, name, depth):
149 if not is_simple(sum):
150 self.sum_with_constructors(sum, name, depth)
151
152 def sum_with_constructors(self, sum, name, depth):
153 def emit(s, depth=depth):
154 self.emit(s % sys._getframe(1).f_locals, depth)
155 enum = []
156 for i in range(len(sum.types)):
157 type = sum.types[i]
158 enum.append("%s_kind=%d" % (type.name, i + 1))
159
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000160 emit("enum _%(name)s_kind {" + ", ".join(enum) + "};")
161
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000162 emit("struct _%(name)s {")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000163 emit("enum _%(name)s_kind kind;", depth + 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000164 emit("union {", depth + 1)
165 for t in sum.types:
166 self.visit(t, depth + 2)
167 emit("} v;", depth + 1)
168 for field in sum.attributes:
169 # rudimentary attribute handling
170 type = str(field.type)
171 assert type in asdl.builtin_types, type
172 emit("%s %s;" % (type, field.name), depth + 1);
173 emit("};")
174 emit("")
175
176 def visitConstructor(self, cons, depth):
177 if cons.fields:
178 self.emit("struct {", depth)
179 for f in cons.fields:
180 self.visit(f, depth + 1)
181 self.emit("} %s;" % cons.name, depth)
182 self.emit("", depth)
183 else:
184 # XXX not sure what I want here, nothing is probably fine
185 pass
186
187 def visitField(self, field, depth):
188 # XXX need to lookup field.type, because it might be something
189 # like a builtin...
190 ctype = get_c_type(field.type)
191 name = field.name
192 if field.seq:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000193 if field.type.value in ('cmpop',):
194 self.emit("asdl_int_seq *%(name)s;" % locals(), depth)
195 else:
196 self.emit("asdl_seq *%(name)s;" % locals(), depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000197 else:
198 self.emit("%(ctype)s %(name)s;" % locals(), depth)
199
200 def visitProduct(self, product, name, depth):
201 self.emit("struct _%(name)s {" % locals(), depth)
202 for f in product.fields:
203 self.visit(f, depth + 1)
204 self.emit("};", depth)
205 self.emit("", depth)
206
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000207
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000208class PrototypeVisitor(EmitVisitor):
209 """Generate function prototypes for the .h file"""
210
211 def visitModule(self, mod):
212 for dfn in mod.dfns:
213 self.visit(dfn)
214
215 def visitType(self, type):
216 self.visit(type.value, type.name)
217
218 def visitSum(self, sum, name):
219 if is_simple(sum):
220 pass # XXX
221 else:
222 for t in sum.types:
223 self.visit(t, name, sum.attributes)
224
225 def get_args(self, fields):
226 """Return list of C argument into, one for each field.
227
228 Argument info is 3-tuple of a C type, variable name, and flag
229 that is true if type can be NULL.
230 """
231 args = []
232 unnamed = {}
233 for f in fields:
234 if f.name is None:
235 name = f.type
236 c = unnamed[name] = unnamed.get(name, 0) + 1
237 if c > 1:
238 name = "name%d" % (c - 1)
239 else:
240 name = f.name
241 # XXX should extend get_c_type() to handle this
242 if f.seq:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000243 if f.type.value in ('cmpop',):
244 ctype = "asdl_int_seq *"
245 else:
246 ctype = "asdl_seq *"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000247 else:
248 ctype = get_c_type(f.type)
249 args.append((ctype, name, f.opt or f.seq))
250 return args
251
252 def visitConstructor(self, cons, type, attrs):
253 args = self.get_args(cons.fields)
254 attrs = self.get_args(attrs)
255 ctype = get_c_type(type)
256 self.emit_function(cons.name, ctype, args, attrs)
257
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000258 def emit_function(self, name, ctype, args, attrs, union=True):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000259 args = args + attrs
260 if args:
261 argstr = ", ".join(["%s %s" % (atype, aname)
262 for atype, aname, opt in args])
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000263 argstr += ", PyArena *arena"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000264 else:
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000265 argstr = "PyArena *arena"
Thomas Woutersb2137042007-02-01 18:02:27 +0000266 margs = "a0"
267 for i in range(1, len(args)+1):
268 margs += ", a%d" % i
269 self.emit("#define %s(%s) _Py_%s(%s)" % (name, margs, name, margs), 0,
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000270 reflow=False)
271 self.emit("%s _Py_%s(%s);" % (ctype, name, argstr), False)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000272
273 def visitProduct(self, prod, name):
274 self.emit_function(name, get_c_type(name),
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000275 self.get_args(prod.fields), [], union=False)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000276
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000277
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000278class FunctionVisitor(PrototypeVisitor):
279 """Visitor to generate constructor functions for AST."""
280
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000281 def emit_function(self, name, ctype, args, attrs, union=True):
282 def emit(s, depth=0, reflow=True):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000283 self.emit(s, depth, reflow)
284 argstr = ", ".join(["%s %s" % (atype, aname)
285 for atype, aname, opt in args + attrs])
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000286 if argstr:
287 argstr += ", PyArena *arena"
288 else:
289 argstr = "PyArena *arena"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000290 self.emit("%s" % ctype, 0)
291 emit("%s(%s)" % (name, argstr))
292 emit("{")
293 emit("%s p;" % ctype, 1)
294 for argtype, argname, opt in args:
Neal Norwitz3591bbe2007-02-26 19:04:49 +0000295 if not opt and argtype != "int":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296 emit("if (!%s) {" % argname, 1)
297 emit("PyErr_SetString(PyExc_ValueError,", 2)
298 msg = "field %s is required for %s" % (argname, name)
299 emit(' "%s");' % msg,
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000300 2, reflow=False)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000301 emit('return NULL;', 2)
302 emit('}', 1)
303
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000304 emit("p = (%s)PyArena_Malloc(arena, sizeof(*p));" % ctype, 1);
Thomas Woutersa44f3a32007-02-26 18:20:15 +0000305 emit("if (!p)", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000306 emit("return NULL;", 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000307 if union:
308 self.emit_body_union(name, args, attrs)
309 else:
310 self.emit_body_struct(name, args, attrs)
311 emit("return p;", 1)
312 emit("}")
313 emit("")
314
315 def emit_body_union(self, name, args, attrs):
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000316 def emit(s, depth=0, reflow=True):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000317 self.emit(s, depth, reflow)
318 emit("p->kind = %s_kind;" % name, 1)
319 for argtype, argname, opt in args:
320 emit("p->v.%s.%s = %s;" % (name, argname, argname), 1)
321 for argtype, argname, opt in attrs:
322 emit("p->%s = %s;" % (argname, argname), 1)
323
324 def emit_body_struct(self, name, args, attrs):
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000325 def emit(s, depth=0, reflow=True):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000326 self.emit(s, depth, reflow)
327 for argtype, argname, opt in args:
328 emit("p->%s = %s;" % (argname, argname), 1)
329 assert not attrs
330
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000331
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000332class PickleVisitor(EmitVisitor):
333
334 def visitModule(self, mod):
335 for dfn in mod.dfns:
336 self.visit(dfn)
337
338 def visitType(self, type):
339 self.visit(type.value, type.name)
340
341 def visitSum(self, sum, name):
342 pass
343
344 def visitProduct(self, sum, name):
345 pass
346
347 def visitConstructor(self, cons, name):
348 pass
349
350 def visitField(self, sum):
351 pass
352
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000353
354class Obj2ModPrototypeVisitor(PickleVisitor):
355 def visitProduct(self, prod, name):
356 code = "static int obj2ast_%s(PyObject* obj, %s* out, PyArena* arena);"
357 self.emit(code % (name, get_c_type(name)), 0)
358
359 visitSum = visitProduct
360
361
362class Obj2ModVisitor(PickleVisitor):
363 def funcHeader(self, name):
364 ctype = get_c_type(name)
365 self.emit("int", 0)
366 self.emit("obj2ast_%s(PyObject* obj, %s* out, PyArena* arena)" % (name, ctype), 0)
367 self.emit("{", 0)
Benjamin Peterson0e9e98e2010-11-20 02:01:45 +0000368 self.emit("int isinstance;", 1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000369 self.emit("", 0)
370
Benjamin Peterson5b066812010-11-20 01:38:49 +0000371 def sumTrailer(self, name, add_label=False):
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000372 self.emit("", 0)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000373 # there's really nothing more we can do if this fails ...
Benjamin Peterson5b066812010-11-20 01:38:49 +0000374 error = "expected some sort of %s, but got %%R" % name
375 format = "PyErr_Format(PyExc_TypeError, \"%s\", obj);"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000376 self.emit(format % error, 1, reflow=False)
Benjamin Peterson5b066812010-11-20 01:38:49 +0000377 if add_label:
378 self.emit("failed:", 1)
Benjamin Peterson0a4dae52010-11-21 15:12:34 +0000379 self.emit("Py_XDECREF(tmp);", 1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000380 self.emit("return 1;", 1)
381 self.emit("}", 0)
382 self.emit("", 0)
383
384 def simpleSum(self, sum, name):
385 self.funcHeader(name)
386 for t in sum.types:
Benjamin Peterson97dd9872009-12-13 01:23:39 +0000387 line = ("isinstance = PyObject_IsInstance(obj, "
388 "(PyObject *)%s_type);")
389 self.emit(line % (t.name,), 1)
390 self.emit("if (isinstance == -1) {", 1)
391 self.emit("return 1;", 2)
392 self.emit("}", 1)
393 self.emit("if (isinstance) {", 1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000394 self.emit("*out = %s;" % t.name, 2)
395 self.emit("return 0;", 2)
396 self.emit("}", 1)
397 self.sumTrailer(name)
398
399 def buildArgs(self, fields):
400 return ", ".join(fields + ["arena"])
401
402 def complexSum(self, sum, name):
403 self.funcHeader(name)
Benjamin Petersond8f65972010-11-20 04:31:07 +0000404 self.emit("PyObject *tmp = NULL;", 1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000405 for a in sum.attributes:
406 self.visitAttributeDeclaration(a, name, sum=sum)
407 self.emit("", 0)
408 # XXX: should we only do this for 'expr'?
409 self.emit("if (obj == Py_None) {", 1)
410 self.emit("*out = NULL;", 2)
411 self.emit("return 0;", 2)
412 self.emit("}", 1)
413 for a in sum.attributes:
414 self.visitField(a, name, sum=sum, depth=1)
415 for t in sum.types:
Benjamin Peterson97dd9872009-12-13 01:23:39 +0000416 line = "isinstance = PyObject_IsInstance(obj, (PyObject*)%s_type);"
417 self.emit(line % (t.name,), 1)
418 self.emit("if (isinstance == -1) {", 1)
419 self.emit("return 1;", 2)
420 self.emit("}", 1)
421 self.emit("if (isinstance) {", 1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000422 for f in t.fields:
423 self.visitFieldDeclaration(f, t.name, sum=sum, depth=2)
424 self.emit("", 0)
425 for f in t.fields:
426 self.visitField(f, t.name, sum=sum, depth=2)
427 args = [f.name.value for f in t.fields] + [a.name.value for a in sum.attributes]
428 self.emit("*out = %s(%s);" % (t.name, self.buildArgs(args)), 2)
429 self.emit("if (*out == NULL) goto failed;", 2)
430 self.emit("return 0;", 2)
431 self.emit("}", 1)
Benjamin Peterson5b066812010-11-20 01:38:49 +0000432 self.sumTrailer(name, True)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000433
434 def visitAttributeDeclaration(self, a, name, sum=sum):
435 ctype = get_c_type(a.type)
436 self.emit("%s %s;" % (ctype, a.name), 1)
437
438 def visitSum(self, sum, name):
439 if is_simple(sum):
440 self.simpleSum(sum, name)
441 else:
442 self.complexSum(sum, name)
443
444 def visitProduct(self, prod, name):
445 ctype = get_c_type(name)
446 self.emit("int", 0)
447 self.emit("obj2ast_%s(PyObject* obj, %s* out, PyArena* arena)" % (name, ctype), 0)
448 self.emit("{", 0)
449 self.emit("PyObject* tmp = NULL;", 1)
450 for f in prod.fields:
451 self.visitFieldDeclaration(f, name, prod=prod, depth=1)
452 self.emit("", 0)
453 for f in prod.fields:
454 self.visitField(f, name, prod=prod, depth=1)
455 args = [f.name.value for f in prod.fields]
456 self.emit("*out = %s(%s);" % (name, self.buildArgs(args)), 1)
457 self.emit("return 0;", 1)
458 self.emit("failed:", 0)
459 self.emit("Py_XDECREF(tmp);", 1)
460 self.emit("return 1;", 1)
461 self.emit("}", 0)
462 self.emit("", 0)
463
464 def visitFieldDeclaration(self, field, name, sum=None, prod=None, depth=0):
465 ctype = get_c_type(field.type)
466 if field.seq:
467 if self.isSimpleType(field):
468 self.emit("asdl_int_seq* %s;" % field.name, depth)
469 else:
470 self.emit("asdl_seq* %s;" % field.name, depth)
471 else:
472 ctype = get_c_type(field.type)
473 self.emit("%s %s;" % (ctype, field.name), depth)
474
475 def isSimpleSum(self, field):
476 # XXX can the members of this list be determined automatically?
477 return field.type.value in ('expr_context', 'boolop', 'operator',
478 'unaryop', 'cmpop')
479
480 def isNumeric(self, field):
481 return get_c_type(field.type) in ("int", "bool")
482
483 def isSimpleType(self, field):
484 return self.isSimpleSum(field) or self.isNumeric(field)
485
486 def visitField(self, field, name, sum=None, prod=None, depth=0):
487 ctype = get_c_type(field.type)
488 self.emit("if (PyObject_HasAttrString(obj, \"%s\")) {" % field.name, depth)
489 self.emit("int res;", depth+1)
490 if field.seq:
491 self.emit("Py_ssize_t len;", depth+1)
492 self.emit("Py_ssize_t i;", depth+1)
493 self.emit("tmp = PyObject_GetAttrString(obj, \"%s\");" % field.name, depth+1)
494 self.emit("if (tmp == NULL) goto failed;", depth+1)
495 if field.seq:
496 self.emit("if (!PyList_Check(tmp)) {", depth+1)
497 self.emit("PyErr_Format(PyExc_TypeError, \"%s field \\\"%s\\\" must "
498 "be a list, not a %%.200s\", tmp->ob_type->tp_name);" %
499 (name, field.name),
500 depth+2, reflow=False)
501 self.emit("goto failed;", depth+2)
502 self.emit("}", depth+1)
503 self.emit("len = PyList_GET_SIZE(tmp);", depth+1)
504 if self.isSimpleType(field):
505 self.emit("%s = asdl_int_seq_new(len, arena);" % field.name, depth+1)
506 else:
507 self.emit("%s = asdl_seq_new(len, arena);" % field.name, depth+1)
508 self.emit("if (%s == NULL) goto failed;" % field.name, depth+1)
509 self.emit("for (i = 0; i < len; i++) {", depth+1)
510 self.emit("%s value;" % ctype, depth+2)
511 self.emit("res = obj2ast_%s(PyList_GET_ITEM(tmp, i), &value, arena);" %
512 field.type, depth+2, reflow=False)
513 self.emit("if (res != 0) goto failed;", depth+2)
514 self.emit("asdl_seq_SET(%s, i, value);" % field.name, depth+2)
515 self.emit("}", depth+1)
516 else:
517 self.emit("res = obj2ast_%s(tmp, &%s, arena);" %
518 (field.type, field.name), depth+1)
519 self.emit("if (res != 0) goto failed;", depth+1)
520
521 self.emit("Py_XDECREF(tmp);", depth+1)
522 self.emit("tmp = NULL;", depth+1)
523 self.emit("} else {", depth)
524 if not field.opt:
525 message = "required field \\\"%s\\\" missing from %s" % (field.name, name)
526 format = "PyErr_SetString(PyExc_TypeError, \"%s\");"
527 self.emit(format % message, depth+1, reflow=False)
528 self.emit("return 1;", depth+1)
529 else:
530 if self.isNumeric(field):
531 self.emit("%s = 0;" % field.name, depth+1)
532 elif not self.isSimpleType(field):
533 self.emit("%s = NULL;" % field.name, depth+1)
534 else:
535 raise TypeError("could not determine the default value for %s" % field.name)
536 self.emit("}", depth)
537
538
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000539class MarshalPrototypeVisitor(PickleVisitor):
540
541 def prototype(self, sum, name):
542 ctype = get_c_type(name)
Neal Norwitz6576bd82005-11-13 18:41:28 +0000543 self.emit("static int marshal_write_%s(PyObject **, int *, %s);"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000544 % (name, ctype), 0)
545
546 visitProduct = visitSum = prototype
547
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000548
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000549class PyTypesDeclareVisitor(PickleVisitor):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000550
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000551 def visitProduct(self, prod, name):
Neal Norwitz53d960c2006-02-28 22:47:29 +0000552 self.emit("static PyTypeObject *%s_type;" % name, 0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000553 self.emit("static PyObject* ast2obj_%s(void*);" % name, 0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000554 if prod.fields:
Neal Norwitz53d960c2006-02-28 22:47:29 +0000555 self.emit("static char *%s_fields[]={" % name,0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000556 for f in prod.fields:
557 self.emit('"%s",' % f.name, 1)
558 self.emit("};", 0)
Tim Peters710ab3b2006-02-28 18:30:36 +0000559
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000560 def visitSum(self, sum, name):
Neal Norwitz53d960c2006-02-28 22:47:29 +0000561 self.emit("static PyTypeObject *%s_type;" % name, 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000562 if sum.attributes:
Neal Norwitz53d960c2006-02-28 22:47:29 +0000563 self.emit("static char *%s_attributes[] = {" % name, 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000564 for a in sum.attributes:
565 self.emit('"%s",' % a.name, 1)
566 self.emit("};", 0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000567 ptype = "void*"
568 if is_simple(sum):
569 ptype = get_c_type(name)
570 tnames = []
571 for t in sum.types:
572 tnames.append(str(t.name)+"_singleton")
573 tnames = ", *".join(tnames)
574 self.emit("static PyObject *%s;" % tnames, 0)
575 self.emit("static PyObject* ast2obj_%s(%s);" % (name, ptype), 0)
576 for t in sum.types:
577 self.visitConstructor(t, name)
Tim Peters710ab3b2006-02-28 18:30:36 +0000578
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000579 def visitConstructor(self, cons, name):
Neal Norwitz53d960c2006-02-28 22:47:29 +0000580 self.emit("static PyTypeObject *%s_type;" % cons.name, 0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000581 if cons.fields:
Neal Norwitz53d960c2006-02-28 22:47:29 +0000582 self.emit("static char *%s_fields[]={" % cons.name, 0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000583 for t in cons.fields:
584 self.emit('"%s",' % t.name, 1)
585 self.emit("};",0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000586
587class PyTypesVisitor(PickleVisitor):
588
589 def visitModule(self, mod):
590 self.emit("""
Neal Norwitz207c9f32008-03-31 04:42:11 +0000591static int
592ast_type_init(PyObject *self, PyObject *args, PyObject *kw)
593{
594 Py_ssize_t i, numfields = 0;
595 int res = -1;
596 PyObject *key, *value, *fields;
597 fields = PyObject_GetAttrString((PyObject*)Py_TYPE(self), "_fields");
598 if (!fields)
599 PyErr_Clear();
600 if (fields) {
601 numfields = PySequence_Size(fields);
602 if (numfields == -1)
603 goto cleanup;
604 }
605 res = 0; /* if no error occurs, this stays 0 to the end */
606 if (PyTuple_GET_SIZE(args) > 0) {
607 if (numfields != PyTuple_GET_SIZE(args)) {
608 PyErr_Format(PyExc_TypeError, "%.400s constructor takes %s"
Benjamin Peterson75080da2008-09-10 22:37:34 +0000609 "%zd positional argument%s",
Neal Norwitz207c9f32008-03-31 04:42:11 +0000610 Py_TYPE(self)->tp_name,
611 numfields == 0 ? "" : "either 0 or ",
612 numfields, numfields == 1 ? "" : "s");
613 res = -1;
614 goto cleanup;
615 }
616 for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
617 /* cannot be reached when fields is NULL */
618 PyObject *name = PySequence_GetItem(fields, i);
619 if (!name) {
620 res = -1;
621 goto cleanup;
622 }
623 res = PyObject_SetAttr(self, name, PyTuple_GET_ITEM(args, i));
624 Py_DECREF(name);
625 if (res < 0)
626 goto cleanup;
627 }
628 }
629 if (kw) {
630 i = 0; /* needed by PyDict_Next */
631 while (PyDict_Next(kw, &i, &key, &value)) {
632 res = PyObject_SetAttr(self, key, value);
633 if (res < 0)
634 goto cleanup;
635 }
636 }
637 cleanup:
638 Py_XDECREF(fields);
639 return res;
640}
641
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000642/* Pickling support */
643static PyObject *
644ast_type_reduce(PyObject *self, PyObject *unused)
645{
646 PyObject *res;
647 PyObject *dict = PyObject_GetAttrString(self, "__dict__");
648 if (dict == NULL) {
649 if (PyErr_ExceptionMatches(PyExc_AttributeError))
650 PyErr_Clear();
651 else
652 return NULL;
653 }
654 if (dict) {
655 res = Py_BuildValue("O()O", Py_TYPE(self), dict);
656 Py_DECREF(dict);
657 return res;
658 }
659 return Py_BuildValue("O()", Py_TYPE(self));
660}
661
662static PyMethodDef ast_type_methods[] = {
663 {"__reduce__", ast_type_reduce, METH_NOARGS, NULL},
664 {NULL}
665};
666
Neal Norwitz207c9f32008-03-31 04:42:11 +0000667static PyTypeObject AST_type = {
668 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000669 "_ast.AST",
Neal Norwitz207c9f32008-03-31 04:42:11 +0000670 sizeof(PyObject),
671 0,
672 0, /* tp_dealloc */
673 0, /* tp_print */
674 0, /* tp_getattr */
675 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +0000676 0, /* tp_reserved */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000677 0, /* tp_repr */
678 0, /* tp_as_number */
679 0, /* tp_as_sequence */
680 0, /* tp_as_mapping */
681 0, /* tp_hash */
682 0, /* tp_call */
683 0, /* tp_str */
684 PyObject_GenericGetAttr, /* tp_getattro */
685 PyObject_GenericSetAttr, /* tp_setattro */
686 0, /* tp_as_buffer */
687 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
688 0, /* tp_doc */
689 0, /* tp_traverse */
690 0, /* tp_clear */
691 0, /* tp_richcompare */
692 0, /* tp_weaklistoffset */
693 0, /* tp_iter */
694 0, /* tp_iternext */
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000695 ast_type_methods, /* tp_methods */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000696 0, /* tp_members */
697 0, /* tp_getset */
698 0, /* tp_base */
699 0, /* tp_dict */
700 0, /* tp_descr_get */
701 0, /* tp_descr_set */
702 0, /* tp_dictoffset */
703 (initproc)ast_type_init, /* tp_init */
704 PyType_GenericAlloc, /* tp_alloc */
705 PyType_GenericNew, /* tp_new */
706 PyObject_Del, /* tp_free */
707};
708
709
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000710static PyTypeObject* make_type(char *type, PyTypeObject* base, char**fields, int num_fields)
711{
712 PyObject *fnames, *result;
713 int i;
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000714 fnames = PyTuple_New(num_fields);
715 if (!fnames) return NULL;
716 for (i = 0; i < num_fields; i++) {
Neal Norwitze4dc3242007-08-25 01:33:49 +0000717 PyObject *field = PyUnicode_FromString(fields[i]);
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000718 if (!field) {
719 Py_DECREF(fnames);
720 return NULL;
721 }
722 PyTuple_SET_ITEM(fnames, i, field);
723 }
Benjamin Peterson5b927722010-06-07 22:24:18 +0000724 result = PyObject_CallFunction((PyObject*)&PyType_Type, "s(O){sOss}",
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000725 type, base, "_fields", fnames, "__module__", "_ast");
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000726 Py_DECREF(fnames);
727 return (PyTypeObject*)result;
728}
729
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000730static int add_attributes(PyTypeObject* type, char**attrs, int num_fields)
731{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000732 int i, result;
Neal Norwitz207c9f32008-03-31 04:42:11 +0000733 PyObject *s, *l = PyTuple_New(num_fields);
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000734 if (!l)
735 return 0;
736 for (i = 0; i < num_fields; i++) {
Neal Norwitze4dc3242007-08-25 01:33:49 +0000737 s = PyUnicode_FromString(attrs[i]);
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000738 if (!s) {
739 Py_DECREF(l);
740 return 0;
741 }
Neal Norwitz207c9f32008-03-31 04:42:11 +0000742 PyTuple_SET_ITEM(l, i, s);
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000743 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000744 result = PyObject_SetAttrString((PyObject*)type, "_attributes", l) >= 0;
745 Py_DECREF(l);
746 return result;
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000747}
748
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000749/* Conversion AST -> Python */
750
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000751static PyObject* ast2obj_list(asdl_seq *seq, PyObject* (*func)(void*))
752{
753 int i, n = asdl_seq_LEN(seq);
754 PyObject *result = PyList_New(n);
755 PyObject *value;
756 if (!result)
757 return NULL;
758 for (i = 0; i < n; i++) {
759 value = func(asdl_seq_GET(seq, i));
760 if (!value) {
761 Py_DECREF(result);
762 return NULL;
763 }
764 PyList_SET_ITEM(result, i, value);
765 }
766 return result;
767}
768
769static PyObject* ast2obj_object(void *o)
770{
771 if (!o)
772 o = Py_None;
773 Py_INCREF((PyObject*)o);
774 return (PyObject*)o;
775}
776#define ast2obj_identifier ast2obj_object
777#define ast2obj_string ast2obj_object
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000778
Thomas Woutersa44f3a32007-02-26 18:20:15 +0000779static PyObject* ast2obj_int(long b)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000780{
Christian Heimes2b1c5922007-12-02 22:43:00 +0000781 return PyLong_FromLong(b);
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000782}
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000783
784/* Conversion Python -> AST */
785
786static int obj2ast_object(PyObject* obj, PyObject** out, PyArena* arena)
787{
788 if (obj == Py_None)
789 obj = NULL;
790 if (obj)
791 PyArena_AddPyObject(arena, obj);
792 Py_XINCREF(obj);
793 *out = obj;
794 return 0;
795}
796
797#define obj2ast_identifier obj2ast_object
798#define obj2ast_string obj2ast_object
799
800static int obj2ast_int(PyObject* obj, int* out, PyArena* arena)
801{
802 int i;
803 if (!PyLong_Check(obj)) {
804 PyObject *s = PyObject_Repr(obj);
805 if (s == NULL) return 1;
806 PyErr_Format(PyExc_ValueError, "invalid integer value: %.400s",
Christian Heimes72b710a2008-05-26 13:28:38 +0000807 PyBytes_AS_STRING(s));
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000808 Py_DECREF(s);
809 return 1;
810 }
811
812 i = (int)PyLong_AsLong(obj);
813 if (i == -1 && PyErr_Occurred())
814 return 1;
815 *out = i;
816 return 0;
817}
818
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +0000819static int add_ast_fields(void)
Benjamin Peterson206e3072008-10-19 14:07:49 +0000820{
821 PyObject *empty_tuple, *d;
822 if (PyType_Ready(&AST_type) < 0)
823 return -1;
824 d = AST_type.tp_dict;
825 empty_tuple = PyTuple_New(0);
826 if (!empty_tuple ||
827 PyDict_SetItemString(d, "_fields", empty_tuple) < 0 ||
828 PyDict_SetItemString(d, "_attributes", empty_tuple) < 0) {
829 Py_XDECREF(empty_tuple);
830 return -1;
831 }
832 Py_DECREF(empty_tuple);
833 return 0;
834}
835
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000836""", 0, reflow=False)
837
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000838 self.emit("static int init_types(void)",0)
839 self.emit("{", 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000840 self.emit("static int initialized;", 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000841 self.emit("if (initialized) return 1;", 1)
Benjamin Peterson206e3072008-10-19 14:07:49 +0000842 self.emit("if (add_ast_fields() < 0) return 0;", 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000843 for dfn in mod.dfns:
844 self.visit(dfn)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000845 self.emit("initialized = 1;", 1)
846 self.emit("return 1;", 1);
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000847 self.emit("}", 0)
848
849 def visitProduct(self, prod, name):
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000850 if prod.fields:
851 fields = name.value+"_fields"
852 else:
853 fields = "NULL"
Neal Norwitz207c9f32008-03-31 04:42:11 +0000854 self.emit('%s_type = make_type("%s", &AST_type, %s, %d);' %
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000855 (name, name, fields, len(prod.fields)), 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000856 self.emit("if (!%s_type) return 0;" % name, 1)
Tim Peters710ab3b2006-02-28 18:30:36 +0000857
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000858 def visitSum(self, sum, name):
Neal Norwitz207c9f32008-03-31 04:42:11 +0000859 self.emit('%s_type = make_type("%s", &AST_type, NULL, 0);' %
860 (name, name), 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000861 self.emit("if (!%s_type) return 0;" % name, 1)
862 if sum.attributes:
Tim Peters710ab3b2006-02-28 18:30:36 +0000863 self.emit("if (!add_attributes(%s_type, %s_attributes, %d)) return 0;" %
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000864 (name, name, len(sum.attributes)), 1)
865 else:
866 self.emit("if (!add_attributes(%s_type, NULL, 0)) return 0;" % name, 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000867 simple = is_simple(sum)
868 for t in sum.types:
869 self.visitConstructor(t, name, simple)
Tim Peters710ab3b2006-02-28 18:30:36 +0000870
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000871 def visitConstructor(self, cons, name, simple):
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000872 if cons.fields:
873 fields = cons.name.value+"_fields"
874 else:
875 fields = "NULL"
Tim Peters710ab3b2006-02-28 18:30:36 +0000876 self.emit('%s_type = make_type("%s", %s_type, %s, %d);' %
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000877 (cons.name, cons.name, name, fields, len(cons.fields)), 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000878 self.emit("if (!%s_type) return 0;" % cons.name, 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000879 if simple:
880 self.emit("%s_singleton = PyType_GenericNew(%s_type, NULL, NULL);" %
881 (cons.name, cons.name), 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000882 self.emit("if (!%s_singleton) return 0;" % cons.name, 1)
Tim Peters710ab3b2006-02-28 18:30:36 +0000883
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000884
Thomas Wouterscf297e42007-02-23 15:07:44 +0000885def parse_version(mod):
886 return mod.version.value[12:-3]
887
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000888class ASTModuleVisitor(PickleVisitor):
889
890 def visitModule(self, mod):
Martin v. Löwis1a214512008-06-11 05:26:20 +0000891 self.emit("static struct PyModuleDef _astmodule = {", 0)
892 self.emit(' PyModuleDef_HEAD_INIT, "_ast"', 0)
893 self.emit("};", 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000894 self.emit("PyMODINIT_FUNC", 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000895 self.emit("PyInit__ast(void)", 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000896 self.emit("{", 0)
897 self.emit("PyObject *m, *d;", 1)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000898 self.emit("if (!init_types()) return NULL;", 1)
899 self.emit('m = PyModule_Create(&_astmodule);', 1)
900 self.emit("if (!m) return NULL;", 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000901 self.emit("d = PyModule_GetDict(m);", 1)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000902 self.emit('if (PyDict_SetItemString(d, "AST", (PyObject*)&AST_type) < 0) return NULL;', 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000903 self.emit('if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0)', 1)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000904 self.emit("return NULL;", 2)
Martin v. Löwis40d84592006-02-28 00:30:54 +0000905 # Value of version: "$Revision$"
Thomas Wouterscf297e42007-02-23 15:07:44 +0000906 self.emit('if (PyModule_AddStringConstant(m, "__version__", "%s") < 0)'
907 % parse_version(mod), 1)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000908 self.emit("return NULL;", 2)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000909 for dfn in mod.dfns:
910 self.visit(dfn)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000911 self.emit("return m;", 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000912 self.emit("}", 0)
913
914 def visitProduct(self, prod, name):
915 self.addObj(name)
Tim Peters710ab3b2006-02-28 18:30:36 +0000916
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000917 def visitSum(self, sum, name):
918 self.addObj(name)
919 for t in sum.types:
920 self.visitConstructor(t, name)
Tim Peters710ab3b2006-02-28 18:30:36 +0000921
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000922 def visitConstructor(self, cons, name):
923 self.addObj(cons.name)
Tim Peters710ab3b2006-02-28 18:30:36 +0000924
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000925 def addObj(self, name):
Martin v. Löwis1a214512008-06-11 05:26:20 +0000926 self.emit('if (PyDict_SetItemString(d, "%s", (PyObject*)%s_type) < 0) return NULL;' % (name, name), 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000927
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000928
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000929_SPECIALIZED_SEQUENCES = ('stmt', 'expr')
930
931def find_sequence(fields, doing_specialization):
932 """Return True if any field uses a sequence."""
933 for f in fields:
934 if f.seq:
935 if not doing_specialization:
936 return True
937 if str(f.type) not in _SPECIALIZED_SEQUENCES:
938 return True
939 return False
940
941def has_sequence(types, doing_specialization):
942 for t in types:
943 if find_sequence(t.fields, doing_specialization):
944 return True
945 return False
946
947
948class StaticVisitor(PickleVisitor):
Neal Norwitz7b5a6042005-11-13 19:14:20 +0000949 CODE = '''Very simple, always emit this static code. Overide CODE'''
950
951 def visit(self, object):
952 self.emit(self.CODE, 0, reflow=False)
953
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000954
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000955class ObjVisitor(PickleVisitor):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000956
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000957 def func_begin(self, name):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000958 ctype = get_c_type(name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000959 self.emit("PyObject*", 0)
960 self.emit("ast2obj_%s(void* _o)" % (name), 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000961 self.emit("{", 0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000962 self.emit("%s o = (%s)_o;" % (ctype, ctype), 1)
963 self.emit("PyObject *result = NULL, *value = NULL;", 1)
964 self.emit('if (!o) {', 1)
965 self.emit("Py_INCREF(Py_None);", 2)
966 self.emit('return Py_None;', 2)
967 self.emit("}", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000968 self.emit('', 0)
969
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000970 def func_end(self):
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000971 self.emit("return result;", 1)
972 self.emit("failed:", 0)
973 self.emit("Py_XDECREF(value);", 1)
974 self.emit("Py_XDECREF(result);", 1)
975 self.emit("return NULL;", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000976 self.emit("}", 0)
977 self.emit("", 0)
978
979 def visitSum(self, sum, name):
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000980 if is_simple(sum):
981 self.simpleSum(sum, name)
982 return
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000983 self.func_begin(name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000984 self.emit("switch (o->kind) {", 1)
985 for i in range(len(sum.types)):
986 t = sum.types[i]
987 self.visitConstructor(t, i + 1, name)
988 self.emit("}", 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000989 for a in sum.attributes:
990 self.emit("value = ast2obj_%s(o->%s);" % (a.type, a.name), 1)
991 self.emit("if (!value) goto failed;", 1)
Martin v. Löwis03e5bc02006-03-02 00:31:27 +0000992 self.emit('if (PyObject_SetAttrString(result, "%s", value) < 0)' % a.name, 1)
993 self.emit('goto failed;', 2)
994 self.emit('Py_DECREF(value);', 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000995 self.func_end()
Tim Peters710ab3b2006-02-28 18:30:36 +0000996
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000997 def simpleSum(self, sum, name):
998 self.emit("PyObject* ast2obj_%s(%s_ty o)" % (name, name), 0)
999 self.emit("{", 0)
1000 self.emit("switch(o) {", 1)
1001 for t in sum.types:
1002 self.emit("case %s:" % t.name, 2)
1003 self.emit("Py_INCREF(%s_singleton);" % t.name, 3)
1004 self.emit("return %s_singleton;" % t.name, 3)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001005 self.emit("default:" % name, 2)
1006 self.emit('/* should never happen, but just in case ... */', 3)
1007 code = "PyErr_Format(PyExc_SystemError, \"unknown %s found\");" % name
1008 self.emit(code, 3, reflow=False)
1009 self.emit("return NULL;", 3)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001010 self.emit("}", 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001011 self.emit("}", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001012
1013 def visitProduct(self, prod, name):
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001014 self.func_begin(name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001015 self.emit("result = PyType_GenericNew(%s_type, NULL, NULL);" % name, 1);
1016 self.emit("if (!result) return NULL;", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001017 for field in prod.fields:
1018 self.visitField(field, name, 1, True)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001019 self.func_end()
Tim Peters536cf992005-12-25 23:18:31 +00001020
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001021 def visitConstructor(self, cons, enum, name):
1022 self.emit("case %s_kind:" % cons.name, 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001023 self.emit("result = PyType_GenericNew(%s_type, NULL, NULL);" % cons.name, 2);
1024 self.emit("if (!result) goto failed;", 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001025 for f in cons.fields:
1026 self.visitField(f, cons.name, 2, False)
1027 self.emit("break;", 2)
1028
1029 def visitField(self, field, name, depth, product):
1030 def emit(s, d):
1031 self.emit(s, depth + d)
1032 if product:
1033 value = "o->%s" % field.name
1034 else:
1035 value = "o->v.%s.%s" % (name, field.name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001036 self.set(field, value, depth)
1037 emit("if (!value) goto failed;", 0)
1038 emit('if (PyObject_SetAttrString(result, "%s", value) == -1)' % field.name, 0)
1039 emit("goto failed;", 1)
1040 emit("Py_DECREF(value);", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001041
1042 def emitSeq(self, field, value, depth, emit):
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001043 emit("seq = %s;" % value, 0)
1044 emit("n = asdl_seq_LEN(seq);", 0)
1045 emit("value = PyList_New(n);", 0)
1046 emit("if (!value) goto failed;", 0)
1047 emit("for (i = 0; i < n; i++) {", 0)
1048 self.set("value", field, "asdl_seq_GET(seq, i)", depth + 1)
1049 emit("if (!value1) goto failed;", 1)
1050 emit("PyList_SET_ITEM(value, i, value1);", 1)
1051 emit("value1 = NULL;", 1)
1052 emit("}", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001053
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001054 def set(self, field, value, depth):
1055 if field.seq:
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001056 # XXX should really check for is_simple, but that requires a symbol table
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001057 if field.type.value == "cmpop":
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001058 # While the sequence elements are stored as void*,
1059 # ast2obj_cmpop expects an enum
1060 self.emit("{", depth)
1061 self.emit("int i, n = asdl_seq_LEN(%s);" % value, depth+1)
1062 self.emit("value = PyList_New(n);", depth+1)
1063 self.emit("if (!value) goto failed;", depth+1)
1064 self.emit("for(i = 0; i < n; i++)", depth+1)
1065 # This cannot fail, so no need for error handling
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001066 self.emit("PyList_SET_ITEM(value, i, ast2obj_cmpop((cmpop_ty)asdl_seq_GET(%s, i)));" % value,
1067 depth+2, reflow=False)
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001068 self.emit("}", depth)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001069 else:
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001070 self.emit("value = ast2obj_list(%s, ast2obj_%s);" % (value, field.type), depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001071 else:
1072 ctype = get_c_type(field.type)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001073 self.emit("value = ast2obj_%s(%s);" % (field.type, value), depth, reflow=False)
Tim Peters536cf992005-12-25 23:18:31 +00001074
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001075
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001076class PartingShots(StaticVisitor):
1077
1078 CODE = """
1079PyObject* PyAST_mod2obj(mod_ty t)
1080{
1081 init_types();
1082 return ast2obj_mod(t);
1083}
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001084
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001085/* mode is 0 for "exec", 1 for "eval" and 2 for "single" input */
1086mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001087{
1088 mod_ty res;
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001089 PyObject *req_type[] = {(PyObject*)Module_type, (PyObject*)Expression_type,
1090 (PyObject*)Interactive_type};
1091 char *req_name[] = {"Module", "Expression", "Interactive"};
Benjamin Peterson97dd9872009-12-13 01:23:39 +00001092 int isinstance;
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001093 assert(0 <= mode && mode <= 2);
1094
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001095 init_types();
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001096
Benjamin Peterson97dd9872009-12-13 01:23:39 +00001097 isinstance = PyObject_IsInstance(ast, req_type[mode]);
1098 if (isinstance == -1)
1099 return NULL;
1100 if (!isinstance) {
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001101 PyErr_Format(PyExc_TypeError, "expected %s node, got %.400s",
1102 req_name[mode], Py_TYPE(ast)->tp_name);
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001103 return NULL;
1104 }
1105 if (obj2ast_mod(ast, &res, arena) != 0)
1106 return NULL;
1107 else
1108 return res;
1109}
1110
1111int PyAST_Check(PyObject* obj)
1112{
1113 init_types();
Neal Norwitz207c9f32008-03-31 04:42:11 +00001114 return PyObject_IsInstance(obj, (PyObject*)&AST_type);
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001115}
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001116"""
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001117
1118class ChainOfVisitors:
1119 def __init__(self, *visitors):
1120 self.visitors = visitors
1121
1122 def visit(self, object):
1123 for v in self.visitors:
1124 v.visit(object)
Neal Norwitz7b5a6042005-11-13 19:14:20 +00001125 v.emit("", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001126
Guido van Rossum805365e2007-05-07 22:24:25 +00001127common_msg = "/* File automatically generated by %s. */\n\n"
Thomas Wouterscf297e42007-02-23 15:07:44 +00001128
1129c_file_msg = """
1130/*
1131 __version__ %s.
1132
1133 This module must be committed separately after each AST grammar change;
1134 The __version__ number is set to the revision number of the commit
1135 containing the grammar change.
1136*/
Guido van Rossum805365e2007-05-07 22:24:25 +00001137
Thomas Wouterscf297e42007-02-23 15:07:44 +00001138"""
1139
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001140def main(srcfile):
Neal Norwitz897ff812005-12-11 21:18:22 +00001141 argv0 = sys.argv[0]
Armin Rigo6b1793f2005-12-14 18:05:14 +00001142 components = argv0.split(os.sep)
1143 argv0 = os.sep.join(components[-2:])
Thomas Wouterscf297e42007-02-23 15:07:44 +00001144 auto_gen_msg = common_msg % argv0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001145 mod = asdl.parse(srcfile)
1146 if not asdl.check(mod):
1147 sys.exit(1)
1148 if INC_DIR:
1149 p = "%s/%s-ast.h" % (INC_DIR, mod.name)
Guido van Rossum2af1d892007-11-23 21:26:49 +00001150 f = open(p, "w")
Guido van Rossum805365e2007-05-07 22:24:25 +00001151 f.write(auto_gen_msg)
1152 f.write('#include "asdl.h"\n\n')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001153 c = ChainOfVisitors(TypeDefVisitor(f),
1154 StructVisitor(f),
1155 PrototypeVisitor(f),
1156 )
1157 c.visit(mod)
Guido van Rossum805365e2007-05-07 22:24:25 +00001158 f.write("PyObject* PyAST_mod2obj(mod_ty t);\n")
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001159 f.write("mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode);\n")
1160 f.write("int PyAST_Check(PyObject* obj);\n")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001161 f.close()
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162
1163 if SRC_DIR:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001164 p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c")
Guido van Rossum2af1d892007-11-23 21:26:49 +00001165 f = open(p, "w")
Guido van Rossum805365e2007-05-07 22:24:25 +00001166 f.write(auto_gen_msg)
1167 f.write(c_file_msg % parse_version(mod))
1168 f.write('#include "Python.h"\n')
1169 f.write('#include "%s-ast.h"\n' % mod.name)
1170 f.write('\n')
Neal Norwitz207c9f32008-03-31 04:42:11 +00001171 f.write("static PyTypeObject AST_type;\n")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001172 v = ChainOfVisitors(
1173 PyTypesDeclareVisitor(f),
1174 PyTypesVisitor(f),
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001175 Obj2ModPrototypeVisitor(f),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001176 FunctionVisitor(f),
1177 ObjVisitor(f),
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001178 Obj2ModVisitor(f),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001179 ASTModuleVisitor(f),
1180 PartingShots(f),
1181 )
1182 v.visit(mod)
1183 f.close()
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001184
1185if __name__ == "__main__":
1186 import sys
1187 import getopt
1188
1189 INC_DIR = ''
1190 SRC_DIR = ''
1191 opts, args = getopt.getopt(sys.argv[1:], "h:c:")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001192 if len(opts) != 1:
Guido van Rossum805365e2007-05-07 22:24:25 +00001193 sys.stdout.write("Must specify exactly one output file\n")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001194 sys.exit(1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195 for o, v in opts:
1196 if o == '-h':
1197 INC_DIR = v
1198 if o == '-c':
1199 SRC_DIR = v
1200 if len(args) != 1:
Guido van Rossum805365e2007-05-07 22:24:25 +00001201 sys.stdout.write("Must specify single input file\n")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001202 sys.exit(1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203 main(args[0])