Added section on passing contextual information to logging and documentation for...
[python.git] / Parser / asdl_c.py
blob4877853deaba7ba962d3aa0bd9dec5934bb9445e
1 #! /usr/bin/env python
2 """Generate C code from an ASDL description."""
4 # TO DO
5 # handle fields that have a type but no name
7 import os, sys, traceback
9 import asdl
11 TABSIZE = 8
12 MAX_COL = 80
14 def get_c_type(name):
15 """Return a string for the C name of the type.
17 This function special cases the default types provided by asdl:
18 identifier, string, int, bool.
19 """
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
28 def reflow_lines(s, depth):
29 """Reflow the line s indented depth tabs.
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]
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
50 assert i != -1, "Impossible line %d to reflow: %r" % (size, s)
51 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
70 def is_simple(sum):
71 """Return True if a sum is a simple.
73 A sum is simple if its types have no fields, e.g.
74 unaryop = Invert | Not | UAdd | USub
75 """
77 for t in sum.types:
78 if t.fields:
79 return False
80 return True
82 class EmitVisitor(asdl.VisitorBase):
83 """Visit that emits lines"""
85 def __init__(self, file):
86 self.file = file
87 super(EmitVisitor, self).__init__()
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)
99 class TypeDefVisitor(EmitVisitor):
100 def visitModule(self, mod):
101 for dfn in mod.dfns:
102 self.visit(dfn)
104 def visitType(self, type, depth=0):
105 self.visit(type.value, type.name, depth)
107 def visitSum(self, sum, name, depth):
108 if is_simple(sum):
109 self.simple_sum(sum, name, depth)
110 else:
111 self.sum_with_constructors(sum, name, depth)
113 def simple_sum(self, sum, name, depth):
114 enum = []
115 for i in range(len(sum.types)):
116 type = sum.types[i]
117 enum.append("%s=%d" % (type.name, i + 1))
118 enums = ", ".join(enum)
119 ctype = get_c_type(name)
120 s = "typedef enum _%s { %s } %s;" % (name, enums, ctype)
121 self.emit(s, depth)
122 self.emit("", depth)
124 def sum_with_constructors(self, sum, name, depth):
125 ctype = get_c_type(name)
126 s = "typedef struct _%(name)s *%(ctype)s;" % locals()
127 self.emit(s, depth)
128 self.emit("", depth)
130 def visitProduct(self, product, name, depth):
131 ctype = get_c_type(name)
132 s = "typedef struct _%(name)s *%(ctype)s;" % locals()
133 self.emit(s, depth)
134 self.emit("", depth)
136 class StructVisitor(EmitVisitor):
137 """Visitor to generate typdefs for AST."""
139 def visitModule(self, mod):
140 for dfn in mod.dfns:
141 self.visit(dfn)
143 def visitType(self, type, depth=0):
144 self.visit(type.value, type.name, depth)
146 def visitSum(self, sum, name, depth):
147 if not is_simple(sum):
148 self.sum_with_constructors(sum, name, depth)
150 def sum_with_constructors(self, sum, name, depth):
151 def emit(s, depth=depth):
152 self.emit(s % sys._getframe(1).f_locals, depth)
153 enum = []
154 for i in range(len(sum.types)):
155 type = sum.types[i]
156 enum.append("%s_kind=%d" % (type.name, i + 1))
158 emit("enum _%(name)s_kind {" + ", ".join(enum) + "};")
160 emit("struct _%(name)s {")
161 emit("enum _%(name)s_kind kind;", depth + 1)
162 emit("union {", depth + 1)
163 for t in sum.types:
164 self.visit(t, depth + 2)
165 emit("} v;", depth + 1)
166 for field in sum.attributes:
167 # rudimentary attribute handling
168 type = str(field.type)
169 assert type in asdl.builtin_types, type
170 emit("%s %s;" % (type, field.name), depth + 1);
171 emit("};")
172 emit("")
174 def visitConstructor(self, cons, depth):
175 if cons.fields:
176 self.emit("struct {", depth)
177 for f in cons.fields:
178 self.visit(f, depth + 1)
179 self.emit("} %s;" % cons.name, depth)
180 self.emit("", depth)
181 else:
182 # XXX not sure what I want here, nothing is probably fine
183 pass
185 def visitField(self, field, depth):
186 # XXX need to lookup field.type, because it might be something
187 # like a builtin...
188 ctype = get_c_type(field.type)
189 name = field.name
190 if field.seq:
191 if field.type.value in ('cmpop',):
192 self.emit("asdl_int_seq *%(name)s;" % locals(), depth)
193 else:
194 self.emit("asdl_seq *%(name)s;" % locals(), depth)
195 else:
196 self.emit("%(ctype)s %(name)s;" % locals(), depth)
198 def visitProduct(self, product, name, depth):
199 self.emit("struct _%(name)s {" % locals(), depth)
200 for f in product.fields:
201 self.visit(f, depth + 1)
202 self.emit("};", depth)
203 self.emit("", depth)
205 class PrototypeVisitor(EmitVisitor):
206 """Generate function prototypes for the .h file"""
208 def visitModule(self, mod):
209 for dfn in mod.dfns:
210 self.visit(dfn)
212 def visitType(self, type):
213 self.visit(type.value, type.name)
215 def visitSum(self, sum, name):
216 if is_simple(sum):
217 pass # XXX
218 else:
219 for t in sum.types:
220 self.visit(t, name, sum.attributes)
222 def get_args(self, fields):
223 """Return list of C argument into, one for each field.
225 Argument info is 3-tuple of a C type, variable name, and flag
226 that is true if type can be NULL.
228 args = []
229 unnamed = {}
230 for f in fields:
231 if f.name is None:
232 name = f.type
233 c = unnamed[name] = unnamed.get(name, 0) + 1
234 if c > 1:
235 name = "name%d" % (c - 1)
236 else:
237 name = f.name
238 # XXX should extend get_c_type() to handle this
239 if f.seq:
240 if f.type.value in ('cmpop',):
241 ctype = "asdl_int_seq *"
242 else:
243 ctype = "asdl_seq *"
244 else:
245 ctype = get_c_type(f.type)
246 args.append((ctype, name, f.opt or f.seq))
247 return args
249 def visitConstructor(self, cons, type, attrs):
250 args = self.get_args(cons.fields)
251 attrs = self.get_args(attrs)
252 ctype = get_c_type(type)
253 self.emit_function(cons.name, ctype, args, attrs)
255 def emit_function(self, name, ctype, args, attrs, union=1):
256 args = args + attrs
257 if args:
258 argstr = ", ".join(["%s %s" % (atype, aname)
259 for atype, aname, opt in args])
260 argstr += ", PyArena *arena"
261 else:
262 argstr = "PyArena *arena"
263 margs = "a0"
264 for i in range(1, len(args)+1):
265 margs += ", a%d" % i
266 self.emit("#define %s(%s) _Py_%s(%s)" % (name, margs, name, margs), 0,
267 reflow = 0)
268 self.emit("%s _Py_%s(%s);" % (ctype, name, argstr), 0)
270 def visitProduct(self, prod, name):
271 self.emit_function(name, get_c_type(name),
272 self.get_args(prod.fields), [], union=0)
274 class FunctionVisitor(PrototypeVisitor):
275 """Visitor to generate constructor functions for AST."""
277 def emit_function(self, name, ctype, args, attrs, union=1):
278 def emit(s, depth=0, reflow=1):
279 self.emit(s, depth, reflow)
280 argstr = ", ".join(["%s %s" % (atype, aname)
281 for atype, aname, opt in args + attrs])
282 if argstr:
283 argstr += ", PyArena *arena"
284 else:
285 argstr = "PyArena *arena"
286 self.emit("%s" % ctype, 0)
287 emit("%s(%s)" % (name, argstr))
288 emit("{")
289 emit("%s p;" % ctype, 1)
290 for argtype, argname, opt in args:
291 # XXX hack alert: false is allowed for a bool
292 if not opt and not (argtype == "bool" or argtype == "int"):
293 emit("if (!%s) {" % argname, 1)
294 emit("PyErr_SetString(PyExc_ValueError,", 2)
295 msg = "field %s is required for %s" % (argname, name)
296 emit(' "%s");' % msg,
297 2, reflow=0)
298 emit('return NULL;', 2)
299 emit('}', 1)
301 emit("p = (%s)PyArena_Malloc(arena, sizeof(*p));" % ctype, 1);
302 emit("if (!p)", 1)
303 emit("return NULL;", 2)
304 if union:
305 self.emit_body_union(name, args, attrs)
306 else:
307 self.emit_body_struct(name, args, attrs)
308 emit("return p;", 1)
309 emit("}")
310 emit("")
312 def emit_body_union(self, name, args, attrs):
313 def emit(s, depth=0, reflow=1):
314 self.emit(s, depth, reflow)
315 emit("p->kind = %s_kind;" % name, 1)
316 for argtype, argname, opt in args:
317 emit("p->v.%s.%s = %s;" % (name, argname, argname), 1)
318 for argtype, argname, opt in attrs:
319 emit("p->%s = %s;" % (argname, argname), 1)
321 def emit_body_struct(self, name, args, attrs):
322 def emit(s, depth=0, reflow=1):
323 self.emit(s, depth, reflow)
324 for argtype, argname, opt in args:
325 emit("p->%s = %s;" % (argname, argname), 1)
326 assert not attrs
328 class PickleVisitor(EmitVisitor):
330 def visitModule(self, mod):
331 for dfn in mod.dfns:
332 self.visit(dfn)
334 def visitType(self, type):
335 self.visit(type.value, type.name)
337 def visitSum(self, sum, name):
338 pass
340 def visitProduct(self, sum, name):
341 pass
343 def visitConstructor(self, cons, name):
344 pass
346 def visitField(self, sum):
347 pass
349 class MarshalPrototypeVisitor(PickleVisitor):
351 def prototype(self, sum, name):
352 ctype = get_c_type(name)
353 self.emit("static int marshal_write_%s(PyObject **, int *, %s);"
354 % (name, ctype), 0)
356 visitProduct = visitSum = prototype
358 class PyTypesDeclareVisitor(PickleVisitor):
360 def visitProduct(self, prod, name):
361 self.emit("static PyTypeObject *%s_type;" % name, 0)
362 self.emit("static PyObject* ast2obj_%s(void*);" % name, 0)
363 if prod.fields:
364 self.emit("static char *%s_fields[]={" % name,0)
365 for f in prod.fields:
366 self.emit('"%s",' % f.name, 1)
367 self.emit("};", 0)
369 def visitSum(self, sum, name):
370 self.emit("static PyTypeObject *%s_type;" % name, 0)
371 if sum.attributes:
372 self.emit("static char *%s_attributes[] = {" % name, 0)
373 for a in sum.attributes:
374 self.emit('"%s",' % a.name, 1)
375 self.emit("};", 0)
376 ptype = "void*"
377 if is_simple(sum):
378 ptype = get_c_type(name)
379 tnames = []
380 for t in sum.types:
381 tnames.append(str(t.name)+"_singleton")
382 tnames = ", *".join(tnames)
383 self.emit("static PyObject *%s;" % tnames, 0)
384 self.emit("static PyObject* ast2obj_%s(%s);" % (name, ptype), 0)
385 for t in sum.types:
386 self.visitConstructor(t, name)
388 def visitConstructor(self, cons, name):
389 self.emit("static PyTypeObject *%s_type;" % cons.name, 0)
390 if cons.fields:
391 self.emit("static char *%s_fields[]={" % cons.name, 0)
392 for t in cons.fields:
393 self.emit('"%s",' % t.name, 1)
394 self.emit("};",0)
396 class PyTypesVisitor(PickleVisitor):
398 def visitModule(self, mod):
399 self.emit("""
400 static PyTypeObject* make_type(char *type, PyTypeObject* base, char**fields, int num_fields)
402 PyObject *fnames, *result;
403 int i;
404 if (num_fields) {
405 fnames = PyTuple_New(num_fields);
406 if (!fnames) return NULL;
407 } else {
408 fnames = Py_None;
409 Py_INCREF(Py_None);
411 for(i=0; i < num_fields; i++) {
412 PyObject *field = PyString_FromString(fields[i]);
413 if (!field) {
414 Py_DECREF(fnames);
415 return NULL;
417 PyTuple_SET_ITEM(fnames, i, field);
419 result = PyObject_CallFunction((PyObject*)&PyType_Type, "s(O){sOss}",
420 type, base, "_fields", fnames, "__module__", "_ast");
421 Py_DECREF(fnames);
422 return (PyTypeObject*)result;
425 static int add_attributes(PyTypeObject* type, char**attrs, int num_fields)
427 int i, result;
428 PyObject *s, *l = PyList_New(num_fields);
429 if (!l) return 0;
430 for(i = 0; i < num_fields; i++) {
431 s = PyString_FromString(attrs[i]);
432 if (!s) {
433 Py_DECREF(l);
434 return 0;
436 PyList_SET_ITEM(l, i, s);
438 result = PyObject_SetAttrString((PyObject*)type, "_attributes", l) >= 0;
439 Py_DECREF(l);
440 return result;
443 static PyObject* ast2obj_list(asdl_seq *seq, PyObject* (*func)(void*))
445 int i, n = asdl_seq_LEN(seq);
446 PyObject *result = PyList_New(n);
447 PyObject *value;
448 if (!result)
449 return NULL;
450 for (i = 0; i < n; i++) {
451 value = func(asdl_seq_GET(seq, i));
452 if (!value) {
453 Py_DECREF(result);
454 return NULL;
456 PyList_SET_ITEM(result, i, value);
458 return result;
461 static PyObject* ast2obj_object(void *o)
463 if (!o)
464 o = Py_None;
465 Py_INCREF((PyObject*)o);
466 return (PyObject*)o;
468 #define ast2obj_identifier ast2obj_object
469 #define ast2obj_string ast2obj_object
470 static PyObject* ast2obj_bool(bool b)
472 return PyBool_FromLong(b);
475 static PyObject* ast2obj_int(long b)
477 return PyInt_FromLong(b);
479 """, 0, reflow=False)
481 self.emit("static int init_types(void)",0)
482 self.emit("{", 0)
483 self.emit("static int initialized;", 1)
484 self.emit("if (initialized) return 1;", 1)
485 self.emit('AST_type = make_type("AST", &PyBaseObject_Type, NULL, 0);', 1)
486 for dfn in mod.dfns:
487 self.visit(dfn)
488 self.emit("initialized = 1;", 1)
489 self.emit("return 1;", 1);
490 self.emit("}", 0)
492 def visitProduct(self, prod, name):
493 if prod.fields:
494 fields = name.value+"_fields"
495 else:
496 fields = "NULL"
497 self.emit('%s_type = make_type("%s", AST_type, %s, %d);' %
498 (name, name, fields, len(prod.fields)), 1)
499 self.emit("if (!%s_type) return 0;" % name, 1)
501 def visitSum(self, sum, name):
502 self.emit('%s_type = make_type("%s", AST_type, NULL, 0);' % (name, name), 1)
503 self.emit("if (!%s_type) return 0;" % name, 1)
504 if sum.attributes:
505 self.emit("if (!add_attributes(%s_type, %s_attributes, %d)) return 0;" %
506 (name, name, len(sum.attributes)), 1)
507 else:
508 self.emit("if (!add_attributes(%s_type, NULL, 0)) return 0;" % name, 1)
509 simple = is_simple(sum)
510 for t in sum.types:
511 self.visitConstructor(t, name, simple)
513 def visitConstructor(self, cons, name, simple):
514 if cons.fields:
515 fields = cons.name.value+"_fields"
516 else:
517 fields = "NULL"
518 self.emit('%s_type = make_type("%s", %s_type, %s, %d);' %
519 (cons.name, cons.name, name, fields, len(cons.fields)), 1)
520 self.emit("if (!%s_type) return 0;" % cons.name, 1)
521 if simple:
522 self.emit("%s_singleton = PyType_GenericNew(%s_type, NULL, NULL);" %
523 (cons.name, cons.name), 1)
524 self.emit("if (!%s_singleton) return 0;" % cons.name, 1)
526 def parse_version(mod):
527 return mod.version.value[12:-3]
529 class ASTModuleVisitor(PickleVisitor):
531 def visitModule(self, mod):
532 self.emit("PyMODINIT_FUNC", 0)
533 self.emit("init_ast(void)", 0)
534 self.emit("{", 0)
535 self.emit("PyObject *m, *d;", 1)
536 self.emit("if (!init_types()) return;", 1)
537 self.emit('m = Py_InitModule3("_ast", NULL, NULL);', 1)
538 self.emit("if (!m) return;", 1)
539 self.emit("d = PyModule_GetDict(m);", 1)
540 self.emit('if (PyDict_SetItemString(d, "AST", (PyObject*)AST_type) < 0) return;', 1)
541 self.emit('if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0)', 1)
542 self.emit("return;", 2)
543 # Value of version: "$Revision$"
544 self.emit('if (PyModule_AddStringConstant(m, "__version__", "%s") < 0)'
545 % parse_version(mod), 1)
546 self.emit("return;", 2)
547 for dfn in mod.dfns:
548 self.visit(dfn)
549 self.emit("}", 0)
551 def visitProduct(self, prod, name):
552 self.addObj(name)
554 def visitSum(self, sum, name):
555 self.addObj(name)
556 for t in sum.types:
557 self.visitConstructor(t, name)
559 def visitConstructor(self, cons, name):
560 self.addObj(cons.name)
562 def addObj(self, name):
563 self.emit('if (PyDict_SetItemString(d, "%s", (PyObject*)%s_type) < 0) return;' % (name, name), 1)
565 _SPECIALIZED_SEQUENCES = ('stmt', 'expr')
567 def find_sequence(fields, doing_specialization):
568 """Return True if any field uses a sequence."""
569 for f in fields:
570 if f.seq:
571 if not doing_specialization:
572 return True
573 if str(f.type) not in _SPECIALIZED_SEQUENCES:
574 return True
575 return False
577 def has_sequence(types, doing_specialization):
578 for t in types:
579 if find_sequence(t.fields, doing_specialization):
580 return True
581 return False
584 class StaticVisitor(PickleVisitor):
585 CODE = '''Very simple, always emit this static code. Overide CODE'''
587 def visit(self, object):
588 self.emit(self.CODE, 0, reflow=False)
590 class ObjVisitor(PickleVisitor):
592 def func_begin(self, name):
593 ctype = get_c_type(name)
594 self.emit("PyObject*", 0)
595 self.emit("ast2obj_%s(void* _o)" % (name), 0)
596 self.emit("{", 0)
597 self.emit("%s o = (%s)_o;" % (ctype, ctype), 1)
598 self.emit("PyObject *result = NULL, *value = NULL;", 1)
599 self.emit('if (!o) {', 1)
600 self.emit("Py_INCREF(Py_None);", 2)
601 self.emit('return Py_None;', 2)
602 self.emit("}", 1)
603 self.emit('', 0)
605 def func_end(self):
606 self.emit("return result;", 1)
607 self.emit("failed:", 0)
608 self.emit("Py_XDECREF(value);", 1)
609 self.emit("Py_XDECREF(result);", 1)
610 self.emit("return NULL;", 1)
611 self.emit("}", 0)
612 self.emit("", 0)
614 def visitSum(self, sum, name):
615 if is_simple(sum):
616 self.simpleSum(sum, name)
617 return
618 self.func_begin(name)
619 self.emit("switch (o->kind) {", 1)
620 for i in range(len(sum.types)):
621 t = sum.types[i]
622 self.visitConstructor(t, i + 1, name)
623 self.emit("}", 1)
624 for a in sum.attributes:
625 self.emit("value = ast2obj_%s(o->%s);" % (a.type, a.name), 1)
626 self.emit("if (!value) goto failed;", 1)
627 self.emit('if (PyObject_SetAttrString(result, "%s", value) < 0)' % a.name, 1)
628 self.emit('goto failed;', 2)
629 self.emit('Py_DECREF(value);', 1)
630 self.func_end()
632 def simpleSum(self, sum, name):
633 self.emit("PyObject* ast2obj_%s(%s_ty o)" % (name, name), 0)
634 self.emit("{", 0)
635 self.emit("switch(o) {", 1)
636 for t in sum.types:
637 self.emit("case %s:" % t.name, 2)
638 self.emit("Py_INCREF(%s_singleton);" % t.name, 3)
639 self.emit("return %s_singleton;" % t.name, 3)
640 self.emit("}", 1)
641 self.emit("return NULL; /* cannot happen */", 1)
642 self.emit("}", 0)
644 def visitProduct(self, prod, name):
645 self.func_begin(name)
646 self.emit("result = PyType_GenericNew(%s_type, NULL, NULL);" % name, 1);
647 self.emit("if (!result) return NULL;", 1)
648 for field in prod.fields:
649 self.visitField(field, name, 1, True)
650 self.func_end()
652 def visitConstructor(self, cons, enum, name):
653 self.emit("case %s_kind:" % cons.name, 1)
654 self.emit("result = PyType_GenericNew(%s_type, NULL, NULL);" % cons.name, 2);
655 self.emit("if (!result) goto failed;", 2)
656 for f in cons.fields:
657 self.visitField(f, cons.name, 2, False)
658 self.emit("break;", 2)
660 def visitField(self, field, name, depth, product):
661 def emit(s, d):
662 self.emit(s, depth + d)
663 if product:
664 value = "o->%s" % field.name
665 else:
666 value = "o->v.%s.%s" % (name, field.name)
667 self.set(field, value, depth)
668 emit("if (!value) goto failed;", 0)
669 emit('if (PyObject_SetAttrString(result, "%s", value) == -1)' % field.name, 0)
670 emit("goto failed;", 1)
671 emit("Py_DECREF(value);", 0)
673 def emitSeq(self, field, value, depth, emit):
674 emit("seq = %s;" % value, 0)
675 emit("n = asdl_seq_LEN(seq);", 0)
676 emit("value = PyList_New(n);", 0)
677 emit("if (!value) goto failed;", 0)
678 emit("for (i = 0; i < n; i++) {", 0)
679 self.set("value", field, "asdl_seq_GET(seq, i)", depth + 1)
680 emit("if (!value1) goto failed;", 1)
681 emit("PyList_SET_ITEM(value, i, value1);", 1)
682 emit("value1 = NULL;", 1)
683 emit("}", 0)
685 def set(self, field, value, depth):
686 if field.seq:
687 # XXX should really check for is_simple, but that requires a symbol table
688 if field.type.value == "cmpop":
689 # While the sequence elements are stored as void*,
690 # ast2obj_cmpop expects an enum
691 self.emit("{", depth)
692 self.emit("int i, n = asdl_seq_LEN(%s);" % value, depth+1)
693 self.emit("value = PyList_New(n);", depth+1)
694 self.emit("if (!value) goto failed;", depth+1)
695 self.emit("for(i = 0; i < n; i++)", depth+1)
696 # This cannot fail, so no need for error handling
697 self.emit("PyList_SET_ITEM(value, i, ast2obj_cmpop((cmpop_ty)asdl_seq_GET(%s, i)));" % value,
698 depth+2, reflow=False)
699 self.emit("}", depth)
700 else:
701 self.emit("value = ast2obj_list(%s, ast2obj_%s);" % (value, field.type), depth)
702 else:
703 ctype = get_c_type(field.type)
704 self.emit("value = ast2obj_%s(%s);" % (field.type, value), depth, reflow=False)
707 class PartingShots(StaticVisitor):
709 CODE = """
710 PyObject* PyAST_mod2obj(mod_ty t)
712 init_types();
713 return ast2obj_mod(t);
717 class ChainOfVisitors:
718 def __init__(self, *visitors):
719 self.visitors = visitors
721 def visit(self, object):
722 for v in self.visitors:
723 v.visit(object)
724 v.emit("", 0)
726 common_msg = "/* File automatically generated by %s. */\n"
728 c_file_msg = """
730 __version__ %s.
732 This module must be committed separately after each AST grammar change;
733 The __version__ number is set to the revision number of the commit
734 containing the grammar change.
738 def main(srcfile):
739 argv0 = sys.argv[0]
740 components = argv0.split(os.sep)
741 argv0 = os.sep.join(components[-2:])
742 auto_gen_msg = common_msg % argv0
743 mod = asdl.parse(srcfile)
744 if not asdl.check(mod):
745 sys.exit(1)
746 if INC_DIR:
747 p = "%s/%s-ast.h" % (INC_DIR, mod.name)
748 f = open(p, "wb")
749 print >> f, auto_gen_msg
750 print >> f, '#include "asdl.h"\n'
751 c = ChainOfVisitors(TypeDefVisitor(f),
752 StructVisitor(f),
753 PrototypeVisitor(f),
755 c.visit(mod)
756 print >>f, "PyObject* PyAST_mod2obj(mod_ty t);"
757 f.close()
759 if SRC_DIR:
760 p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c")
761 f = open(p, "wb")
762 print >> f, auto_gen_msg
763 print >> f, c_file_msg % parse_version(mod)
764 print >> f, '#include "Python.h"'
765 print >> f, '#include "%s-ast.h"' % mod.name
766 print >> f
767 print >>f, "static PyTypeObject* AST_type;"
768 v = ChainOfVisitors(
769 PyTypesDeclareVisitor(f),
770 PyTypesVisitor(f),
771 FunctionVisitor(f),
772 ObjVisitor(f),
773 ASTModuleVisitor(f),
774 PartingShots(f),
776 v.visit(mod)
777 f.close()
779 if __name__ == "__main__":
780 import sys
781 import getopt
783 INC_DIR = ''
784 SRC_DIR = ''
785 opts, args = getopt.getopt(sys.argv[1:], "h:c:")
786 if len(opts) != 1:
787 print "Must specify exactly one output file"
788 sys.exit(1)
789 for o, v in opts:
790 if o == '-h':
791 INC_DIR = v
792 if o == '-c':
793 SRC_DIR = v
794 if len(args) != 1:
795 print "Must specify single input file"
796 sys.exit(1)
797 main(args[0])