2 """Generate C code from an ASDL description."""
5 # handle fields that have a type but no name
7 import os
, sys
, traceback
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.
20 # XXX ack! need to figure out where Id is useful and where string
21 if isinstance(name
, asdl
.Id
):
23 if name
in asdl
.builtin_types
:
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
38 size
= MAX_COL
- depth
* TABSIZE
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
:
50 assert i
!= -1, "Impossible line %d to reflow: %s" % (size
, `s`
)
51 lines
.append(padding
+ cur
[:i
])
53 # find new size based on brace
54 j
= cur
.find('{', 0, i
)
56 j
+= 2 # account for the brace and the space after it
60 j
= cur
.find('(', 0, i
)
62 j
+= 1 # account for the paren (no space after it)
67 lines
.append(padding
+ cur
)
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
82 class EmitVisitor(asdl
.VisitorBase
):
83 """Visit that emits lines"""
85 def __init__(self
, file):
87 super(EmitVisitor
, self
).__init
__()
89 def emit(self
, s
, depth
, reflow
=1):
90 # XXX reflow long lines?
92 lines
= reflow_lines(s
, depth
)
96 line
= (" " * TABSIZE
* depth
) + line
+ "\n"
99 class TypeDefVisitor(EmitVisitor
):
100 def visitModule(self
, mod
):
104 def visitType(self
, type, depth
=0):
105 self
.visit(type.value
, type.name
, depth
)
107 def visitSum(self
, sum, name
, depth
):
109 self
.simple_sum(sum, name
, depth
)
111 self
.sum_with_constructors(sum, name
, depth
)
113 def simple_sum(self
, sum, name
, depth
):
115 for i
in range(len(sum.types
)):
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
)
124 def sum_with_constructors(self
, sum, name
, depth
):
125 ctype
= get_c_type(name
)
126 s
= "typedef struct _%(name)s *%(ctype)s;" % locals()
130 def visitProduct(self
, product
, name
, depth
):
131 ctype
= get_c_type(name
)
132 s
= "typedef struct _%(name)s *%(ctype)s;" % locals()
136 class StructVisitor(EmitVisitor
):
137 """Visitor to generate typdefs for AST."""
139 def visitModule(self
, mod
):
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
)
154 for i
in range(len(sum.types
)):
156 enum
.append("%s_kind=%d" % (type.name
, i
+ 1))
158 emit("struct _%(name)s {")
159 emit("enum { " + ", ".join(enum
) + " } kind;", depth
+ 1)
160 emit("union {", depth
+ 1)
162 self
.visit(t
, depth
+ 2)
163 emit("} v;", depth
+ 1)
164 for field
in sum.attributes
:
165 # rudimentary attribute handling
166 type = str(field
.type)
167 assert type in asdl
.builtin_types
, type
168 emit("%s %s;" % (type, field
.name
), depth
+ 1);
172 def visitConstructor(self
, cons
, depth
):
174 self
.emit("struct {", depth
)
175 for f
in cons
.fields
:
176 self
.visit(f
, depth
+ 1)
177 self
.emit("} %s;" % cons
.name
, depth
)
180 # XXX not sure what I want here, nothing is probably fine
183 def visitField(self
, field
, depth
):
184 # XXX need to lookup field.type, because it might be something
186 ctype
= get_c_type(field
.type)
189 self
.emit("asdl_seq *%(name)s;" % locals(), depth
)
191 self
.emit("%(ctype)s %(name)s;" % locals(), depth
)
193 def visitProduct(self
, product
, name
, depth
):
194 self
.emit("struct _%(name)s {" % locals(), depth
)
195 for f
in product
.fields
:
196 self
.visit(f
, depth
+ 1)
197 self
.emit("};", depth
)
200 class PrototypeVisitor(EmitVisitor
):
201 """Generate function prototypes for the .h file"""
203 def visitModule(self
, mod
):
207 def visitType(self
, type):
208 self
.visit(type.value
, type.name
)
210 def visitSum(self
, sum, name
):
215 self
.visit(t
, name
, sum.attributes
)
217 def get_args(self
, fields
):
218 """Return list of C argument into, one for each field.
220 Argument info is 3-tuple of a C type, variable name, and flag
221 that is true if type can be NULL.
228 c
= unnamed
[name
] = unnamed
.get(name
, 0) + 1
230 name
= "name%d" % (c
- 1)
233 # XXX should extend get_c_type() to handle this
237 ctype
= get_c_type(f
.type)
238 args
.append((ctype
, name
, f
.opt
or f
.seq
))
241 def visitConstructor(self
, cons
, type, attrs
):
242 args
= self
.get_args(cons
.fields
)
243 attrs
= self
.get_args(attrs
)
244 ctype
= get_c_type(type)
245 self
.emit_function(cons
.name
, ctype
, args
, attrs
)
247 def emit_function(self
, name
, ctype
, args
, attrs
, union
=1):
250 argstr
= ", ".join(["%s %s" % (atype
, aname
)
251 for atype
, aname
, opt
in args
])
254 self
.emit("%s %s(%s);" % (ctype
, name
, argstr
), 0)
256 def visitProduct(self
, prod
, name
):
257 self
.emit_function(name
, get_c_type(name
),
258 self
.get_args(prod
.fields
), [], union
=0)
260 class FunctionVisitor(PrototypeVisitor
):
261 """Visitor to generate constructor functions for AST."""
263 def emit_function(self
, name
, ctype
, args
, attrs
, union
=1):
264 def emit(s
, depth
=0, reflow
=1):
265 self
.emit(s
, depth
, reflow
)
266 argstr
= ", ".join(["%s %s" % (atype
, aname
)
267 for atype
, aname
, opt
in args
+ attrs
])
268 self
.emit("%s" % ctype
, 0)
269 emit("%s(%s)" % (name
, argstr
))
271 emit("%s p;" % ctype
, 1)
272 for argtype
, argname
, opt
in args
:
273 # XXX hack alert: false is allowed for a bool
274 if not opt
and not argtype
== "bool":
275 emit("if (!%s) {" % argname
, 1)
276 emit("PyErr_SetString(PyExc_ValueError,", 2)
277 msg
= "field %s is required for %s" % (argname
, name
)
278 emit(' "%s");' % msg
,
280 emit('return NULL;', 2)
283 emit("p = (%s)malloc(sizeof(*p));" % ctype
, 1)
285 emit("PyErr_NoMemory();", 2)
286 emit("return NULL;", 2)
289 self
.emit_body_union(name
, args
, attrs
)
291 self
.emit_body_struct(name
, args
, attrs
)
296 def emit_body_union(self
, name
, args
, attrs
):
297 def emit(s
, depth
=0, reflow
=1):
298 self
.emit(s
, depth
, reflow
)
299 emit("p->kind = %s_kind;" % name
, 1)
300 for argtype
, argname
, opt
in args
:
301 emit("p->v.%s.%s = %s;" % (name
, argname
, argname
), 1)
302 for argtype
, argname
, opt
in attrs
:
303 emit("p->%s = %s;" % (argname
, argname
), 1)
305 def emit_body_struct(self
, name
, args
, attrs
):
306 def emit(s
, depth
=0, reflow
=1):
307 self
.emit(s
, depth
, reflow
)
308 for argtype
, argname
, opt
in args
:
309 emit("p->%s = %s;" % (argname
, argname
), 1)
312 class PickleVisitor(EmitVisitor
):
314 def visitModule(self
, mod
):
318 def visitType(self
, type):
319 self
.visit(type.value
, type.name
)
321 def visitSum(self
, sum, name
):
324 def visitProduct(self
, sum, name
):
327 def visitConstructor(self
, cons
, name
):
330 def visitField(self
, sum):
333 class MarshalPrototypeVisitor(PickleVisitor
):
335 def prototype(self
, sum, name
):
336 ctype
= get_c_type(name
)
337 self
.emit("int marshal_write_%s(PyObject **, int *, %s);"
340 visitProduct
= visitSum
= prototype
342 class FreePrototypeVisitor(PickleVisitor
):
344 def prototype(self
, sum, name
):
345 ctype
= get_c_type(name
)
346 self
.emit("void free_%s(%s);" % (name
, ctype
), 0)
348 visitProduct
= visitSum
= prototype
350 _SPECIALIZED_SEQUENCES
= ('stmt', 'expr')
352 def find_sequence(fields
, doing_specialization
):
353 """Return True if any field uses a sequence."""
356 if not doing_specialization
:
358 if str(f
.type) not in _SPECIALIZED_SEQUENCES
:
362 def has_sequence(types
, doing_specialization
):
364 if find_sequence(t
.fields
, doing_specialization
):
369 class StaticVisitor(PickleVisitor
):
370 '''Very simple, always emit this static code'''
372 CODE
= '''static void
373 free_seq_exprs(asdl_seq *seq)
376 n = asdl_seq_LEN(seq);
377 for (i = 0; i < n; i++)
378 free_expr((expr_ty)asdl_seq_GET(seq, i));
383 free_seq_stmts(asdl_seq *seq)
386 n = asdl_seq_LEN(seq);
387 for (i = 0; i < n; i++)
388 free_stmt((stmt_ty)asdl_seq_GET(seq, i));
393 def visit(self
, object):
394 self
.emit(self
.CODE
, 0, reflow
=False)
397 class FreeVisitor(PickleVisitor
):
399 def func_begin(self
, name
, has_seq
):
400 ctype
= get_c_type(name
)
402 self
.emit("free_%s(%s o)" % (name
, ctype
), 0)
405 self
.emit("int i, n;", 1)
406 self
.emit("asdl_seq *seq;", 1)
408 self
.emit('if (!o)', 1)
409 self
.emit('return;', 2)
416 def visitSum(self
, sum, name
):
417 has_seq
= has_sequence(sum.types
, True)
418 self
.func_begin(name
, has_seq
)
419 if not is_simple(sum):
420 self
.emit("switch (o->kind) {", 1)
421 for i
in range(len(sum.types
)):
423 self
.visitConstructor(t
, i
+ 1, name
)
426 self
.emit("free(o);", 1)
429 def visitProduct(self
, prod
, name
):
430 self
.func_begin(name
, find_sequence(prod
.fields
, True))
431 for field
in prod
.fields
:
432 self
.visitField(field
, name
, 1, True)
434 self
.emit("free(o);", 1)
437 def visitConstructor(self
, cons
, enum
, name
):
438 self
.emit("case %s_kind:" % cons
.name
, 1)
439 for f
in cons
.fields
:
440 self
.visitField(f
, cons
.name
, 2, False)
441 self
.emit("break;", 2)
443 def visitField(self
, field
, name
, depth
, product
):
445 self
.emit(s
, depth
+ d
)
447 value
= "o->%s" % field
.name
449 value
= "o->v.%s.%s" % (name
, field
.name
)
451 self
.emitSeq(field
, value
, depth
, emit
)
453 # XXX need to know the simple types in advance, so that we
454 # don't call free_TYPE() for them.
457 emit("if (%s) {" % value
, 0)
458 self
.free(field
, value
, depth
+ 1)
461 self
.free(field
, value
, depth
)
463 def emitSeq(self
, field
, value
, depth
, emit
):
464 # specialize for freeing sequences of statements and expressions
465 if str(field
.type) in _SPECIALIZED_SEQUENCES
:
466 c_code
= "free_seq_%ss(%s);" % (field
.type, value
)
469 emit("seq = %s;" % value
, 0)
470 emit("n = asdl_seq_LEN(seq);", 0)
471 emit("for (i = 0; i < n; i++)", 0)
472 self
.free(field
, "asdl_seq_GET(seq, i)", depth
+ 1)
473 emit("asdl_seq_free(seq);", 0)
475 def free(self
, field
, value
, depth
):
476 if str(field
.type) in ("identifier", "string", "object"):
477 ctype
= get_c_type(field
.type)
478 self
.emit("Py_DECREF((%s)%s);" % (ctype
, value
), depth
)
479 elif str(field
.type) == "bool":
482 ctype
= get_c_type(field
.type)
483 self
.emit("free_%s((%s)%s);" % (field
.type, ctype
, value
), depth
)
486 class MarshalFunctionVisitor(PickleVisitor
):
488 def func_begin(self
, name
, has_seq
):
489 ctype
= get_c_type(name
)
491 self
.emit("marshal_write_%s(PyObject **buf, int *off, %s o)" %
495 self
.emit("int i;", 1)
498 self
.emit("return 1;", 1)
502 def visitSum(self
, sum, name
):
503 self
.func_begin(name
, has_sequence(sum.types
, False))
504 simple
= is_simple(sum)
506 self
.emit("switch (o) {", 1)
508 self
.emit("switch (o->kind) {", 1)
509 for i
in range(len(sum.types
)):
511 self
.visitConstructor(t
, i
+ 1, name
, simple
)
515 def visitProduct(self
, prod
, name
):
516 self
.func_begin(name
, find_sequence(prod
.fields
, False))
517 for field
in prod
.fields
:
518 self
.visitField(field
, name
, 1, 1)
521 def visitConstructor(self
, cons
, enum
, name
, simple
):
523 self
.emit("case %s:" % cons
.name
, 1)
524 self
.emit("marshal_write_int(buf, off, %d);" % enum
, 2);
525 self
.emit("break;", 2)
527 self
.emit("case %s_kind:" % cons
.name
, 1)
528 self
.emit("marshal_write_int(buf, off, %d);" % enum
, 2)
529 for f
in cons
.fields
:
530 self
.visitField(f
, cons
.name
, 2, 0)
531 self
.emit("break;", 2)
533 def visitField(self
, field
, name
, depth
, product
):
535 self
.emit(s
, depth
+ d
)
537 value
= "o->%s" % field
.name
539 value
= "o->v.%s.%s" % (name
, field
.name
)
541 emit("marshal_write_int(buf, off, asdl_seq_LEN(%s));" % value
, 0)
542 emit("for (i = 0; i < asdl_seq_LEN(%s); i++) {" % value
, 0)
543 emit("void *elt = asdl_seq_GET(%s, i);" % value
, 1);
544 ctype
= get_c_type(field
.type);
545 emit("marshal_write_%s(buf, off, (%s)elt);" % (field
.type,
549 emit("if (%s) {" % value
, 0)
550 emit("marshal_write_int(buf, off, 1);", 1)
551 emit("marshal_write_%s(buf, off, %s);" % (field
.type, value
), 1)
554 emit("marshal_write_int(buf, off, 0);", 1)
557 emit("marshal_write_%s(buf, off, %s);" % (field
.type, value
), 0)
559 class ChainOfVisitors
:
560 def __init__(self
, *visitors
):
561 self
.visitors
= visitors
563 def visit(self
, object):
564 for v
in self
.visitors
:
568 auto_gen_msg
= '/* File automatically generated by %s */\n' % sys
.argv
[0]
569 mod
= asdl
.parse(srcfile
)
570 if not asdl
.check(mod
):
573 p
= "%s/%s-ast.h" % (INC_DIR
, mod
.name
)
575 p
= "%s-ast.h" % mod
.name
577 print >> f
, auto_gen_msg
578 print >> f
, '#include "asdl.h"\n'
579 c
= ChainOfVisitors(TypeDefVisitor(f
),
582 FreePrototypeVisitor(f
),
583 MarshalPrototypeVisitor(f
),
589 p
= "%s/%s-ast.c" % (SRC_DIR
, mod
.name
)
591 p
= "%s-ast.c" % mod
.name
593 print >> f
, auto_gen_msg
594 print >> f
, '#include "Python.h"'
595 print >> f
, '#include "%s-ast.h"' % mod
.name
597 v
= ChainOfVisitors(FunctionVisitor(f
),
600 MarshalFunctionVisitor(f
),
605 if __name__
== "__main__":
611 opts
, args
= getopt
.getopt(sys
.argv
[1:], "h:c:")
618 print "Must specify single input file"