blob: cdce5a3f032514ec5a810630db39078c1f8dfbe1 [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
Benjamin Peterson6cb2b922011-03-12 18:28:16 -06008import subprocess
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00009
10import asdl
11
12TABSIZE = 8
13MAX_COL = 80
14
15def get_c_type(name):
16 """Return a string for the C name of the type.
17
18 This function special cases the default types provided by asdl:
Neal Norwitz3591bbe2007-02-26 19:04:49 +000019 identifier, string, int.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000020 """
21 # XXX ack! need to figure out where Id is useful and where string
22 if isinstance(name, asdl.Id):
23 name = name.value
24 if name in asdl.builtin_types:
25 return name
26 else:
27 return "%s_ty" % name
28
29def reflow_lines(s, depth):
30 """Reflow the line s indented depth tabs.
31
32 Return a sequence of lines where no line extends beyond MAX_COL
33 when properly indented. The first line is properly indented based
34 exclusively on depth * TABSIZE. All following lines -- these are
35 the reflowed lines generated by this function -- start at the same
36 column as the first character beyond the opening { in the first
37 line.
38 """
39 size = MAX_COL - depth * TABSIZE
40 if len(s) < size:
41 return [s]
42
43 lines = []
44 cur = s
45 padding = ""
46 while len(cur) > size:
47 i = cur.rfind(' ', 0, size)
48 # XXX this should be fixed for real
49 if i == -1 and 'GeneratorExp' in cur:
50 i = size + 3
Brett Cannonf0365512006-08-25 04:06:31 +000051 assert i != -1, "Impossible line %d to reflow: %r" % (size, s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000052 lines.append(padding + cur[:i])
53 if len(lines) == 1:
54 # find new size based on brace
55 j = cur.find('{', 0, i)
56 if j >= 0:
57 j += 2 # account for the brace and the space after it
58 size -= j
59 padding = " " * j
60 else:
61 j = cur.find('(', 0, i)
62 if j >= 0:
63 j += 1 # account for the paren (no space after it)
64 size -= j
65 padding = " " * j
66 cur = cur[i+1:]
67 else:
68 lines.append(padding + cur)
69 return lines
70
71def is_simple(sum):
72 """Return True if a sum is a simple.
73
74 A sum is simple if its types have no fields, e.g.
75 unaryop = Invert | Not | UAdd | USub
76 """
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000077 for t in sum.types:
78 if t.fields:
79 return False
80 return True
81
Martin v. Löwis618dc5e2008-03-30 20:03:44 +000082
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000083class EmitVisitor(asdl.VisitorBase):
84 """Visit that emits lines"""
85
86 def __init__(self, file):
87 self.file = file
88 super(EmitVisitor, self).__init__()
89
Benjamin Peterson87c8d872009-06-11 22:54:11 +000090 def emit(self, s, depth, reflow=True):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000091 # XXX reflow long lines?
92 if reflow:
93 lines = reflow_lines(s, depth)
94 else:
95 lines = [s]
96 for line in lines:
97 line = (" " * TABSIZE * depth) + line + "\n"
98 self.file.write(line)
99
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000100
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000101class TypeDefVisitor(EmitVisitor):
102 def visitModule(self, mod):
103 for dfn in mod.dfns:
104 self.visit(dfn)
105
106 def visitType(self, type, depth=0):
107 self.visit(type.value, type.name, depth)
108
109 def visitSum(self, sum, name, depth):
110 if is_simple(sum):
111 self.simple_sum(sum, name, depth)
112 else:
113 self.sum_with_constructors(sum, name, depth)
114
115 def simple_sum(self, sum, name, depth):
116 enum = []
117 for i in range(len(sum.types)):
118 type = sum.types[i]
119 enum.append("%s=%d" % (type.name, i + 1))
120 enums = ", ".join(enum)
121 ctype = get_c_type(name)
122 s = "typedef enum _%s { %s } %s;" % (name, enums, ctype)
123 self.emit(s, depth)
124 self.emit("", depth)
125
126 def sum_with_constructors(self, sum, name, depth):
127 ctype = get_c_type(name)
128 s = "typedef struct _%(name)s *%(ctype)s;" % locals()
129 self.emit(s, depth)
130 self.emit("", depth)
131
132 def visitProduct(self, product, name, depth):
133 ctype = get_c_type(name)
134 s = "typedef struct _%(name)s *%(ctype)s;" % locals()
135 self.emit(s, depth)
136 self.emit("", depth)
137
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000138
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000139class StructVisitor(EmitVisitor):
140 """Visitor to generate typdefs for AST."""
141
142 def visitModule(self, mod):
143 for dfn in mod.dfns:
144 self.visit(dfn)
145
146 def visitType(self, type, depth=0):
147 self.visit(type.value, type.name, depth)
148
149 def visitSum(self, sum, name, depth):
150 if not is_simple(sum):
151 self.sum_with_constructors(sum, name, depth)
152
153 def sum_with_constructors(self, sum, name, depth):
154 def emit(s, depth=depth):
155 self.emit(s % sys._getframe(1).f_locals, depth)
156 enum = []
157 for i in range(len(sum.types)):
158 type = sum.types[i]
159 enum.append("%s_kind=%d" % (type.name, i + 1))
160
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000161 emit("enum _%(name)s_kind {" + ", ".join(enum) + "};")
162
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000163 emit("struct _%(name)s {")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000164 emit("enum _%(name)s_kind kind;", depth + 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000165 emit("union {", depth + 1)
166 for t in sum.types:
167 self.visit(t, depth + 2)
168 emit("} v;", depth + 1)
169 for field in sum.attributes:
170 # rudimentary attribute handling
171 type = str(field.type)
172 assert type in asdl.builtin_types, type
173 emit("%s %s;" % (type, field.name), depth + 1);
174 emit("};")
175 emit("")
176
177 def visitConstructor(self, cons, depth):
178 if cons.fields:
179 self.emit("struct {", depth)
180 for f in cons.fields:
181 self.visit(f, depth + 1)
182 self.emit("} %s;" % cons.name, depth)
183 self.emit("", depth)
184 else:
185 # XXX not sure what I want here, nothing is probably fine
186 pass
187
188 def visitField(self, field, depth):
189 # XXX need to lookup field.type, because it might be something
190 # like a builtin...
191 ctype = get_c_type(field.type)
192 name = field.name
193 if field.seq:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000194 if field.type.value in ('cmpop',):
195 self.emit("asdl_int_seq *%(name)s;" % locals(), depth)
196 else:
197 self.emit("asdl_seq *%(name)s;" % locals(), depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000198 else:
199 self.emit("%(ctype)s %(name)s;" % locals(), depth)
200
201 def visitProduct(self, product, name, depth):
202 self.emit("struct _%(name)s {" % locals(), depth)
203 for f in product.fields:
204 self.visit(f, depth + 1)
205 self.emit("};", depth)
206 self.emit("", depth)
207
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000208
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000209class PrototypeVisitor(EmitVisitor):
210 """Generate function prototypes for the .h file"""
211
212 def visitModule(self, mod):
213 for dfn in mod.dfns:
214 self.visit(dfn)
215
216 def visitType(self, type):
217 self.visit(type.value, type.name)
218
219 def visitSum(self, sum, name):
220 if is_simple(sum):
221 pass # XXX
222 else:
223 for t in sum.types:
224 self.visit(t, name, sum.attributes)
225
226 def get_args(self, fields):
227 """Return list of C argument into, one for each field.
228
229 Argument info is 3-tuple of a C type, variable name, and flag
230 that is true if type can be NULL.
231 """
232 args = []
233 unnamed = {}
234 for f in fields:
235 if f.name is None:
236 name = f.type
237 c = unnamed[name] = unnamed.get(name, 0) + 1
238 if c > 1:
239 name = "name%d" % (c - 1)
240 else:
241 name = f.name
242 # XXX should extend get_c_type() to handle this
243 if f.seq:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000244 if f.type.value in ('cmpop',):
245 ctype = "asdl_int_seq *"
246 else:
247 ctype = "asdl_seq *"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000248 else:
249 ctype = get_c_type(f.type)
250 args.append((ctype, name, f.opt or f.seq))
251 return args
252
253 def visitConstructor(self, cons, type, attrs):
254 args = self.get_args(cons.fields)
255 attrs = self.get_args(attrs)
256 ctype = get_c_type(type)
257 self.emit_function(cons.name, ctype, args, attrs)
258
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000259 def emit_function(self, name, ctype, args, attrs, union=True):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000260 args = args + attrs
261 if args:
262 argstr = ", ".join(["%s %s" % (atype, aname)
263 for atype, aname, opt in args])
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000264 argstr += ", PyArena *arena"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000265 else:
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000266 argstr = "PyArena *arena"
Thomas Woutersb2137042007-02-01 18:02:27 +0000267 margs = "a0"
268 for i in range(1, len(args)+1):
269 margs += ", a%d" % i
270 self.emit("#define %s(%s) _Py_%s(%s)" % (name, margs, name, margs), 0,
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000271 reflow=False)
272 self.emit("%s _Py_%s(%s);" % (ctype, name, argstr), False)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000273
274 def visitProduct(self, prod, name):
275 self.emit_function(name, get_c_type(name),
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000276 self.get_args(prod.fields), [], union=False)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000277
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000278
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000279class FunctionVisitor(PrototypeVisitor):
280 """Visitor to generate constructor functions for AST."""
281
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000282 def emit_function(self, name, ctype, args, attrs, union=True):
283 def emit(s, depth=0, reflow=True):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000284 self.emit(s, depth, reflow)
285 argstr = ", ".join(["%s %s" % (atype, aname)
286 for atype, aname, opt in args + attrs])
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000287 if argstr:
288 argstr += ", PyArena *arena"
289 else:
290 argstr = "PyArena *arena"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000291 self.emit("%s" % ctype, 0)
292 emit("%s(%s)" % (name, argstr))
293 emit("{")
294 emit("%s p;" % ctype, 1)
295 for argtype, argname, opt in args:
Neal Norwitz3591bbe2007-02-26 19:04:49 +0000296 if not opt and argtype != "int":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000297 emit("if (!%s) {" % argname, 1)
298 emit("PyErr_SetString(PyExc_ValueError,", 2)
299 msg = "field %s is required for %s" % (argname, name)
300 emit(' "%s");' % msg,
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000301 2, reflow=False)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000302 emit('return NULL;', 2)
303 emit('}', 1)
304
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000305 emit("p = (%s)PyArena_Malloc(arena, sizeof(*p));" % ctype, 1);
Thomas Woutersa44f3a32007-02-26 18:20:15 +0000306 emit("if (!p)", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000307 emit("return NULL;", 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000308 if union:
309 self.emit_body_union(name, args, attrs)
310 else:
311 self.emit_body_struct(name, args, attrs)
312 emit("return p;", 1)
313 emit("}")
314 emit("")
315
316 def emit_body_union(self, name, args, attrs):
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000317 def emit(s, depth=0, reflow=True):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000318 self.emit(s, depth, reflow)
319 emit("p->kind = %s_kind;" % name, 1)
320 for argtype, argname, opt in args:
321 emit("p->v.%s.%s = %s;" % (name, argname, argname), 1)
322 for argtype, argname, opt in attrs:
323 emit("p->%s = %s;" % (argname, argname), 1)
324
325 def emit_body_struct(self, name, args, attrs):
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000326 def emit(s, depth=0, reflow=True):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000327 self.emit(s, depth, reflow)
328 for argtype, argname, opt in args:
329 emit("p->%s = %s;" % (argname, argname), 1)
330 assert not attrs
331
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000332
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000333class PickleVisitor(EmitVisitor):
334
335 def visitModule(self, mod):
336 for dfn in mod.dfns:
337 self.visit(dfn)
338
339 def visitType(self, type):
340 self.visit(type.value, type.name)
341
342 def visitSum(self, sum, name):
343 pass
344
345 def visitProduct(self, sum, name):
346 pass
347
348 def visitConstructor(self, cons, name):
349 pass
350
351 def visitField(self, sum):
352 pass
353
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000354
355class Obj2ModPrototypeVisitor(PickleVisitor):
356 def visitProduct(self, prod, name):
357 code = "static int obj2ast_%s(PyObject* obj, %s* out, PyArena* arena);"
358 self.emit(code % (name, get_c_type(name)), 0)
359
360 visitSum = visitProduct
361
362
363class Obj2ModVisitor(PickleVisitor):
364 def funcHeader(self, name):
365 ctype = get_c_type(name)
366 self.emit("int", 0)
367 self.emit("obj2ast_%s(PyObject* obj, %s* out, PyArena* arena)" % (name, ctype), 0)
368 self.emit("{", 0)
Benjamin Peterson0e9e98e2010-11-20 02:01:45 +0000369 self.emit("int isinstance;", 1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000370 self.emit("", 0)
371
Benjamin Peterson5b066812010-11-20 01:38:49 +0000372 def sumTrailer(self, name, add_label=False):
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000373 self.emit("", 0)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000374 # there's really nothing more we can do if this fails ...
Benjamin Peterson5b066812010-11-20 01:38:49 +0000375 error = "expected some sort of %s, but got %%R" % name
376 format = "PyErr_Format(PyExc_TypeError, \"%s\", obj);"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000377 self.emit(format % error, 1, reflow=False)
Benjamin Peterson5b066812010-11-20 01:38:49 +0000378 if add_label:
379 self.emit("failed:", 1)
Benjamin Peterson0a4dae52010-11-21 15:12:34 +0000380 self.emit("Py_XDECREF(tmp);", 1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000381 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:
Benjamin Peterson97dd9872009-12-13 01:23:39 +0000388 line = ("isinstance = PyObject_IsInstance(obj, "
389 "(PyObject *)%s_type);")
390 self.emit(line % (t.name,), 1)
391 self.emit("if (isinstance == -1) {", 1)
392 self.emit("return 1;", 2)
393 self.emit("}", 1)
394 self.emit("if (isinstance) {", 1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000395 self.emit("*out = %s;" % t.name, 2)
396 self.emit("return 0;", 2)
397 self.emit("}", 1)
398 self.sumTrailer(name)
399
400 def buildArgs(self, fields):
401 return ", ".join(fields + ["arena"])
402
403 def complexSum(self, sum, name):
404 self.funcHeader(name)
Benjamin Petersond8f65972010-11-20 04:31:07 +0000405 self.emit("PyObject *tmp = NULL;", 1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000406 for a in sum.attributes:
407 self.visitAttributeDeclaration(a, name, sum=sum)
408 self.emit("", 0)
409 # XXX: should we only do this for 'expr'?
410 self.emit("if (obj == Py_None) {", 1)
411 self.emit("*out = NULL;", 2)
412 self.emit("return 0;", 2)
413 self.emit("}", 1)
414 for a in sum.attributes:
415 self.visitField(a, name, sum=sum, depth=1)
416 for t in sum.types:
Benjamin Peterson97dd9872009-12-13 01:23:39 +0000417 line = "isinstance = PyObject_IsInstance(obj, (PyObject*)%s_type);"
418 self.emit(line % (t.name,), 1)
419 self.emit("if (isinstance == -1) {", 1)
420 self.emit("return 1;", 2)
421 self.emit("}", 1)
422 self.emit("if (isinstance) {", 1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000423 for f in t.fields:
424 self.visitFieldDeclaration(f, t.name, sum=sum, depth=2)
425 self.emit("", 0)
426 for f in t.fields:
427 self.visitField(f, t.name, sum=sum, depth=2)
428 args = [f.name.value for f in t.fields] + [a.name.value for a in sum.attributes]
429 self.emit("*out = %s(%s);" % (t.name, self.buildArgs(args)), 2)
430 self.emit("if (*out == NULL) goto failed;", 2)
431 self.emit("return 0;", 2)
432 self.emit("}", 1)
Benjamin Peterson5b066812010-11-20 01:38:49 +0000433 self.sumTrailer(name, True)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000434
435 def visitAttributeDeclaration(self, a, name, sum=sum):
436 ctype = get_c_type(a.type)
437 self.emit("%s %s;" % (ctype, a.name), 1)
438
439 def visitSum(self, sum, name):
440 if is_simple(sum):
441 self.simpleSum(sum, name)
442 else:
443 self.complexSum(sum, name)
444
445 def visitProduct(self, prod, name):
446 ctype = get_c_type(name)
447 self.emit("int", 0)
448 self.emit("obj2ast_%s(PyObject* obj, %s* out, PyArena* arena)" % (name, ctype), 0)
449 self.emit("{", 0)
450 self.emit("PyObject* tmp = NULL;", 1)
451 for f in prod.fields:
452 self.visitFieldDeclaration(f, name, prod=prod, depth=1)
453 self.emit("", 0)
454 for f in prod.fields:
455 self.visitField(f, name, prod=prod, depth=1)
456 args = [f.name.value for f in prod.fields]
457 self.emit("*out = %s(%s);" % (name, self.buildArgs(args)), 1)
458 self.emit("return 0;", 1)
459 self.emit("failed:", 0)
460 self.emit("Py_XDECREF(tmp);", 1)
461 self.emit("return 1;", 1)
462 self.emit("}", 0)
463 self.emit("", 0)
464
465 def visitFieldDeclaration(self, field, name, sum=None, prod=None, depth=0):
466 ctype = get_c_type(field.type)
467 if field.seq:
468 if self.isSimpleType(field):
469 self.emit("asdl_int_seq* %s;" % field.name, depth)
470 else:
471 self.emit("asdl_seq* %s;" % field.name, depth)
472 else:
473 ctype = get_c_type(field.type)
474 self.emit("%s %s;" % (ctype, field.name), depth)
475
476 def isSimpleSum(self, field):
477 # XXX can the members of this list be determined automatically?
478 return field.type.value in ('expr_context', 'boolop', 'operator',
479 'unaryop', 'cmpop')
480
481 def isNumeric(self, field):
482 return get_c_type(field.type) in ("int", "bool")
483
484 def isSimpleType(self, field):
485 return self.isSimpleSum(field) or self.isNumeric(field)
486
487 def visitField(self, field, name, sum=None, prod=None, depth=0):
488 ctype = get_c_type(field.type)
489 self.emit("if (PyObject_HasAttrString(obj, \"%s\")) {" % field.name, depth)
490 self.emit("int res;", depth+1)
491 if field.seq:
492 self.emit("Py_ssize_t len;", depth+1)
493 self.emit("Py_ssize_t i;", depth+1)
494 self.emit("tmp = PyObject_GetAttrString(obj, \"%s\");" % field.name, depth+1)
495 self.emit("if (tmp == NULL) goto failed;", depth+1)
496 if field.seq:
497 self.emit("if (!PyList_Check(tmp)) {", depth+1)
498 self.emit("PyErr_Format(PyExc_TypeError, \"%s field \\\"%s\\\" must "
499 "be a list, not a %%.200s\", tmp->ob_type->tp_name);" %
500 (name, field.name),
501 depth+2, reflow=False)
502 self.emit("goto failed;", depth+2)
503 self.emit("}", depth+1)
504 self.emit("len = PyList_GET_SIZE(tmp);", depth+1)
505 if self.isSimpleType(field):
506 self.emit("%s = asdl_int_seq_new(len, arena);" % field.name, depth+1)
507 else:
508 self.emit("%s = asdl_seq_new(len, arena);" % field.name, depth+1)
509 self.emit("if (%s == NULL) goto failed;" % field.name, depth+1)
510 self.emit("for (i = 0; i < len; i++) {", depth+1)
511 self.emit("%s value;" % ctype, depth+2)
512 self.emit("res = obj2ast_%s(PyList_GET_ITEM(tmp, i), &value, arena);" %
513 field.type, depth+2, reflow=False)
514 self.emit("if (res != 0) goto failed;", depth+2)
515 self.emit("asdl_seq_SET(%s, i, value);" % field.name, depth+2)
516 self.emit("}", depth+1)
517 else:
518 self.emit("res = obj2ast_%s(tmp, &%s, arena);" %
519 (field.type, field.name), depth+1)
520 self.emit("if (res != 0) goto failed;", depth+1)
521
522 self.emit("Py_XDECREF(tmp);", depth+1)
523 self.emit("tmp = NULL;", depth+1)
524 self.emit("} else {", depth)
525 if not field.opt:
526 message = "required field \\\"%s\\\" missing from %s" % (field.name, name)
527 format = "PyErr_SetString(PyExc_TypeError, \"%s\");"
528 self.emit(format % message, depth+1, reflow=False)
529 self.emit("return 1;", depth+1)
530 else:
531 if self.isNumeric(field):
532 self.emit("%s = 0;" % field.name, depth+1)
533 elif not self.isSimpleType(field):
534 self.emit("%s = NULL;" % field.name, depth+1)
535 else:
536 raise TypeError("could not determine the default value for %s" % field.name)
537 self.emit("}", depth)
538
539
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000540class MarshalPrototypeVisitor(PickleVisitor):
541
542 def prototype(self, sum, name):
543 ctype = get_c_type(name)
Neal Norwitz6576bd82005-11-13 18:41:28 +0000544 self.emit("static int marshal_write_%s(PyObject **, int *, %s);"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000545 % (name, ctype), 0)
546
547 visitProduct = visitSum = prototype
548
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000549
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000550class PyTypesDeclareVisitor(PickleVisitor):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000551
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000552 def visitProduct(self, prod, name):
Neal Norwitz53d960c2006-02-28 22:47:29 +0000553 self.emit("static PyTypeObject *%s_type;" % name, 0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000554 self.emit("static PyObject* ast2obj_%s(void*);" % name, 0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000555 if prod.fields:
Neal Norwitz53d960c2006-02-28 22:47:29 +0000556 self.emit("static char *%s_fields[]={" % name,0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000557 for f in prod.fields:
558 self.emit('"%s",' % f.name, 1)
559 self.emit("};", 0)
Tim Peters710ab3b2006-02-28 18:30:36 +0000560
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000561 def visitSum(self, sum, name):
Neal Norwitz53d960c2006-02-28 22:47:29 +0000562 self.emit("static PyTypeObject *%s_type;" % name, 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000563 if sum.attributes:
Neal Norwitz53d960c2006-02-28 22:47:29 +0000564 self.emit("static char *%s_attributes[] = {" % name, 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000565 for a in sum.attributes:
566 self.emit('"%s",' % a.name, 1)
567 self.emit("};", 0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000568 ptype = "void*"
569 if is_simple(sum):
570 ptype = get_c_type(name)
571 tnames = []
572 for t in sum.types:
573 tnames.append(str(t.name)+"_singleton")
574 tnames = ", *".join(tnames)
575 self.emit("static PyObject *%s;" % tnames, 0)
576 self.emit("static PyObject* ast2obj_%s(%s);" % (name, ptype), 0)
577 for t in sum.types:
578 self.visitConstructor(t, name)
Tim Peters710ab3b2006-02-28 18:30:36 +0000579
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000580 def visitConstructor(self, cons, name):
Neal Norwitz53d960c2006-02-28 22:47:29 +0000581 self.emit("static PyTypeObject *%s_type;" % cons.name, 0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000582 if cons.fields:
Neal Norwitz53d960c2006-02-28 22:47:29 +0000583 self.emit("static char *%s_fields[]={" % cons.name, 0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000584 for t in cons.fields:
585 self.emit('"%s",' % t.name, 1)
586 self.emit("};",0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000587
588class PyTypesVisitor(PickleVisitor):
589
590 def visitModule(self, mod):
591 self.emit("""
Neal Norwitz207c9f32008-03-31 04:42:11 +0000592static int
593ast_type_init(PyObject *self, PyObject *args, PyObject *kw)
594{
595 Py_ssize_t i, numfields = 0;
596 int res = -1;
597 PyObject *key, *value, *fields;
598 fields = PyObject_GetAttrString((PyObject*)Py_TYPE(self), "_fields");
599 if (!fields)
600 PyErr_Clear();
601 if (fields) {
602 numfields = PySequence_Size(fields);
603 if (numfields == -1)
604 goto cleanup;
605 }
606 res = 0; /* if no error occurs, this stays 0 to the end */
607 if (PyTuple_GET_SIZE(args) > 0) {
608 if (numfields != PyTuple_GET_SIZE(args)) {
609 PyErr_Format(PyExc_TypeError, "%.400s constructor takes %s"
Benjamin Peterson75080da2008-09-10 22:37:34 +0000610 "%zd positional argument%s",
Neal Norwitz207c9f32008-03-31 04:42:11 +0000611 Py_TYPE(self)->tp_name,
612 numfields == 0 ? "" : "either 0 or ",
613 numfields, numfields == 1 ? "" : "s");
614 res = -1;
615 goto cleanup;
616 }
617 for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
618 /* cannot be reached when fields is NULL */
619 PyObject *name = PySequence_GetItem(fields, i);
620 if (!name) {
621 res = -1;
622 goto cleanup;
623 }
624 res = PyObject_SetAttr(self, name, PyTuple_GET_ITEM(args, i));
625 Py_DECREF(name);
626 if (res < 0)
627 goto cleanup;
628 }
629 }
630 if (kw) {
631 i = 0; /* needed by PyDict_Next */
632 while (PyDict_Next(kw, &i, &key, &value)) {
633 res = PyObject_SetAttr(self, key, value);
634 if (res < 0)
635 goto cleanup;
636 }
637 }
638 cleanup:
639 Py_XDECREF(fields);
640 return res;
641}
642
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000643/* Pickling support */
644static PyObject *
645ast_type_reduce(PyObject *self, PyObject *unused)
646{
647 PyObject *res;
648 PyObject *dict = PyObject_GetAttrString(self, "__dict__");
649 if (dict == NULL) {
650 if (PyErr_ExceptionMatches(PyExc_AttributeError))
651 PyErr_Clear();
652 else
653 return NULL;
654 }
655 if (dict) {
656 res = Py_BuildValue("O()O", Py_TYPE(self), dict);
657 Py_DECREF(dict);
658 return res;
659 }
660 return Py_BuildValue("O()", Py_TYPE(self));
661}
662
663static PyMethodDef ast_type_methods[] = {
664 {"__reduce__", ast_type_reduce, METH_NOARGS, NULL},
665 {NULL}
666};
667
Neal Norwitz207c9f32008-03-31 04:42:11 +0000668static PyTypeObject AST_type = {
669 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000670 "_ast.AST",
Neal Norwitz207c9f32008-03-31 04:42:11 +0000671 sizeof(PyObject),
672 0,
673 0, /* tp_dealloc */
674 0, /* tp_print */
675 0, /* tp_getattr */
676 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +0000677 0, /* tp_reserved */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000678 0, /* tp_repr */
679 0, /* tp_as_number */
680 0, /* tp_as_sequence */
681 0, /* tp_as_mapping */
682 0, /* tp_hash */
683 0, /* tp_call */
684 0, /* tp_str */
685 PyObject_GenericGetAttr, /* tp_getattro */
686 PyObject_GenericSetAttr, /* tp_setattro */
687 0, /* tp_as_buffer */
688 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
689 0, /* tp_doc */
690 0, /* tp_traverse */
691 0, /* tp_clear */
692 0, /* tp_richcompare */
693 0, /* tp_weaklistoffset */
694 0, /* tp_iter */
695 0, /* tp_iternext */
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000696 ast_type_methods, /* tp_methods */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000697 0, /* tp_members */
698 0, /* tp_getset */
699 0, /* tp_base */
700 0, /* tp_dict */
701 0, /* tp_descr_get */
702 0, /* tp_descr_set */
703 0, /* tp_dictoffset */
704 (initproc)ast_type_init, /* tp_init */
705 PyType_GenericAlloc, /* tp_alloc */
706 PyType_GenericNew, /* tp_new */
707 PyObject_Del, /* tp_free */
708};
709
710
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000711static PyTypeObject* make_type(char *type, PyTypeObject* base, char**fields, int num_fields)
712{
713 PyObject *fnames, *result;
714 int i;
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000715 fnames = PyTuple_New(num_fields);
716 if (!fnames) return NULL;
717 for (i = 0; i < num_fields; i++) {
Neal Norwitze4dc3242007-08-25 01:33:49 +0000718 PyObject *field = PyUnicode_FromString(fields[i]);
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000719 if (!field) {
720 Py_DECREF(fnames);
721 return NULL;
722 }
723 PyTuple_SET_ITEM(fnames, i, field);
724 }
Benjamin Peterson5b927722010-06-07 22:24:18 +0000725 result = PyObject_CallFunction((PyObject*)&PyType_Type, "s(O){sOss}",
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000726 type, base, "_fields", fnames, "__module__", "_ast");
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000727 Py_DECREF(fnames);
728 return (PyTypeObject*)result;
729}
730
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000731static int add_attributes(PyTypeObject* type, char**attrs, int num_fields)
732{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000733 int i, result;
Neal Norwitz207c9f32008-03-31 04:42:11 +0000734 PyObject *s, *l = PyTuple_New(num_fields);
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000735 if (!l)
736 return 0;
737 for (i = 0; i < num_fields; i++) {
Neal Norwitze4dc3242007-08-25 01:33:49 +0000738 s = PyUnicode_FromString(attrs[i]);
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000739 if (!s) {
740 Py_DECREF(l);
741 return 0;
742 }
Neal Norwitz207c9f32008-03-31 04:42:11 +0000743 PyTuple_SET_ITEM(l, i, s);
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000744 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000745 result = PyObject_SetAttrString((PyObject*)type, "_attributes", l) >= 0;
746 Py_DECREF(l);
747 return result;
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000748}
749
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000750/* Conversion AST -> Python */
751
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000752static PyObject* ast2obj_list(asdl_seq *seq, PyObject* (*func)(void*))
753{
754 int i, n = asdl_seq_LEN(seq);
755 PyObject *result = PyList_New(n);
756 PyObject *value;
757 if (!result)
758 return NULL;
759 for (i = 0; i < n; i++) {
760 value = func(asdl_seq_GET(seq, i));
761 if (!value) {
762 Py_DECREF(result);
763 return NULL;
764 }
765 PyList_SET_ITEM(result, i, value);
766 }
767 return result;
768}
769
770static PyObject* ast2obj_object(void *o)
771{
772 if (!o)
773 o = Py_None;
774 Py_INCREF((PyObject*)o);
775 return (PyObject*)o;
776}
777#define ast2obj_identifier ast2obj_object
778#define ast2obj_string ast2obj_object
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000779
Thomas Woutersa44f3a32007-02-26 18:20:15 +0000780static PyObject* ast2obj_int(long b)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000781{
Christian Heimes2b1c5922007-12-02 22:43:00 +0000782 return PyLong_FromLong(b);
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000783}
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000784
785/* Conversion Python -> AST */
786
787static int obj2ast_object(PyObject* obj, PyObject** out, PyArena* arena)
788{
789 if (obj == Py_None)
790 obj = NULL;
791 if (obj)
792 PyArena_AddPyObject(arena, obj);
793 Py_XINCREF(obj);
794 *out = obj;
795 return 0;
796}
797
798#define obj2ast_identifier obj2ast_object
799#define obj2ast_string obj2ast_object
800
801static int obj2ast_int(PyObject* obj, int* out, PyArena* arena)
802{
803 int i;
804 if (!PyLong_Check(obj)) {
805 PyObject *s = PyObject_Repr(obj);
806 if (s == NULL) return 1;
807 PyErr_Format(PyExc_ValueError, "invalid integer value: %.400s",
Christian Heimes72b710a2008-05-26 13:28:38 +0000808 PyBytes_AS_STRING(s));
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000809 Py_DECREF(s);
810 return 1;
811 }
812
813 i = (int)PyLong_AsLong(obj);
814 if (i == -1 && PyErr_Occurred())
815 return 1;
816 *out = i;
817 return 0;
818}
819
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +0000820static int add_ast_fields(void)
Benjamin Peterson206e3072008-10-19 14:07:49 +0000821{
822 PyObject *empty_tuple, *d;
823 if (PyType_Ready(&AST_type) < 0)
824 return -1;
825 d = AST_type.tp_dict;
826 empty_tuple = PyTuple_New(0);
827 if (!empty_tuple ||
828 PyDict_SetItemString(d, "_fields", empty_tuple) < 0 ||
829 PyDict_SetItemString(d, "_attributes", empty_tuple) < 0) {
830 Py_XDECREF(empty_tuple);
831 return -1;
832 }
833 Py_DECREF(empty_tuple);
834 return 0;
835}
836
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000837""", 0, reflow=False)
838
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000839 self.emit("static int init_types(void)",0)
840 self.emit("{", 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000841 self.emit("static int initialized;", 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000842 self.emit("if (initialized) return 1;", 1)
Benjamin Peterson206e3072008-10-19 14:07:49 +0000843 self.emit("if (add_ast_fields() < 0) return 0;", 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000844 for dfn in mod.dfns:
845 self.visit(dfn)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000846 self.emit("initialized = 1;", 1)
847 self.emit("return 1;", 1);
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000848 self.emit("}", 0)
849
850 def visitProduct(self, prod, name):
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000851 if prod.fields:
852 fields = name.value+"_fields"
853 else:
854 fields = "NULL"
Neal Norwitz207c9f32008-03-31 04:42:11 +0000855 self.emit('%s_type = make_type("%s", &AST_type, %s, %d);' %
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000856 (name, name, fields, len(prod.fields)), 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000857 self.emit("if (!%s_type) return 0;" % name, 1)
Tim Peters710ab3b2006-02-28 18:30:36 +0000858
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000859 def visitSum(self, sum, name):
Neal Norwitz207c9f32008-03-31 04:42:11 +0000860 self.emit('%s_type = make_type("%s", &AST_type, NULL, 0);' %
861 (name, name), 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000862 self.emit("if (!%s_type) return 0;" % name, 1)
863 if sum.attributes:
Tim Peters710ab3b2006-02-28 18:30:36 +0000864 self.emit("if (!add_attributes(%s_type, %s_attributes, %d)) return 0;" %
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000865 (name, name, len(sum.attributes)), 1)
866 else:
867 self.emit("if (!add_attributes(%s_type, NULL, 0)) return 0;" % name, 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000868 simple = is_simple(sum)
869 for t in sum.types:
870 self.visitConstructor(t, name, simple)
Tim Peters710ab3b2006-02-28 18:30:36 +0000871
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000872 def visitConstructor(self, cons, name, simple):
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000873 if cons.fields:
874 fields = cons.name.value+"_fields"
875 else:
876 fields = "NULL"
Tim Peters710ab3b2006-02-28 18:30:36 +0000877 self.emit('%s_type = make_type("%s", %s_type, %s, %d);' %
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000878 (cons.name, cons.name, name, fields, len(cons.fields)), 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000879 self.emit("if (!%s_type) return 0;" % cons.name, 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000880 if simple:
881 self.emit("%s_singleton = PyType_GenericNew(%s_type, NULL, NULL);" %
882 (cons.name, cons.name), 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000883 self.emit("if (!%s_singleton) return 0;" % cons.name, 1)
Tim Peters710ab3b2006-02-28 18:30:36 +0000884
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000885
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000886class ASTModuleVisitor(PickleVisitor):
887
888 def visitModule(self, mod):
Martin v. Löwis1a214512008-06-11 05:26:20 +0000889 self.emit("static struct PyModuleDef _astmodule = {", 0)
890 self.emit(' PyModuleDef_HEAD_INIT, "_ast"', 0)
891 self.emit("};", 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000892 self.emit("PyMODINIT_FUNC", 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000893 self.emit("PyInit__ast(void)", 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000894 self.emit("{", 0)
895 self.emit("PyObject *m, *d;", 1)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000896 self.emit("if (!init_types()) return NULL;", 1)
897 self.emit('m = PyModule_Create(&_astmodule);', 1)
898 self.emit("if (!m) return NULL;", 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000899 self.emit("d = PyModule_GetDict(m);", 1)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000900 self.emit('if (PyDict_SetItemString(d, "AST", (PyObject*)&AST_type) < 0) return NULL;', 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000901 self.emit('if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0)', 1)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000902 self.emit("return NULL;", 2)
Martin v. Löwis40d84592006-02-28 00:30:54 +0000903 # Value of version: "$Revision$"
Thomas Wouterscf297e42007-02-23 15:07:44 +0000904 self.emit('if (PyModule_AddStringConstant(m, "__version__", "%s") < 0)'
Benjamin Peterson6cb2b922011-03-12 18:28:16 -0600905 % (mod.version,), 1)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000906 self.emit("return NULL;", 2)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000907 for dfn in mod.dfns:
908 self.visit(dfn)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000909 self.emit("return m;", 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000910 self.emit("}", 0)
911
912 def visitProduct(self, prod, name):
913 self.addObj(name)
Tim Peters710ab3b2006-02-28 18:30:36 +0000914
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000915 def visitSum(self, sum, name):
916 self.addObj(name)
917 for t in sum.types:
918 self.visitConstructor(t, name)
Tim Peters710ab3b2006-02-28 18:30:36 +0000919
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000920 def visitConstructor(self, cons, name):
921 self.addObj(cons.name)
Tim Peters710ab3b2006-02-28 18:30:36 +0000922
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000923 def addObj(self, name):
Martin v. Löwis1a214512008-06-11 05:26:20 +0000924 self.emit('if (PyDict_SetItemString(d, "%s", (PyObject*)%s_type) < 0) return NULL;' % (name, name), 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000925
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000926
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000927_SPECIALIZED_SEQUENCES = ('stmt', 'expr')
928
929def find_sequence(fields, doing_specialization):
930 """Return True if any field uses a sequence."""
931 for f in fields:
932 if f.seq:
933 if not doing_specialization:
934 return True
935 if str(f.type) not in _SPECIALIZED_SEQUENCES:
936 return True
937 return False
938
939def has_sequence(types, doing_specialization):
940 for t in types:
941 if find_sequence(t.fields, doing_specialization):
942 return True
943 return False
944
945
946class StaticVisitor(PickleVisitor):
Neal Norwitz7b5a6042005-11-13 19:14:20 +0000947 CODE = '''Very simple, always emit this static code. Overide CODE'''
948
949 def visit(self, object):
950 self.emit(self.CODE, 0, reflow=False)
951
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000952
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000953class ObjVisitor(PickleVisitor):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000954
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000955 def func_begin(self, name):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000956 ctype = get_c_type(name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000957 self.emit("PyObject*", 0)
958 self.emit("ast2obj_%s(void* _o)" % (name), 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000959 self.emit("{", 0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000960 self.emit("%s o = (%s)_o;" % (ctype, ctype), 1)
961 self.emit("PyObject *result = NULL, *value = NULL;", 1)
962 self.emit('if (!o) {', 1)
963 self.emit("Py_INCREF(Py_None);", 2)
964 self.emit('return Py_None;', 2)
965 self.emit("}", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000966 self.emit('', 0)
967
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000968 def func_end(self):
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000969 self.emit("return result;", 1)
970 self.emit("failed:", 0)
971 self.emit("Py_XDECREF(value);", 1)
972 self.emit("Py_XDECREF(result);", 1)
973 self.emit("return NULL;", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000974 self.emit("}", 0)
975 self.emit("", 0)
976
977 def visitSum(self, sum, name):
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000978 if is_simple(sum):
979 self.simpleSum(sum, name)
980 return
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000981 self.func_begin(name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000982 self.emit("switch (o->kind) {", 1)
983 for i in range(len(sum.types)):
984 t = sum.types[i]
985 self.visitConstructor(t, i + 1, name)
986 self.emit("}", 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000987 for a in sum.attributes:
988 self.emit("value = ast2obj_%s(o->%s);" % (a.type, a.name), 1)
989 self.emit("if (!value) goto failed;", 1)
Martin v. Löwis03e5bc02006-03-02 00:31:27 +0000990 self.emit('if (PyObject_SetAttrString(result, "%s", value) < 0)' % a.name, 1)
991 self.emit('goto failed;', 2)
992 self.emit('Py_DECREF(value);', 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000993 self.func_end()
Tim Peters710ab3b2006-02-28 18:30:36 +0000994
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000995 def simpleSum(self, sum, name):
996 self.emit("PyObject* ast2obj_%s(%s_ty o)" % (name, name), 0)
997 self.emit("{", 0)
998 self.emit("switch(o) {", 1)
999 for t in sum.types:
1000 self.emit("case %s:" % t.name, 2)
1001 self.emit("Py_INCREF(%s_singleton);" % t.name, 3)
1002 self.emit("return %s_singleton;" % t.name, 3)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001003 self.emit("default:" % name, 2)
1004 self.emit('/* should never happen, but just in case ... */', 3)
1005 code = "PyErr_Format(PyExc_SystemError, \"unknown %s found\");" % name
1006 self.emit(code, 3, reflow=False)
1007 self.emit("return NULL;", 3)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001008 self.emit("}", 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001009 self.emit("}", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001010
1011 def visitProduct(self, prod, name):
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001012 self.func_begin(name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001013 self.emit("result = PyType_GenericNew(%s_type, NULL, NULL);" % name, 1);
1014 self.emit("if (!result) return NULL;", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001015 for field in prod.fields:
1016 self.visitField(field, name, 1, True)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001017 self.func_end()
Tim Peters536cf992005-12-25 23:18:31 +00001018
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001019 def visitConstructor(self, cons, enum, name):
1020 self.emit("case %s_kind:" % cons.name, 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001021 self.emit("result = PyType_GenericNew(%s_type, NULL, NULL);" % cons.name, 2);
1022 self.emit("if (!result) goto failed;", 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001023 for f in cons.fields:
1024 self.visitField(f, cons.name, 2, False)
1025 self.emit("break;", 2)
1026
1027 def visitField(self, field, name, depth, product):
1028 def emit(s, d):
1029 self.emit(s, depth + d)
1030 if product:
1031 value = "o->%s" % field.name
1032 else:
1033 value = "o->v.%s.%s" % (name, field.name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001034 self.set(field, value, depth)
1035 emit("if (!value) goto failed;", 0)
1036 emit('if (PyObject_SetAttrString(result, "%s", value) == -1)' % field.name, 0)
1037 emit("goto failed;", 1)
1038 emit("Py_DECREF(value);", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001039
1040 def emitSeq(self, field, value, depth, emit):
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001041 emit("seq = %s;" % value, 0)
1042 emit("n = asdl_seq_LEN(seq);", 0)
1043 emit("value = PyList_New(n);", 0)
1044 emit("if (!value) goto failed;", 0)
1045 emit("for (i = 0; i < n; i++) {", 0)
1046 self.set("value", field, "asdl_seq_GET(seq, i)", depth + 1)
1047 emit("if (!value1) goto failed;", 1)
1048 emit("PyList_SET_ITEM(value, i, value1);", 1)
1049 emit("value1 = NULL;", 1)
1050 emit("}", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001051
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001052 def set(self, field, value, depth):
1053 if field.seq:
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001054 # XXX should really check for is_simple, but that requires a symbol table
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001055 if field.type.value == "cmpop":
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001056 # While the sequence elements are stored as void*,
1057 # ast2obj_cmpop expects an enum
1058 self.emit("{", depth)
1059 self.emit("int i, n = asdl_seq_LEN(%s);" % value, depth+1)
1060 self.emit("value = PyList_New(n);", depth+1)
1061 self.emit("if (!value) goto failed;", depth+1)
1062 self.emit("for(i = 0; i < n; i++)", depth+1)
1063 # This cannot fail, so no need for error handling
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001064 self.emit("PyList_SET_ITEM(value, i, ast2obj_cmpop((cmpop_ty)asdl_seq_GET(%s, i)));" % value,
1065 depth+2, reflow=False)
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001066 self.emit("}", depth)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001067 else:
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001068 self.emit("value = ast2obj_list(%s, ast2obj_%s);" % (value, field.type), depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001069 else:
1070 ctype = get_c_type(field.type)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001071 self.emit("value = ast2obj_%s(%s);" % (field.type, value), depth, reflow=False)
Tim Peters536cf992005-12-25 23:18:31 +00001072
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001073
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001074class PartingShots(StaticVisitor):
1075
1076 CODE = """
1077PyObject* PyAST_mod2obj(mod_ty t)
1078{
1079 init_types();
1080 return ast2obj_mod(t);
1081}
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001082
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001083/* mode is 0 for "exec", 1 for "eval" and 2 for "single" input */
1084mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001085{
1086 mod_ty res;
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001087 PyObject *req_type[] = {(PyObject*)Module_type, (PyObject*)Expression_type,
1088 (PyObject*)Interactive_type};
1089 char *req_name[] = {"Module", "Expression", "Interactive"};
Benjamin Peterson97dd9872009-12-13 01:23:39 +00001090 int isinstance;
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001091 assert(0 <= mode && mode <= 2);
1092
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001093 init_types();
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001094
Benjamin Peterson97dd9872009-12-13 01:23:39 +00001095 isinstance = PyObject_IsInstance(ast, req_type[mode]);
1096 if (isinstance == -1)
1097 return NULL;
1098 if (!isinstance) {
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001099 PyErr_Format(PyExc_TypeError, "expected %s node, got %.400s",
1100 req_name[mode], Py_TYPE(ast)->tp_name);
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001101 return NULL;
1102 }
1103 if (obj2ast_mod(ast, &res, arena) != 0)
1104 return NULL;
1105 else
1106 return res;
1107}
1108
1109int PyAST_Check(PyObject* obj)
1110{
1111 init_types();
Neal Norwitz207c9f32008-03-31 04:42:11 +00001112 return PyObject_IsInstance(obj, (PyObject*)&AST_type);
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001113}
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001114"""
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001115
1116class ChainOfVisitors:
1117 def __init__(self, *visitors):
1118 self.visitors = visitors
1119
1120 def visit(self, object):
1121 for v in self.visitors:
1122 v.visit(object)
Neal Norwitz7b5a6042005-11-13 19:14:20 +00001123 v.emit("", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124
Guido van Rossum805365e2007-05-07 22:24:25 +00001125common_msg = "/* File automatically generated by %s. */\n\n"
Thomas Wouterscf297e42007-02-23 15:07:44 +00001126
1127c_file_msg = """
1128/*
1129 __version__ %s.
1130
1131 This module must be committed separately after each AST grammar change;
1132 The __version__ number is set to the revision number of the commit
1133 containing the grammar change.
1134*/
Guido van Rossum805365e2007-05-07 22:24:25 +00001135
Thomas Wouterscf297e42007-02-23 15:07:44 +00001136"""
1137
Benjamin Peterson6cb2b922011-03-12 18:28:16 -06001138
1139def get_file_revision(f):
1140 """Fish out the last change to a file in hg."""
Benjamin Petersonc9723d02011-03-13 16:36:08 -05001141 args = ["hg", "log", "--template", "{node|short}", "--limit", "1", f]
Benjamin Peterson6cb2b922011-03-12 18:28:16 -06001142 p = subprocess.Popen(args, stdout=subprocess.PIPE)
1143 out = p.communicate()[0]
1144 if p.returncode:
1145 print >> sys.stderr, "error return code from hg"
1146 sys.exit(1)
1147 return out
1148
1149
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150def main(srcfile):
Neal Norwitz897ff812005-12-11 21:18:22 +00001151 argv0 = sys.argv[0]
Armin Rigo6b1793f2005-12-14 18:05:14 +00001152 components = argv0.split(os.sep)
1153 argv0 = os.sep.join(components[-2:])
Thomas Wouterscf297e42007-02-23 15:07:44 +00001154 auto_gen_msg = common_msg % argv0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001155 mod = asdl.parse(srcfile)
1156 if not asdl.check(mod):
1157 sys.exit(1)
Benjamin Peterson6cb2b922011-03-12 18:28:16 -06001158 mod.version = get_file_revision(srcfile)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001159 if INC_DIR:
1160 p = "%s/%s-ast.h" % (INC_DIR, mod.name)
Guido van Rossum2af1d892007-11-23 21:26:49 +00001161 f = open(p, "w")
Guido van Rossum805365e2007-05-07 22:24:25 +00001162 f.write(auto_gen_msg)
1163 f.write('#include "asdl.h"\n\n')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001164 c = ChainOfVisitors(TypeDefVisitor(f),
1165 StructVisitor(f),
1166 PrototypeVisitor(f),
1167 )
1168 c.visit(mod)
Guido van Rossum805365e2007-05-07 22:24:25 +00001169 f.write("PyObject* PyAST_mod2obj(mod_ty t);\n")
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001170 f.write("mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode);\n")
1171 f.write("int PyAST_Check(PyObject* obj);\n")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001172 f.close()
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001173
1174 if SRC_DIR:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001175 p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c")
Guido van Rossum2af1d892007-11-23 21:26:49 +00001176 f = open(p, "w")
Guido van Rossum805365e2007-05-07 22:24:25 +00001177 f.write(auto_gen_msg)
Benjamin Peterson6cb2b922011-03-12 18:28:16 -06001178 f.write(c_file_msg % (mod.version,))
Guido van Rossum805365e2007-05-07 22:24:25 +00001179 f.write('#include "Python.h"\n')
1180 f.write('#include "%s-ast.h"\n' % mod.name)
1181 f.write('\n')
Neal Norwitz207c9f32008-03-31 04:42:11 +00001182 f.write("static PyTypeObject AST_type;\n")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001183 v = ChainOfVisitors(
1184 PyTypesDeclareVisitor(f),
1185 PyTypesVisitor(f),
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001186 Obj2ModPrototypeVisitor(f),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001187 FunctionVisitor(f),
1188 ObjVisitor(f),
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001189 Obj2ModVisitor(f),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001190 ASTModuleVisitor(f),
1191 PartingShots(f),
1192 )
1193 v.visit(mod)
1194 f.close()
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195
1196if __name__ == "__main__":
1197 import sys
1198 import getopt
1199
1200 INC_DIR = ''
1201 SRC_DIR = ''
1202 opts, args = getopt.getopt(sys.argv[1:], "h:c:")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001203 if len(opts) != 1:
Guido van Rossum805365e2007-05-07 22:24:25 +00001204 sys.stdout.write("Must specify exactly one output file\n")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001205 sys.exit(1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001206 for o, v in opts:
1207 if o == '-h':
1208 INC_DIR = v
1209 if o == '-c':
1210 SRC_DIR = v
1211 if len(args) != 1:
Guido van Rossum805365e2007-05-07 22:24:25 +00001212 sys.stdout.write("Must specify single input file\n")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001213 sys.exit(1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001214 main(args[0])