blob: a743aac2341069c7d8267099e656b63d0f71d3b9 [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
89 def emit(self, s, depth, reflow=1):
90 # 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
258 def emit_function(self, name, ctype, args, attrs, union=1):
259 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,
270 reflow = 0)
271 self.emit("%s _Py_%s(%s);" % (ctype, name, argstr), 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000272
273 def visitProduct(self, prod, name):
274 self.emit_function(name, get_c_type(name),
275 self.get_args(prod.fields), [], union=0)
276
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
281 def emit_function(self, name, ctype, args, attrs, union=1):
282 def emit(s, depth=0, reflow=1):
283 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,
300 2, reflow=0)
301 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):
316 def emit(s, depth=0, reflow=1):
317 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):
325 def emit(s, depth=0, reflow=1):
326 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)
368 self.emit("PyObject* tmp = NULL;", 1)
369 self.emit("", 0)
370
371 def sumTrailer(self, name):
372 self.emit("", 0)
373 self.emit("tmp = PyObject_Repr(obj);", 1)
374 # there's really nothing more we can do if this fails ...
375 self.emit("if (tmp == NULL) goto failed;", 1)
376 error = "expected some sort of %s, but got %%.400s" % name
Christian Heimes72b710a2008-05-26 13:28:38 +0000377 format = "PyErr_Format(PyExc_TypeError, \"%s\", PyBytes_AS_STRING(tmp));"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000378 self.emit(format % error, 1, reflow=False)
379 self.emit("failed:", 0)
380 self.emit("Py_XDECREF(tmp);", 1)
381 self.emit("return 1;", 1)
382 self.emit("}", 0)
383 self.emit("", 0)
384
385 def simpleSum(self, sum, name):
386 self.funcHeader(name)
387 for t in sum.types:
388 self.emit("if (PyObject_IsInstance(obj, (PyObject*)%s_type)) {" % t.name, 1)
389 self.emit("*out = %s;" % t.name, 2)
390 self.emit("return 0;", 2)
391 self.emit("}", 1)
392 self.sumTrailer(name)
393
394 def buildArgs(self, fields):
395 return ", ".join(fields + ["arena"])
396
397 def complexSum(self, sum, name):
398 self.funcHeader(name)
399 for a in sum.attributes:
400 self.visitAttributeDeclaration(a, name, sum=sum)
401 self.emit("", 0)
402 # XXX: should we only do this for 'expr'?
403 self.emit("if (obj == Py_None) {", 1)
404 self.emit("*out = NULL;", 2)
405 self.emit("return 0;", 2)
406 self.emit("}", 1)
407 for a in sum.attributes:
408 self.visitField(a, name, sum=sum, depth=1)
409 for t in sum.types:
410 self.emit("if (PyObject_IsInstance(obj, (PyObject*)%s_type)) {" % t.name, 1)
411 for f in t.fields:
412 self.visitFieldDeclaration(f, t.name, sum=sum, depth=2)
413 self.emit("", 0)
414 for f in t.fields:
415 self.visitField(f, t.name, sum=sum, depth=2)
416 args = [f.name.value for f in t.fields] + [a.name.value for a in sum.attributes]
417 self.emit("*out = %s(%s);" % (t.name, self.buildArgs(args)), 2)
418 self.emit("if (*out == NULL) goto failed;", 2)
419 self.emit("return 0;", 2)
420 self.emit("}", 1)
421 self.sumTrailer(name)
422
423 def visitAttributeDeclaration(self, a, name, sum=sum):
424 ctype = get_c_type(a.type)
425 self.emit("%s %s;" % (ctype, a.name), 1)
426
427 def visitSum(self, sum, name):
428 if is_simple(sum):
429 self.simpleSum(sum, name)
430 else:
431 self.complexSum(sum, name)
432
433 def visitProduct(self, prod, name):
434 ctype = get_c_type(name)
435 self.emit("int", 0)
436 self.emit("obj2ast_%s(PyObject* obj, %s* out, PyArena* arena)" % (name, ctype), 0)
437 self.emit("{", 0)
438 self.emit("PyObject* tmp = NULL;", 1)
439 for f in prod.fields:
440 self.visitFieldDeclaration(f, name, prod=prod, depth=1)
441 self.emit("", 0)
442 for f in prod.fields:
443 self.visitField(f, name, prod=prod, depth=1)
444 args = [f.name.value for f in prod.fields]
445 self.emit("*out = %s(%s);" % (name, self.buildArgs(args)), 1)
446 self.emit("return 0;", 1)
447 self.emit("failed:", 0)
448 self.emit("Py_XDECREF(tmp);", 1)
449 self.emit("return 1;", 1)
450 self.emit("}", 0)
451 self.emit("", 0)
452
453 def visitFieldDeclaration(self, field, name, sum=None, prod=None, depth=0):
454 ctype = get_c_type(field.type)
455 if field.seq:
456 if self.isSimpleType(field):
457 self.emit("asdl_int_seq* %s;" % field.name, depth)
458 else:
459 self.emit("asdl_seq* %s;" % field.name, depth)
460 else:
461 ctype = get_c_type(field.type)
462 self.emit("%s %s;" % (ctype, field.name), depth)
463
464 def isSimpleSum(self, field):
465 # XXX can the members of this list be determined automatically?
466 return field.type.value in ('expr_context', 'boolop', 'operator',
467 'unaryop', 'cmpop')
468
469 def isNumeric(self, field):
470 return get_c_type(field.type) in ("int", "bool")
471
472 def isSimpleType(self, field):
473 return self.isSimpleSum(field) or self.isNumeric(field)
474
475 def visitField(self, field, name, sum=None, prod=None, depth=0):
476 ctype = get_c_type(field.type)
477 self.emit("if (PyObject_HasAttrString(obj, \"%s\")) {" % field.name, depth)
478 self.emit("int res;", depth+1)
479 if field.seq:
480 self.emit("Py_ssize_t len;", depth+1)
481 self.emit("Py_ssize_t i;", depth+1)
482 self.emit("tmp = PyObject_GetAttrString(obj, \"%s\");" % field.name, depth+1)
483 self.emit("if (tmp == NULL) goto failed;", depth+1)
484 if field.seq:
485 self.emit("if (!PyList_Check(tmp)) {", depth+1)
486 self.emit("PyErr_Format(PyExc_TypeError, \"%s field \\\"%s\\\" must "
487 "be a list, not a %%.200s\", tmp->ob_type->tp_name);" %
488 (name, field.name),
489 depth+2, reflow=False)
490 self.emit("goto failed;", depth+2)
491 self.emit("}", depth+1)
492 self.emit("len = PyList_GET_SIZE(tmp);", depth+1)
493 if self.isSimpleType(field):
494 self.emit("%s = asdl_int_seq_new(len, arena);" % field.name, depth+1)
495 else:
496 self.emit("%s = asdl_seq_new(len, arena);" % field.name, depth+1)
497 self.emit("if (%s == NULL) goto failed;" % field.name, depth+1)
498 self.emit("for (i = 0; i < len; i++) {", depth+1)
499 self.emit("%s value;" % ctype, depth+2)
500 self.emit("res = obj2ast_%s(PyList_GET_ITEM(tmp, i), &value, arena);" %
501 field.type, depth+2, reflow=False)
502 self.emit("if (res != 0) goto failed;", depth+2)
503 self.emit("asdl_seq_SET(%s, i, value);" % field.name, depth+2)
504 self.emit("}", depth+1)
505 else:
506 self.emit("res = obj2ast_%s(tmp, &%s, arena);" %
507 (field.type, field.name), depth+1)
508 self.emit("if (res != 0) goto failed;", depth+1)
509
510 self.emit("Py_XDECREF(tmp);", depth+1)
511 self.emit("tmp = NULL;", depth+1)
512 self.emit("} else {", depth)
513 if not field.opt:
514 message = "required field \\\"%s\\\" missing from %s" % (field.name, name)
515 format = "PyErr_SetString(PyExc_TypeError, \"%s\");"
516 self.emit(format % message, depth+1, reflow=False)
517 self.emit("return 1;", depth+1)
518 else:
519 if self.isNumeric(field):
520 self.emit("%s = 0;" % field.name, depth+1)
521 elif not self.isSimpleType(field):
522 self.emit("%s = NULL;" % field.name, depth+1)
523 else:
524 raise TypeError("could not determine the default value for %s" % field.name)
525 self.emit("}", depth)
526
527
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000528class MarshalPrototypeVisitor(PickleVisitor):
529
530 def prototype(self, sum, name):
531 ctype = get_c_type(name)
Neal Norwitz6576bd82005-11-13 18:41:28 +0000532 self.emit("static int marshal_write_%s(PyObject **, int *, %s);"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000533 % (name, ctype), 0)
534
535 visitProduct = visitSum = prototype
536
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000537
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000538class PyTypesDeclareVisitor(PickleVisitor):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000539
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000540 def visitProduct(self, prod, name):
Neal Norwitz53d960c2006-02-28 22:47:29 +0000541 self.emit("static PyTypeObject *%s_type;" % name, 0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000542 self.emit("static PyObject* ast2obj_%s(void*);" % name, 0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000543 if prod.fields:
Neal Norwitz53d960c2006-02-28 22:47:29 +0000544 self.emit("static char *%s_fields[]={" % name,0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000545 for f in prod.fields:
546 self.emit('"%s",' % f.name, 1)
547 self.emit("};", 0)
Tim Peters710ab3b2006-02-28 18:30:36 +0000548
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000549 def visitSum(self, sum, name):
Neal Norwitz53d960c2006-02-28 22:47:29 +0000550 self.emit("static PyTypeObject *%s_type;" % name, 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000551 if sum.attributes:
Neal Norwitz53d960c2006-02-28 22:47:29 +0000552 self.emit("static char *%s_attributes[] = {" % name, 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000553 for a in sum.attributes:
554 self.emit('"%s",' % a.name, 1)
555 self.emit("};", 0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000556 ptype = "void*"
557 if is_simple(sum):
558 ptype = get_c_type(name)
559 tnames = []
560 for t in sum.types:
561 tnames.append(str(t.name)+"_singleton")
562 tnames = ", *".join(tnames)
563 self.emit("static PyObject *%s;" % tnames, 0)
564 self.emit("static PyObject* ast2obj_%s(%s);" % (name, ptype), 0)
565 for t in sum.types:
566 self.visitConstructor(t, name)
Tim Peters710ab3b2006-02-28 18:30:36 +0000567
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000568 def visitConstructor(self, cons, name):
Neal Norwitz53d960c2006-02-28 22:47:29 +0000569 self.emit("static PyTypeObject *%s_type;" % cons.name, 0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000570 if cons.fields:
Neal Norwitz53d960c2006-02-28 22:47:29 +0000571 self.emit("static char *%s_fields[]={" % cons.name, 0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000572 for t in cons.fields:
573 self.emit('"%s",' % t.name, 1)
574 self.emit("};",0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000575
576class PyTypesVisitor(PickleVisitor):
577
578 def visitModule(self, mod):
579 self.emit("""
Neal Norwitz207c9f32008-03-31 04:42:11 +0000580static int
581ast_type_init(PyObject *self, PyObject *args, PyObject *kw)
582{
583 Py_ssize_t i, numfields = 0;
584 int res = -1;
585 PyObject *key, *value, *fields;
586 fields = PyObject_GetAttrString((PyObject*)Py_TYPE(self), "_fields");
587 if (!fields)
588 PyErr_Clear();
589 if (fields) {
590 numfields = PySequence_Size(fields);
591 if (numfields == -1)
592 goto cleanup;
593 }
594 res = 0; /* if no error occurs, this stays 0 to the end */
595 if (PyTuple_GET_SIZE(args) > 0) {
596 if (numfields != PyTuple_GET_SIZE(args)) {
597 PyErr_Format(PyExc_TypeError, "%.400s constructor takes %s"
598 "%" PY_FORMAT_SIZE_T "d positional argument%s",
599 Py_TYPE(self)->tp_name,
600 numfields == 0 ? "" : "either 0 or ",
601 numfields, numfields == 1 ? "" : "s");
602 res = -1;
603 goto cleanup;
604 }
605 for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
606 /* cannot be reached when fields is NULL */
607 PyObject *name = PySequence_GetItem(fields, i);
608 if (!name) {
609 res = -1;
610 goto cleanup;
611 }
612 res = PyObject_SetAttr(self, name, PyTuple_GET_ITEM(args, i));
613 Py_DECREF(name);
614 if (res < 0)
615 goto cleanup;
616 }
617 }
618 if (kw) {
619 i = 0; /* needed by PyDict_Next */
620 while (PyDict_Next(kw, &i, &key, &value)) {
621 res = PyObject_SetAttr(self, key, value);
622 if (res < 0)
623 goto cleanup;
624 }
625 }
626 cleanup:
627 Py_XDECREF(fields);
628 return res;
629}
630
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000631/* Pickling support */
632static PyObject *
633ast_type_reduce(PyObject *self, PyObject *unused)
634{
635 PyObject *res;
636 PyObject *dict = PyObject_GetAttrString(self, "__dict__");
637 if (dict == NULL) {
638 if (PyErr_ExceptionMatches(PyExc_AttributeError))
639 PyErr_Clear();
640 else
641 return NULL;
642 }
643 if (dict) {
644 res = Py_BuildValue("O()O", Py_TYPE(self), dict);
645 Py_DECREF(dict);
646 return res;
647 }
648 return Py_BuildValue("O()", Py_TYPE(self));
649}
650
651static PyMethodDef ast_type_methods[] = {
652 {"__reduce__", ast_type_reduce, METH_NOARGS, NULL},
653 {NULL}
654};
655
Neal Norwitz207c9f32008-03-31 04:42:11 +0000656static PyTypeObject AST_type = {
657 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000658 "_ast.AST",
Neal Norwitz207c9f32008-03-31 04:42:11 +0000659 sizeof(PyObject),
660 0,
661 0, /* tp_dealloc */
662 0, /* tp_print */
663 0, /* tp_getattr */
664 0, /* tp_setattr */
665 0, /* tp_compare */
666 0, /* tp_repr */
667 0, /* tp_as_number */
668 0, /* tp_as_sequence */
669 0, /* tp_as_mapping */
670 0, /* tp_hash */
671 0, /* tp_call */
672 0, /* tp_str */
673 PyObject_GenericGetAttr, /* tp_getattro */
674 PyObject_GenericSetAttr, /* tp_setattro */
675 0, /* tp_as_buffer */
676 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
677 0, /* tp_doc */
678 0, /* tp_traverse */
679 0, /* tp_clear */
680 0, /* tp_richcompare */
681 0, /* tp_weaklistoffset */
682 0, /* tp_iter */
683 0, /* tp_iternext */
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000684 ast_type_methods, /* tp_methods */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000685 0, /* tp_members */
686 0, /* tp_getset */
687 0, /* tp_base */
688 0, /* tp_dict */
689 0, /* tp_descr_get */
690 0, /* tp_descr_set */
691 0, /* tp_dictoffset */
692 (initproc)ast_type_init, /* tp_init */
693 PyType_GenericAlloc, /* tp_alloc */
694 PyType_GenericNew, /* tp_new */
695 PyObject_Del, /* tp_free */
696};
697
698
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000699static PyTypeObject* make_type(char *type, PyTypeObject* base, char**fields, int num_fields)
700{
701 PyObject *fnames, *result;
702 int i;
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000703 fnames = PyTuple_New(num_fields);
704 if (!fnames) return NULL;
705 for (i = 0; i < num_fields; i++) {
Neal Norwitze4dc3242007-08-25 01:33:49 +0000706 PyObject *field = PyUnicode_FromString(fields[i]);
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000707 if (!field) {
708 Py_DECREF(fnames);
709 return NULL;
710 }
711 PyTuple_SET_ITEM(fnames, i, field);
712 }
Guido van Rossume845c0f2007-11-02 23:07:07 +0000713 result = PyObject_CallFunction((PyObject*)&PyType_Type, "U(O){sOss}",
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000714 type, base, "_fields", fnames, "__module__", "_ast");
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000715 Py_DECREF(fnames);
716 return (PyTypeObject*)result;
717}
718
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000719static int add_attributes(PyTypeObject* type, char**attrs, int num_fields)
720{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000721 int i, result;
Neal Norwitz207c9f32008-03-31 04:42:11 +0000722 PyObject *s, *l = PyTuple_New(num_fields);
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000723 if (!l) return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000724 for(i = 0; i < num_fields; i++) {
Neal Norwitze4dc3242007-08-25 01:33:49 +0000725 s = PyUnicode_FromString(attrs[i]);
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000726 if (!s) {
727 Py_DECREF(l);
728 return 0;
729 }
Neal Norwitz207c9f32008-03-31 04:42:11 +0000730 PyTuple_SET_ITEM(l, i, s);
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000731 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000732 result = PyObject_SetAttrString((PyObject*)type, "_attributes", l) >= 0;
733 Py_DECREF(l);
734 return result;
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000735}
736
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000737/* Conversion AST -> Python */
738
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000739static PyObject* ast2obj_list(asdl_seq *seq, PyObject* (*func)(void*))
740{
741 int i, n = asdl_seq_LEN(seq);
742 PyObject *result = PyList_New(n);
743 PyObject *value;
744 if (!result)
745 return NULL;
746 for (i = 0; i < n; i++) {
747 value = func(asdl_seq_GET(seq, i));
748 if (!value) {
749 Py_DECREF(result);
750 return NULL;
751 }
752 PyList_SET_ITEM(result, i, value);
753 }
754 return result;
755}
756
757static PyObject* ast2obj_object(void *o)
758{
759 if (!o)
760 o = Py_None;
761 Py_INCREF((PyObject*)o);
762 return (PyObject*)o;
763}
764#define ast2obj_identifier ast2obj_object
765#define ast2obj_string ast2obj_object
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000766
Thomas Woutersa44f3a32007-02-26 18:20:15 +0000767static PyObject* ast2obj_int(long b)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000768{
Christian Heimes2b1c5922007-12-02 22:43:00 +0000769 return PyLong_FromLong(b);
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000770}
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000771
772/* Conversion Python -> AST */
773
774static int obj2ast_object(PyObject* obj, PyObject** out, PyArena* arena)
775{
776 if (obj == Py_None)
777 obj = NULL;
778 if (obj)
779 PyArena_AddPyObject(arena, obj);
780 Py_XINCREF(obj);
781 *out = obj;
782 return 0;
783}
784
785#define obj2ast_identifier obj2ast_object
786#define obj2ast_string obj2ast_object
787
788static int obj2ast_int(PyObject* obj, int* out, PyArena* arena)
789{
790 int i;
791 if (!PyLong_Check(obj)) {
792 PyObject *s = PyObject_Repr(obj);
793 if (s == NULL) return 1;
794 PyErr_Format(PyExc_ValueError, "invalid integer value: %.400s",
Christian Heimes72b710a2008-05-26 13:28:38 +0000795 PyBytes_AS_STRING(s));
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000796 Py_DECREF(s);
797 return 1;
798 }
799
800 i = (int)PyLong_AsLong(obj);
801 if (i == -1 && PyErr_Occurred())
802 return 1;
803 *out = i;
804 return 0;
805}
806
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000807""", 0, reflow=False)
808
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000809 self.emit("static int init_types(void)",0)
810 self.emit("{", 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000811 self.emit("static int initialized;", 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000812 self.emit("if (initialized) return 1;", 1)
813 for dfn in mod.dfns:
814 self.visit(dfn)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000815 self.emit("initialized = 1;", 1)
816 self.emit("return 1;", 1);
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000817 self.emit("}", 0)
818
819 def visitProduct(self, prod, name):
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000820 if prod.fields:
821 fields = name.value+"_fields"
822 else:
823 fields = "NULL"
Neal Norwitz207c9f32008-03-31 04:42:11 +0000824 self.emit('%s_type = make_type("%s", &AST_type, %s, %d);' %
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000825 (name, name, fields, len(prod.fields)), 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000826 self.emit("if (!%s_type) return 0;" % name, 1)
Tim Peters710ab3b2006-02-28 18:30:36 +0000827
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000828 def visitSum(self, sum, name):
Neal Norwitz207c9f32008-03-31 04:42:11 +0000829 self.emit('%s_type = make_type("%s", &AST_type, NULL, 0);' %
830 (name, name), 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000831 self.emit("if (!%s_type) return 0;" % name, 1)
832 if sum.attributes:
Tim Peters710ab3b2006-02-28 18:30:36 +0000833 self.emit("if (!add_attributes(%s_type, %s_attributes, %d)) return 0;" %
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000834 (name, name, len(sum.attributes)), 1)
835 else:
836 self.emit("if (!add_attributes(%s_type, NULL, 0)) return 0;" % name, 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000837 simple = is_simple(sum)
838 for t in sum.types:
839 self.visitConstructor(t, name, simple)
Tim Peters710ab3b2006-02-28 18:30:36 +0000840
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000841 def visitConstructor(self, cons, name, simple):
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000842 if cons.fields:
843 fields = cons.name.value+"_fields"
844 else:
845 fields = "NULL"
Tim Peters710ab3b2006-02-28 18:30:36 +0000846 self.emit('%s_type = make_type("%s", %s_type, %s, %d);' %
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000847 (cons.name, cons.name, name, fields, len(cons.fields)), 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000848 self.emit("if (!%s_type) return 0;" % cons.name, 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000849 if simple:
850 self.emit("%s_singleton = PyType_GenericNew(%s_type, NULL, NULL);" %
851 (cons.name, cons.name), 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000852 self.emit("if (!%s_singleton) return 0;" % cons.name, 1)
Tim Peters710ab3b2006-02-28 18:30:36 +0000853
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000854
Thomas Wouterscf297e42007-02-23 15:07:44 +0000855def parse_version(mod):
856 return mod.version.value[12:-3]
857
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000858class ASTModuleVisitor(PickleVisitor):
859
860 def visitModule(self, mod):
Martin v. Löwis1a214512008-06-11 05:26:20 +0000861 self.emit("static struct PyModuleDef _astmodule = {", 0)
862 self.emit(' PyModuleDef_HEAD_INIT, "_ast"', 0)
863 self.emit("};", 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000864 self.emit("PyMODINIT_FUNC", 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000865 self.emit("PyInit__ast(void)", 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000866 self.emit("{", 0)
867 self.emit("PyObject *m, *d;", 1)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000868 self.emit("if (!init_types()) return NULL;", 1)
869 self.emit('m = PyModule_Create(&_astmodule);', 1)
870 self.emit("if (!m) return NULL;", 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000871 self.emit("d = PyModule_GetDict(m);", 1)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000872 self.emit('if (PyDict_SetItemString(d, "AST", (PyObject*)&AST_type) < 0) return NULL;', 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000873 self.emit('if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0)', 1)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000874 self.emit("return NULL;", 2)
Martin v. Löwis40d84592006-02-28 00:30:54 +0000875 # Value of version: "$Revision$"
Thomas Wouterscf297e42007-02-23 15:07:44 +0000876 self.emit('if (PyModule_AddStringConstant(m, "__version__", "%s") < 0)'
877 % parse_version(mod), 1)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000878 self.emit("return NULL;", 2)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000879 for dfn in mod.dfns:
880 self.visit(dfn)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000881 self.emit("return m;", 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000882 self.emit("}", 0)
883
884 def visitProduct(self, prod, name):
885 self.addObj(name)
Tim Peters710ab3b2006-02-28 18:30:36 +0000886
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000887 def visitSum(self, sum, name):
888 self.addObj(name)
889 for t in sum.types:
890 self.visitConstructor(t, name)
Tim Peters710ab3b2006-02-28 18:30:36 +0000891
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000892 def visitConstructor(self, cons, name):
893 self.addObj(cons.name)
Tim Peters710ab3b2006-02-28 18:30:36 +0000894
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000895 def addObj(self, name):
Martin v. Löwis1a214512008-06-11 05:26:20 +0000896 self.emit('if (PyDict_SetItemString(d, "%s", (PyObject*)%s_type) < 0) return NULL;' % (name, name), 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000897
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000898
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000899_SPECIALIZED_SEQUENCES = ('stmt', 'expr')
900
901def find_sequence(fields, doing_specialization):
902 """Return True if any field uses a sequence."""
903 for f in fields:
904 if f.seq:
905 if not doing_specialization:
906 return True
907 if str(f.type) not in _SPECIALIZED_SEQUENCES:
908 return True
909 return False
910
911def has_sequence(types, doing_specialization):
912 for t in types:
913 if find_sequence(t.fields, doing_specialization):
914 return True
915 return False
916
917
918class StaticVisitor(PickleVisitor):
Neal Norwitz7b5a6042005-11-13 19:14:20 +0000919 CODE = '''Very simple, always emit this static code. Overide CODE'''
920
921 def visit(self, object):
922 self.emit(self.CODE, 0, reflow=False)
923
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000924
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000925class ObjVisitor(PickleVisitor):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000926
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000927 def func_begin(self, name):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000928 ctype = get_c_type(name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000929 self.emit("PyObject*", 0)
930 self.emit("ast2obj_%s(void* _o)" % (name), 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000931 self.emit("{", 0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000932 self.emit("%s o = (%s)_o;" % (ctype, ctype), 1)
933 self.emit("PyObject *result = NULL, *value = NULL;", 1)
934 self.emit('if (!o) {', 1)
935 self.emit("Py_INCREF(Py_None);", 2)
936 self.emit('return Py_None;', 2)
937 self.emit("}", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000938 self.emit('', 0)
939
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000940 def func_end(self):
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000941 self.emit("return result;", 1)
942 self.emit("failed:", 0)
943 self.emit("Py_XDECREF(value);", 1)
944 self.emit("Py_XDECREF(result);", 1)
945 self.emit("return NULL;", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000946 self.emit("}", 0)
947 self.emit("", 0)
948
949 def visitSum(self, sum, name):
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000950 if is_simple(sum):
951 self.simpleSum(sum, name)
952 return
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000953 self.func_begin(name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000954 self.emit("switch (o->kind) {", 1)
955 for i in range(len(sum.types)):
956 t = sum.types[i]
957 self.visitConstructor(t, i + 1, name)
958 self.emit("}", 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000959 for a in sum.attributes:
960 self.emit("value = ast2obj_%s(o->%s);" % (a.type, a.name), 1)
961 self.emit("if (!value) goto failed;", 1)
Martin v. Löwis03e5bc02006-03-02 00:31:27 +0000962 self.emit('if (PyObject_SetAttrString(result, "%s", value) < 0)' % a.name, 1)
963 self.emit('goto failed;', 2)
964 self.emit('Py_DECREF(value);', 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000965 self.func_end()
Tim Peters710ab3b2006-02-28 18:30:36 +0000966
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000967 def simpleSum(self, sum, name):
968 self.emit("PyObject* ast2obj_%s(%s_ty o)" % (name, name), 0)
969 self.emit("{", 0)
970 self.emit("switch(o) {", 1)
971 for t in sum.types:
972 self.emit("case %s:" % t.name, 2)
973 self.emit("Py_INCREF(%s_singleton);" % t.name, 3)
974 self.emit("return %s_singleton;" % t.name, 3)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000975 self.emit("default:" % name, 2)
976 self.emit('/* should never happen, but just in case ... */', 3)
977 code = "PyErr_Format(PyExc_SystemError, \"unknown %s found\");" % name
978 self.emit(code, 3, reflow=False)
979 self.emit("return NULL;", 3)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000980 self.emit("}", 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000981 self.emit("}", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000982
983 def visitProduct(self, prod, name):
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000984 self.func_begin(name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000985 self.emit("result = PyType_GenericNew(%s_type, NULL, NULL);" % name, 1);
986 self.emit("if (!result) return NULL;", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000987 for field in prod.fields:
988 self.visitField(field, name, 1, True)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000989 self.func_end()
Tim Peters536cf992005-12-25 23:18:31 +0000990
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000991 def visitConstructor(self, cons, enum, name):
992 self.emit("case %s_kind:" % cons.name, 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000993 self.emit("result = PyType_GenericNew(%s_type, NULL, NULL);" % cons.name, 2);
994 self.emit("if (!result) goto failed;", 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000995 for f in cons.fields:
996 self.visitField(f, cons.name, 2, False)
997 self.emit("break;", 2)
998
999 def visitField(self, field, name, depth, product):
1000 def emit(s, d):
1001 self.emit(s, depth + d)
1002 if product:
1003 value = "o->%s" % field.name
1004 else:
1005 value = "o->v.%s.%s" % (name, field.name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001006 self.set(field, value, depth)
1007 emit("if (!value) goto failed;", 0)
1008 emit('if (PyObject_SetAttrString(result, "%s", value) == -1)' % field.name, 0)
1009 emit("goto failed;", 1)
1010 emit("Py_DECREF(value);", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001011
1012 def emitSeq(self, field, value, depth, emit):
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001013 emit("seq = %s;" % value, 0)
1014 emit("n = asdl_seq_LEN(seq);", 0)
1015 emit("value = PyList_New(n);", 0)
1016 emit("if (!value) goto failed;", 0)
1017 emit("for (i = 0; i < n; i++) {", 0)
1018 self.set("value", field, "asdl_seq_GET(seq, i)", depth + 1)
1019 emit("if (!value1) goto failed;", 1)
1020 emit("PyList_SET_ITEM(value, i, value1);", 1)
1021 emit("value1 = NULL;", 1)
1022 emit("}", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001023
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001024 def set(self, field, value, depth):
1025 if field.seq:
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001026 # XXX should really check for is_simple, but that requires a symbol table
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001027 if field.type.value == "cmpop":
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001028 # While the sequence elements are stored as void*,
1029 # ast2obj_cmpop expects an enum
1030 self.emit("{", depth)
1031 self.emit("int i, n = asdl_seq_LEN(%s);" % value, depth+1)
1032 self.emit("value = PyList_New(n);", depth+1)
1033 self.emit("if (!value) goto failed;", depth+1)
1034 self.emit("for(i = 0; i < n; i++)", depth+1)
1035 # This cannot fail, so no need for error handling
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001036 self.emit("PyList_SET_ITEM(value, i, ast2obj_cmpop((cmpop_ty)asdl_seq_GET(%s, i)));" % value,
1037 depth+2, reflow=False)
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001038 self.emit("}", depth)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001039 else:
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001040 self.emit("value = ast2obj_list(%s, ast2obj_%s);" % (value, field.type), depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001041 else:
1042 ctype = get_c_type(field.type)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001043 self.emit("value = ast2obj_%s(%s);" % (field.type, value), depth, reflow=False)
Tim Peters536cf992005-12-25 23:18:31 +00001044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001045
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001046class PartingShots(StaticVisitor):
1047
1048 CODE = """
1049PyObject* PyAST_mod2obj(mod_ty t)
1050{
1051 init_types();
1052 return ast2obj_mod(t);
1053}
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001054
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001055/* mode is 0 for "exec", 1 for "eval" and 2 for "single" input */
1056mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001057{
1058 mod_ty res;
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001059 PyObject *req_type[] = {(PyObject*)Module_type, (PyObject*)Expression_type,
1060 (PyObject*)Interactive_type};
1061 char *req_name[] = {"Module", "Expression", "Interactive"};
1062 assert(0 <= mode && mode <= 2);
1063
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001064 init_types();
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001065
1066 if (!PyObject_IsInstance(ast, req_type[mode])) {
1067 PyErr_Format(PyExc_TypeError, "expected %s node, got %.400s",
1068 req_name[mode], Py_TYPE(ast)->tp_name);
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001069 return NULL;
1070 }
1071 if (obj2ast_mod(ast, &res, arena) != 0)
1072 return NULL;
1073 else
1074 return res;
1075}
1076
1077int PyAST_Check(PyObject* obj)
1078{
1079 init_types();
Neal Norwitz207c9f32008-03-31 04:42:11 +00001080 return PyObject_IsInstance(obj, (PyObject*)&AST_type);
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001081}
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001082"""
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001083
1084class ChainOfVisitors:
1085 def __init__(self, *visitors):
1086 self.visitors = visitors
1087
1088 def visit(self, object):
1089 for v in self.visitors:
1090 v.visit(object)
Neal Norwitz7b5a6042005-11-13 19:14:20 +00001091 v.emit("", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001092
Guido van Rossum805365e2007-05-07 22:24:25 +00001093common_msg = "/* File automatically generated by %s. */\n\n"
Thomas Wouterscf297e42007-02-23 15:07:44 +00001094
1095c_file_msg = """
1096/*
1097 __version__ %s.
1098
1099 This module must be committed separately after each AST grammar change;
1100 The __version__ number is set to the revision number of the commit
1101 containing the grammar change.
1102*/
Guido van Rossum805365e2007-05-07 22:24:25 +00001103
Thomas Wouterscf297e42007-02-23 15:07:44 +00001104"""
1105
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001106def main(srcfile):
Neal Norwitz897ff812005-12-11 21:18:22 +00001107 argv0 = sys.argv[0]
Armin Rigo6b1793f2005-12-14 18:05:14 +00001108 components = argv0.split(os.sep)
1109 argv0 = os.sep.join(components[-2:])
Thomas Wouterscf297e42007-02-23 15:07:44 +00001110 auto_gen_msg = common_msg % argv0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001111 mod = asdl.parse(srcfile)
1112 if not asdl.check(mod):
1113 sys.exit(1)
1114 if INC_DIR:
1115 p = "%s/%s-ast.h" % (INC_DIR, mod.name)
Guido van Rossum2af1d892007-11-23 21:26:49 +00001116 f = open(p, "w")
Guido van Rossum805365e2007-05-07 22:24:25 +00001117 f.write(auto_gen_msg)
1118 f.write('#include "asdl.h"\n\n')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001119 c = ChainOfVisitors(TypeDefVisitor(f),
1120 StructVisitor(f),
1121 PrototypeVisitor(f),
1122 )
1123 c.visit(mod)
Guido van Rossum805365e2007-05-07 22:24:25 +00001124 f.write("PyObject* PyAST_mod2obj(mod_ty t);\n")
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001125 f.write("mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode);\n")
1126 f.write("int PyAST_Check(PyObject* obj);\n")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001127 f.close()
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001128
1129 if SRC_DIR:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001130 p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c")
Guido van Rossum2af1d892007-11-23 21:26:49 +00001131 f = open(p, "w")
Guido van Rossum805365e2007-05-07 22:24:25 +00001132 f.write(auto_gen_msg)
1133 f.write(c_file_msg % parse_version(mod))
1134 f.write('#include "Python.h"\n')
1135 f.write('#include "%s-ast.h"\n' % mod.name)
1136 f.write('\n')
Neal Norwitz207c9f32008-03-31 04:42:11 +00001137 f.write("static PyTypeObject AST_type;\n")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001138 v = ChainOfVisitors(
1139 PyTypesDeclareVisitor(f),
1140 PyTypesVisitor(f),
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001141 Obj2ModPrototypeVisitor(f),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001142 FunctionVisitor(f),
1143 ObjVisitor(f),
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001144 Obj2ModVisitor(f),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001145 ASTModuleVisitor(f),
1146 PartingShots(f),
1147 )
1148 v.visit(mod)
1149 f.close()
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150
1151if __name__ == "__main__":
1152 import sys
1153 import getopt
1154
1155 INC_DIR = ''
1156 SRC_DIR = ''
1157 opts, args = getopt.getopt(sys.argv[1:], "h:c:")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001158 if len(opts) != 1:
Guido van Rossum805365e2007-05-07 22:24:25 +00001159 sys.stdout.write("Must specify exactly one output file\n")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001160 sys.exit(1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161 for o, v in opts:
1162 if o == '-h':
1163 INC_DIR = v
1164 if o == '-c':
1165 SRC_DIR = v
1166 if len(args) != 1:
Guido van Rossum805365e2007-05-07 22:24:25 +00001167 sys.stdout.write("Must specify single input file\n")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001168 sys.exit(1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001169 main(args[0])