blob: 69583d914f63fe42ba231cabd31e42e87fdf6816 [file] [log] [blame]
Benjamin Petersonf51d36a2011-12-29 12:07:21 -06001#! /usr/bin/env python
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002"""Generate C code from an ASDL description."""
3
Benjamin Peterson5a3f49b2011-08-11 14:42:28 -05004import os, sys
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005
6import asdl
7
Victor Stinnerce72e1c2013-07-27 00:00:36 +02008TABSIZE = 4
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00009MAX_COL = 80
10
11def get_c_type(name):
12 """Return a string for the C name of the type.
13
Eli Bendersky5e3d3382014-05-09 17:58:22 -070014 This function special cases the default types provided by asdl.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000015 """
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000016 if name in asdl.builtin_types:
17 return name
18 else:
19 return "%s_ty" % name
20
21def reflow_lines(s, depth):
22 """Reflow the line s indented depth tabs.
23
24 Return a sequence of lines where no line extends beyond MAX_COL
25 when properly indented. The first line is properly indented based
26 exclusively on depth * TABSIZE. All following lines -- these are
27 the reflowed lines generated by this function -- start at the same
28 column as the first character beyond the opening { in the first
29 line.
30 """
31 size = MAX_COL - depth * TABSIZE
32 if len(s) < size:
33 return [s]
34
35 lines = []
36 cur = s
37 padding = ""
38 while len(cur) > size:
39 i = cur.rfind(' ', 0, size)
40 # XXX this should be fixed for real
41 if i == -1 and 'GeneratorExp' in cur:
42 i = size + 3
Brett Cannonf0365512006-08-25 04:06:31 +000043 assert i != -1, "Impossible line %d to reflow: %r" % (size, s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000044 lines.append(padding + cur[:i])
45 if len(lines) == 1:
46 # find new size based on brace
47 j = cur.find('{', 0, i)
48 if j >= 0:
49 j += 2 # account for the brace and the space after it
50 size -= j
51 padding = " " * j
52 else:
53 j = cur.find('(', 0, i)
54 if j >= 0:
55 j += 1 # account for the paren (no space after it)
56 size -= j
57 padding = " " * j
58 cur = cur[i+1:]
59 else:
60 lines.append(padding + cur)
61 return lines
62
63def is_simple(sum):
64 """Return True if a sum is a simple.
65
66 A sum is simple if its types have no fields, e.g.
67 unaryop = Invert | Not | UAdd | USub
68 """
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000069 for t in sum.types:
70 if t.fields:
71 return False
72 return True
73
Martin v. Löwis618dc5e2008-03-30 20:03:44 +000074
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075class EmitVisitor(asdl.VisitorBase):
76 """Visit that emits lines"""
77
78 def __init__(self, file):
79 self.file = file
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +020080 self.identifiers = set()
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000081 super(EmitVisitor, self).__init__()
82
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +020083 def emit_identifier(self, name):
84 name = str(name)
85 if name in self.identifiers:
86 return
Meador Inge70d86bd2011-10-22 14:06:50 -050087 self.emit("_Py_IDENTIFIER(%s);" % name, 0)
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +020088 self.identifiers.add(name)
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:
Serhiy Storchaka5d84cb32017-09-15 06:28:22 +030097 if line:
98 line = (" " * TABSIZE * depth) + line
99 self.file.write(line + "\n")
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000100
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000101
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000102class TypeDefVisitor(EmitVisitor):
103 def visitModule(self, mod):
104 for dfn in mod.dfns:
105 self.visit(dfn)
106
107 def visitType(self, type, depth=0):
108 self.visit(type.value, type.name, depth)
109
110 def visitSum(self, sum, name, depth):
111 if is_simple(sum):
112 self.simple_sum(sum, name, depth)
113 else:
114 self.sum_with_constructors(sum, name, depth)
115
116 def simple_sum(self, sum, name, depth):
117 enum = []
118 for i in range(len(sum.types)):
119 type = sum.types[i]
120 enum.append("%s=%d" % (type.name, i + 1))
121 enums = ", ".join(enum)
122 ctype = get_c_type(name)
123 s = "typedef enum _%s { %s } %s;" % (name, enums, ctype)
124 self.emit(s, depth)
125 self.emit("", depth)
126
127 def sum_with_constructors(self, sum, name, depth):
128 ctype = get_c_type(name)
129 s = "typedef struct _%(name)s *%(ctype)s;" % locals()
130 self.emit(s, depth)
131 self.emit("", depth)
132
133 def visitProduct(self, product, name, depth):
134 ctype = get_c_type(name)
135 s = "typedef struct _%(name)s *%(ctype)s;" % locals()
136 self.emit(s, depth)
137 self.emit("", depth)
138
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000139
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140class StructVisitor(EmitVisitor):
Eli Bendersky5e3d3382014-05-09 17:58:22 -0700141 """Visitor to generate typedefs for AST."""
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000142
143 def visitModule(self, mod):
144 for dfn in mod.dfns:
145 self.visit(dfn)
146
147 def visitType(self, type, depth=0):
148 self.visit(type.value, type.name, depth)
149
150 def visitSum(self, sum, name, depth):
151 if not is_simple(sum):
152 self.sum_with_constructors(sum, name, depth)
153
154 def sum_with_constructors(self, sum, name, depth):
155 def emit(s, depth=depth):
156 self.emit(s % sys._getframe(1).f_locals, depth)
157 enum = []
158 for i in range(len(sum.types)):
159 type = sum.types[i]
160 enum.append("%s_kind=%d" % (type.name, i + 1))
161
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000162 emit("enum _%(name)s_kind {" + ", ".join(enum) + "};")
163
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000164 emit("struct _%(name)s {")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000165 emit("enum _%(name)s_kind kind;", depth + 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000166 emit("union {", depth + 1)
167 for t in sum.types:
168 self.visit(t, depth + 2)
169 emit("} v;", depth + 1)
170 for field in sum.attributes:
171 # rudimentary attribute handling
172 type = str(field.type)
173 assert type in asdl.builtin_types, type
174 emit("%s %s;" % (type, field.name), depth + 1);
175 emit("};")
176 emit("")
177
178 def visitConstructor(self, cons, depth):
179 if cons.fields:
180 self.emit("struct {", depth)
181 for f in cons.fields:
182 self.visit(f, depth + 1)
183 self.emit("} %s;" % cons.name, depth)
184 self.emit("", depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185
186 def visitField(self, field, depth):
187 # XXX need to lookup field.type, because it might be something
188 # like a builtin...
189 ctype = get_c_type(field.type)
190 name = field.name
191 if field.seq:
Eli Bendersky5e3d3382014-05-09 17:58:22 -0700192 if field.type == 'cmpop':
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000193 self.emit("asdl_int_seq *%(name)s;" % locals(), depth)
194 else:
195 self.emit("asdl_seq *%(name)s;" % locals(), depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196 else:
197 self.emit("%(ctype)s %(name)s;" % locals(), depth)
198
199 def visitProduct(self, product, name, depth):
200 self.emit("struct _%(name)s {" % locals(), depth)
201 for f in product.fields:
202 self.visit(f, depth + 1)
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700203 for field in product.attributes:
204 # rudimentary attribute handling
205 type = str(field.type)
206 assert type in asdl.builtin_types, type
207 self.emit("%s %s;" % (type, field.name), depth + 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000208 self.emit("};", depth)
209 self.emit("", depth)
210
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000211
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000212class PrototypeVisitor(EmitVisitor):
213 """Generate function prototypes for the .h file"""
214
215 def visitModule(self, mod):
216 for dfn in mod.dfns:
217 self.visit(dfn)
218
219 def visitType(self, type):
220 self.visit(type.value, type.name)
221
222 def visitSum(self, sum, name):
223 if is_simple(sum):
224 pass # XXX
225 else:
226 for t in sum.types:
227 self.visit(t, name, sum.attributes)
228
229 def get_args(self, fields):
230 """Return list of C argument into, one for each field.
231
232 Argument info is 3-tuple of a C type, variable name, and flag
233 that is true if type can be NULL.
234 """
235 args = []
236 unnamed = {}
237 for f in fields:
238 if f.name is None:
239 name = f.type
240 c = unnamed[name] = unnamed.get(name, 0) + 1
241 if c > 1:
242 name = "name%d" % (c - 1)
243 else:
244 name = f.name
245 # XXX should extend get_c_type() to handle this
246 if f.seq:
Eli Bendersky5e3d3382014-05-09 17:58:22 -0700247 if f.type == 'cmpop':
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000248 ctype = "asdl_int_seq *"
249 else:
250 ctype = "asdl_seq *"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000251 else:
252 ctype = get_c_type(f.type)
253 args.append((ctype, name, f.opt or f.seq))
254 return args
255
256 def visitConstructor(self, cons, type, attrs):
257 args = self.get_args(cons.fields)
258 attrs = self.get_args(attrs)
259 ctype = get_c_type(type)
260 self.emit_function(cons.name, ctype, args, attrs)
261
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000262 def emit_function(self, name, ctype, args, attrs, union=True):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000263 args = args + attrs
264 if args:
265 argstr = ", ".join(["%s %s" % (atype, aname)
266 for atype, aname, opt in args])
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000267 argstr += ", PyArena *arena"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000268 else:
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000269 argstr = "PyArena *arena"
Thomas Woutersb2137042007-02-01 18:02:27 +0000270 margs = "a0"
271 for i in range(1, len(args)+1):
272 margs += ", a%d" % i
273 self.emit("#define %s(%s) _Py_%s(%s)" % (name, margs, name, margs), 0,
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000274 reflow=False)
275 self.emit("%s _Py_%s(%s);" % (ctype, name, argstr), False)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000276
277 def visitProduct(self, prod, name):
278 self.emit_function(name, get_c_type(name),
Victor Stinnerc106c682015-11-06 17:01:48 +0100279 self.get_args(prod.fields),
280 self.get_args(prod.attributes),
281 union=False)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000282
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000283
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000284class FunctionVisitor(PrototypeVisitor):
285 """Visitor to generate constructor functions for AST."""
286
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000287 def emit_function(self, name, ctype, args, attrs, union=True):
288 def emit(s, depth=0, reflow=True):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000289 self.emit(s, depth, reflow)
290 argstr = ", ".join(["%s %s" % (atype, aname)
291 for atype, aname, opt in args + attrs])
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000292 if argstr:
293 argstr += ", PyArena *arena"
294 else:
295 argstr = "PyArena *arena"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296 self.emit("%s" % ctype, 0)
297 emit("%s(%s)" % (name, argstr))
298 emit("{")
299 emit("%s p;" % ctype, 1)
300 for argtype, argname, opt in args:
Neal Norwitz3591bbe2007-02-26 19:04:49 +0000301 if not opt and argtype != "int":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000302 emit("if (!%s) {" % argname, 1)
303 emit("PyErr_SetString(PyExc_ValueError,", 2)
304 msg = "field %s is required for %s" % (argname, name)
305 emit(' "%s");' % msg,
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000306 2, reflow=False)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000307 emit('return NULL;', 2)
308 emit('}', 1)
309
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000310 emit("p = (%s)PyArena_Malloc(arena, sizeof(*p));" % ctype, 1);
Thomas Woutersa44f3a32007-02-26 18:20:15 +0000311 emit("if (!p)", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000312 emit("return NULL;", 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000313 if union:
314 self.emit_body_union(name, args, attrs)
315 else:
316 self.emit_body_struct(name, args, attrs)
317 emit("return p;", 1)
318 emit("}")
319 emit("")
320
321 def emit_body_union(self, name, args, attrs):
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000322 def emit(s, depth=0, reflow=True):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000323 self.emit(s, depth, reflow)
324 emit("p->kind = %s_kind;" % name, 1)
325 for argtype, argname, opt in args:
326 emit("p->v.%s.%s = %s;" % (name, argname, argname), 1)
327 for argtype, argname, opt in attrs:
328 emit("p->%s = %s;" % (argname, argname), 1)
329
330 def emit_body_struct(self, name, args, attrs):
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000331 def emit(s, depth=0, reflow=True):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000332 self.emit(s, depth, reflow)
333 for argtype, argname, opt in args:
334 emit("p->%s = %s;" % (argname, argname), 1)
Victor Stinnerc106c682015-11-06 17:01:48 +0100335 for argtype, argname, opt in attrs:
336 emit("p->%s = %s;" % (argname, argname), 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000337
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000338
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000339class PickleVisitor(EmitVisitor):
340
341 def visitModule(self, mod):
342 for dfn in mod.dfns:
343 self.visit(dfn)
344
345 def visitType(self, type):
346 self.visit(type.value, type.name)
347
348 def visitSum(self, sum, name):
349 pass
350
351 def visitProduct(self, sum, name):
352 pass
353
354 def visitConstructor(self, cons, name):
355 pass
356
357 def visitField(self, sum):
358 pass
359
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000360
361class Obj2ModPrototypeVisitor(PickleVisitor):
362 def visitProduct(self, prod, name):
363 code = "static int obj2ast_%s(PyObject* obj, %s* out, PyArena* arena);"
364 self.emit(code % (name, get_c_type(name)), 0)
365
366 visitSum = visitProduct
367
368
369class Obj2ModVisitor(PickleVisitor):
370 def funcHeader(self, name):
371 ctype = get_c_type(name)
372 self.emit("int", 0)
373 self.emit("obj2ast_%s(PyObject* obj, %s* out, PyArena* arena)" % (name, ctype), 0)
374 self.emit("{", 0)
Benjamin Peterson0e9e98e2010-11-20 02:01:45 +0000375 self.emit("int isinstance;", 1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000376 self.emit("", 0)
377
Benjamin Peterson5b066812010-11-20 01:38:49 +0000378 def sumTrailer(self, name, add_label=False):
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000379 self.emit("", 0)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000380 # there's really nothing more we can do if this fails ...
Benjamin Peterson5b066812010-11-20 01:38:49 +0000381 error = "expected some sort of %s, but got %%R" % name
382 format = "PyErr_Format(PyExc_TypeError, \"%s\", obj);"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000383 self.emit(format % error, 1, reflow=False)
Benjamin Peterson5b066812010-11-20 01:38:49 +0000384 if add_label:
385 self.emit("failed:", 1)
Benjamin Peterson0a4dae52010-11-21 15:12:34 +0000386 self.emit("Py_XDECREF(tmp);", 1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000387 self.emit("return 1;", 1)
388 self.emit("}", 0)
389 self.emit("", 0)
390
391 def simpleSum(self, sum, name):
392 self.funcHeader(name)
393 for t in sum.types:
Benjamin Peterson97dd9872009-12-13 01:23:39 +0000394 line = ("isinstance = PyObject_IsInstance(obj, "
395 "(PyObject *)%s_type);")
396 self.emit(line % (t.name,), 1)
397 self.emit("if (isinstance == -1) {", 1)
398 self.emit("return 1;", 2)
399 self.emit("}", 1)
400 self.emit("if (isinstance) {", 1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000401 self.emit("*out = %s;" % t.name, 2)
402 self.emit("return 0;", 2)
403 self.emit("}", 1)
404 self.sumTrailer(name)
405
406 def buildArgs(self, fields):
407 return ", ".join(fields + ["arena"])
408
409 def complexSum(self, sum, name):
410 self.funcHeader(name)
Benjamin Petersond8f65972010-11-20 04:31:07 +0000411 self.emit("PyObject *tmp = NULL;", 1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000412 for a in sum.attributes:
413 self.visitAttributeDeclaration(a, name, sum=sum)
414 self.emit("", 0)
415 # XXX: should we only do this for 'expr'?
416 self.emit("if (obj == Py_None) {", 1)
417 self.emit("*out = NULL;", 2)
418 self.emit("return 0;", 2)
419 self.emit("}", 1)
420 for a in sum.attributes:
421 self.visitField(a, name, sum=sum, depth=1)
422 for t in sum.types:
Benjamin Peterson97dd9872009-12-13 01:23:39 +0000423 line = "isinstance = PyObject_IsInstance(obj, (PyObject*)%s_type);"
424 self.emit(line % (t.name,), 1)
425 self.emit("if (isinstance == -1) {", 1)
426 self.emit("return 1;", 2)
427 self.emit("}", 1)
428 self.emit("if (isinstance) {", 1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000429 for f in t.fields:
430 self.visitFieldDeclaration(f, t.name, sum=sum, depth=2)
431 self.emit("", 0)
432 for f in t.fields:
433 self.visitField(f, t.name, sum=sum, depth=2)
Eli Bendersky5e3d3382014-05-09 17:58:22 -0700434 args = [f.name for f in t.fields] + [a.name for a in sum.attributes]
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000435 self.emit("*out = %s(%s);" % (t.name, self.buildArgs(args)), 2)
436 self.emit("if (*out == NULL) goto failed;", 2)
437 self.emit("return 0;", 2)
438 self.emit("}", 1)
Benjamin Peterson5b066812010-11-20 01:38:49 +0000439 self.sumTrailer(name, True)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000440
441 def visitAttributeDeclaration(self, a, name, sum=sum):
442 ctype = get_c_type(a.type)
443 self.emit("%s %s;" % (ctype, a.name), 1)
444
445 def visitSum(self, sum, name):
446 if is_simple(sum):
447 self.simpleSum(sum, name)
448 else:
449 self.complexSum(sum, name)
450
451 def visitProduct(self, prod, name):
452 ctype = get_c_type(name)
453 self.emit("int", 0)
454 self.emit("obj2ast_%s(PyObject* obj, %s* out, PyArena* arena)" % (name, ctype), 0)
455 self.emit("{", 0)
456 self.emit("PyObject* tmp = NULL;", 1)
457 for f in prod.fields:
458 self.visitFieldDeclaration(f, name, prod=prod, depth=1)
Victor Stinnerc106c682015-11-06 17:01:48 +0100459 for a in prod.attributes:
460 self.visitFieldDeclaration(a, name, prod=prod, depth=1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000461 self.emit("", 0)
462 for f in prod.fields:
463 self.visitField(f, name, prod=prod, depth=1)
Victor Stinnerc106c682015-11-06 17:01:48 +0100464 for a in prod.attributes:
465 self.visitField(a, name, prod=prod, depth=1)
Eli Bendersky5e3d3382014-05-09 17:58:22 -0700466 args = [f.name for f in prod.fields]
Victor Stinnerc106c682015-11-06 17:01:48 +0100467 args.extend([a.name for a in prod.attributes])
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000468 self.emit("*out = %s(%s);" % (name, self.buildArgs(args)), 1)
469 self.emit("return 0;", 1)
470 self.emit("failed:", 0)
471 self.emit("Py_XDECREF(tmp);", 1)
472 self.emit("return 1;", 1)
473 self.emit("}", 0)
474 self.emit("", 0)
475
476 def visitFieldDeclaration(self, field, name, sum=None, prod=None, depth=0):
477 ctype = get_c_type(field.type)
478 if field.seq:
479 if self.isSimpleType(field):
480 self.emit("asdl_int_seq* %s;" % field.name, depth)
481 else:
482 self.emit("asdl_seq* %s;" % field.name, depth)
483 else:
484 ctype = get_c_type(field.type)
485 self.emit("%s %s;" % (ctype, field.name), depth)
486
487 def isSimpleSum(self, field):
488 # XXX can the members of this list be determined automatically?
Eli Bendersky5e3d3382014-05-09 17:58:22 -0700489 return field.type in ('expr_context', 'boolop', 'operator',
490 'unaryop', 'cmpop')
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000491
492 def isNumeric(self, field):
493 return get_c_type(field.type) in ("int", "bool")
494
495 def isSimpleType(self, field):
496 return self.isSimpleSum(field) or self.isNumeric(field)
497
498 def visitField(self, field, name, sum=None, prod=None, depth=0):
499 ctype = get_c_type(field.type)
Serhiy Storchakabba22392017-11-11 16:41:32 +0200500 if not field.opt:
501 self.emit("tmp = _PyObject_GetAttrId(obj, &PyId_%s);" % field.name, depth)
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700502 else:
Serhiy Storchakabba22392017-11-11 16:41:32 +0200503 self.emit("tmp = get_not_none(obj, &PyId_%s);" % field.name, depth)
504 self.emit("if (tmp != NULL) {", depth)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000505 self.emit("int res;", depth+1)
506 if field.seq:
507 self.emit("Py_ssize_t len;", depth+1)
508 self.emit("Py_ssize_t i;", depth+1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000509 self.emit("if (!PyList_Check(tmp)) {", depth+1)
510 self.emit("PyErr_Format(PyExc_TypeError, \"%s field \\\"%s\\\" must "
511 "be a list, not a %%.200s\", tmp->ob_type->tp_name);" %
512 (name, field.name),
513 depth+2, reflow=False)
514 self.emit("goto failed;", depth+2)
515 self.emit("}", depth+1)
516 self.emit("len = PyList_GET_SIZE(tmp);", depth+1)
517 if self.isSimpleType(field):
Antoine Pitroud01d396e2013-10-12 22:52:43 +0200518 self.emit("%s = _Py_asdl_int_seq_new(len, arena);" % field.name, depth+1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000519 else:
Antoine Pitroud01d396e2013-10-12 22:52:43 +0200520 self.emit("%s = _Py_asdl_seq_new(len, arena);" % field.name, depth+1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000521 self.emit("if (%s == NULL) goto failed;" % field.name, depth+1)
522 self.emit("for (i = 0; i < len; i++) {", depth+1)
Yuan Chao Chou2af565b2017-08-04 10:53:12 -0700523 self.emit("%s val;" % ctype, depth+2)
524 self.emit("res = obj2ast_%s(PyList_GET_ITEM(tmp, i), &val, arena);" %
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000525 field.type, depth+2, reflow=False)
526 self.emit("if (res != 0) goto failed;", depth+2)
Serhiy Storchakacf380602016-10-07 21:51:28 +0300527 self.emit("if (len != PyList_GET_SIZE(tmp)) {", depth+2)
528 self.emit("PyErr_SetString(PyExc_RuntimeError, \"%s field \\\"%s\\\" "
529 "changed size during iteration\");" %
530 (name, field.name),
531 depth+3, reflow=False)
532 self.emit("goto failed;", depth+3)
533 self.emit("}", depth+2)
Yuan Chao Chou2af565b2017-08-04 10:53:12 -0700534 self.emit("asdl_seq_SET(%s, i, val);" % field.name, depth+2)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000535 self.emit("}", depth+1)
536 else:
537 self.emit("res = obj2ast_%s(tmp, &%s, arena);" %
538 (field.type, field.name), depth+1)
539 self.emit("if (res != 0) goto failed;", depth+1)
540
Victor Stinner1acc1292013-07-27 00:03:47 +0200541 self.emit("Py_CLEAR(tmp);", depth+1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000542 if not field.opt:
Serhiy Storchakabba22392017-11-11 16:41:32 +0200543 self.emit("} else {", depth)
544 self.emit("if (PyErr_ExceptionMatches(PyExc_AttributeError)) {", depth+1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000545 message = "required field \\\"%s\\\" missing from %s" % (field.name, name)
546 format = "PyErr_SetString(PyExc_TypeError, \"%s\");"
Serhiy Storchakabba22392017-11-11 16:41:32 +0200547 self.emit(format % message, depth+2, reflow=False)
548 self.emit("}", depth+1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000549 self.emit("return 1;", depth+1)
550 else:
Serhiy Storchakabba22392017-11-11 16:41:32 +0200551 self.emit("} else if (PyErr_Occurred()) {", depth)
552 self.emit("return 1;", depth+1)
553 self.emit("} else {", depth)
554
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000555 if self.isNumeric(field):
556 self.emit("%s = 0;" % field.name, depth+1)
557 elif not self.isSimpleType(field):
558 self.emit("%s = NULL;" % field.name, depth+1)
559 else:
560 raise TypeError("could not determine the default value for %s" % field.name)
561 self.emit("}", depth)
562
563
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000564class MarshalPrototypeVisitor(PickleVisitor):
565
566 def prototype(self, sum, name):
567 ctype = get_c_type(name)
Neal Norwitz6576bd82005-11-13 18:41:28 +0000568 self.emit("static int marshal_write_%s(PyObject **, int *, %s);"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000569 % (name, ctype), 0)
570
571 visitProduct = visitSum = prototype
572
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000573
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000574class PyTypesDeclareVisitor(PickleVisitor):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000575
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000576 def visitProduct(self, prod, name):
Neal Norwitz53d960c2006-02-28 22:47:29 +0000577 self.emit("static PyTypeObject *%s_type;" % name, 0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000578 self.emit("static PyObject* ast2obj_%s(void*);" % name, 0)
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700579 if prod.attributes:
580 for a in prod.attributes:
581 self.emit_identifier(a.name)
582 self.emit("static char *%s_attributes[] = {" % name, 0)
583 for a in prod.attributes:
584 self.emit('"%s",' % a.name, 1)
585 self.emit("};", 0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000586 if prod.fields:
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200587 for f in prod.fields:
588 self.emit_identifier(f.name)
Neal Norwitz53d960c2006-02-28 22:47:29 +0000589 self.emit("static char *%s_fields[]={" % name,0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000590 for f in prod.fields:
591 self.emit('"%s",' % f.name, 1)
592 self.emit("};", 0)
Tim Peters710ab3b2006-02-28 18:30:36 +0000593
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000594 def visitSum(self, sum, name):
Neal Norwitz53d960c2006-02-28 22:47:29 +0000595 self.emit("static PyTypeObject *%s_type;" % name, 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000596 if sum.attributes:
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200597 for a in sum.attributes:
598 self.emit_identifier(a.name)
Neal Norwitz53d960c2006-02-28 22:47:29 +0000599 self.emit("static char *%s_attributes[] = {" % name, 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000600 for a in sum.attributes:
601 self.emit('"%s",' % a.name, 1)
602 self.emit("};", 0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000603 ptype = "void*"
604 if is_simple(sum):
605 ptype = get_c_type(name)
606 tnames = []
607 for t in sum.types:
608 tnames.append(str(t.name)+"_singleton")
609 tnames = ", *".join(tnames)
610 self.emit("static PyObject *%s;" % tnames, 0)
611 self.emit("static PyObject* ast2obj_%s(%s);" % (name, ptype), 0)
612 for t in sum.types:
613 self.visitConstructor(t, name)
Tim Peters710ab3b2006-02-28 18:30:36 +0000614
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000615 def visitConstructor(self, cons, name):
Neal Norwitz53d960c2006-02-28 22:47:29 +0000616 self.emit("static PyTypeObject *%s_type;" % cons.name, 0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000617 if cons.fields:
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200618 for t in cons.fields:
619 self.emit_identifier(t.name)
Neal Norwitz53d960c2006-02-28 22:47:29 +0000620 self.emit("static char *%s_fields[]={" % cons.name, 0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000621 for t in cons.fields:
622 self.emit('"%s",' % t.name, 1)
623 self.emit("};",0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000624
625class PyTypesVisitor(PickleVisitor):
626
627 def visitModule(self, mod):
628 self.emit("""
INADA Naokifc489082017-01-25 22:33:43 +0900629_Py_IDENTIFIER(_fields);
630_Py_IDENTIFIER(_attributes);
631
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700632typedef struct {
Victor Stinner45e50de2012-03-13 01:17:31 +0100633 PyObject_HEAD
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700634 PyObject *dict;
635} AST_object;
636
Benjamin Peterson1767e022012-03-14 21:50:29 -0500637static void
638ast_dealloc(AST_object *self)
639{
INADA Naokia6296d32017-08-24 14:55:17 +0900640 /* bpo-31095: UnTrack is needed before calling any callbacks */
641 PyObject_GC_UnTrack(self);
Benjamin Peterson1767e022012-03-14 21:50:29 -0500642 Py_CLEAR(self->dict);
Antoine Pitrou50750742012-07-08 12:43:32 +0200643 Py_TYPE(self)->tp_free(self);
Benjamin Peterson1767e022012-03-14 21:50:29 -0500644}
645
Neal Norwitz207c9f32008-03-31 04:42:11 +0000646static int
Benjamin Peterson81071762012-07-08 11:03:46 -0700647ast_traverse(AST_object *self, visitproc visit, void *arg)
648{
649 Py_VISIT(self->dict);
650 return 0;
651}
652
653static void
654ast_clear(AST_object *self)
655{
656 Py_CLEAR(self->dict);
657}
658
659static int
Neal Norwitz207c9f32008-03-31 04:42:11 +0000660ast_type_init(PyObject *self, PyObject *args, PyObject *kw)
661{
662 Py_ssize_t i, numfields = 0;
663 int res = -1;
664 PyObject *key, *value, *fields;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200665 fields = _PyObject_GetAttrId((PyObject*)Py_TYPE(self), &PyId__fields);
Neal Norwitz207c9f32008-03-31 04:42:11 +0000666 if (fields) {
667 numfields = PySequence_Size(fields);
668 if (numfields == -1)
669 goto cleanup;
670 }
Serhiy Storchakabba22392017-11-11 16:41:32 +0200671 else if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
672 PyErr_Clear();
673 }
674 else {
675 goto cleanup;
676 }
INADA Naoki4c78c522017-02-24 02:48:17 +0900677
Neal Norwitz207c9f32008-03-31 04:42:11 +0000678 res = 0; /* if no error occurs, this stays 0 to the end */
INADA Naoki4c78c522017-02-24 02:48:17 +0900679 if (numfields < PyTuple_GET_SIZE(args)) {
680 PyErr_Format(PyExc_TypeError, "%.400s constructor takes at most "
681 "%zd positional argument%s",
682 Py_TYPE(self)->tp_name,
683 numfields, numfields == 1 ? "" : "s");
684 res = -1;
685 goto cleanup;
686 }
687 for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
688 /* cannot be reached when fields is NULL */
689 PyObject *name = PySequence_GetItem(fields, i);
690 if (!name) {
Neal Norwitz207c9f32008-03-31 04:42:11 +0000691 res = -1;
692 goto cleanup;
693 }
INADA Naoki4c78c522017-02-24 02:48:17 +0900694 res = PyObject_SetAttr(self, name, PyTuple_GET_ITEM(args, i));
695 Py_DECREF(name);
696 if (res < 0)
697 goto cleanup;
Neal Norwitz207c9f32008-03-31 04:42:11 +0000698 }
699 if (kw) {
700 i = 0; /* needed by PyDict_Next */
701 while (PyDict_Next(kw, &i, &key, &value)) {
702 res = PyObject_SetAttr(self, key, value);
703 if (res < 0)
704 goto cleanup;
705 }
706 }
707 cleanup:
708 Py_XDECREF(fields);
709 return res;
710}
711
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000712/* Pickling support */
713static PyObject *
714ast_type_reduce(PyObject *self, PyObject *unused)
715{
716 PyObject *res;
Meador Inge70d86bd2011-10-22 14:06:50 -0500717 _Py_IDENTIFIER(__dict__);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200718 PyObject *dict = _PyObject_GetAttrId(self, &PyId___dict__);
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000719 if (dict == NULL) {
720 if (PyErr_ExceptionMatches(PyExc_AttributeError))
721 PyErr_Clear();
722 else
723 return NULL;
724 }
725 if (dict) {
726 res = Py_BuildValue("O()O", Py_TYPE(self), dict);
727 Py_DECREF(dict);
728 return res;
729 }
730 return Py_BuildValue("O()", Py_TYPE(self));
731}
732
733static PyMethodDef ast_type_methods[] = {
734 {"__reduce__", ast_type_reduce, METH_NOARGS, NULL},
735 {NULL}
736};
737
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700738static PyGetSetDef ast_type_getsets[] = {
739 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
740 {NULL}
741};
742
Neal Norwitz207c9f32008-03-31 04:42:11 +0000743static PyTypeObject AST_type = {
744 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000745 "_ast.AST",
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700746 sizeof(AST_object),
Neal Norwitz207c9f32008-03-31 04:42:11 +0000747 0,
Benjamin Peterson1767e022012-03-14 21:50:29 -0500748 (destructor)ast_dealloc, /* tp_dealloc */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000749 0, /* tp_print */
750 0, /* tp_getattr */
751 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +0000752 0, /* tp_reserved */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000753 0, /* tp_repr */
754 0, /* tp_as_number */
755 0, /* tp_as_sequence */
756 0, /* tp_as_mapping */
757 0, /* tp_hash */
758 0, /* tp_call */
759 0, /* tp_str */
760 PyObject_GenericGetAttr, /* tp_getattro */
761 PyObject_GenericSetAttr, /* tp_setattro */
762 0, /* tp_as_buffer */
Benjamin Peterson81071762012-07-08 11:03:46 -0700763 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000764 0, /* tp_doc */
Benjamin Peterson81071762012-07-08 11:03:46 -0700765 (traverseproc)ast_traverse, /* tp_traverse */
766 (inquiry)ast_clear, /* tp_clear */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000767 0, /* tp_richcompare */
768 0, /* tp_weaklistoffset */
769 0, /* tp_iter */
770 0, /* tp_iternext */
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000771 ast_type_methods, /* tp_methods */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000772 0, /* tp_members */
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700773 ast_type_getsets, /* tp_getset */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000774 0, /* tp_base */
775 0, /* tp_dict */
776 0, /* tp_descr_get */
777 0, /* tp_descr_set */
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700778 offsetof(AST_object, dict),/* tp_dictoffset */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000779 (initproc)ast_type_init, /* tp_init */
780 PyType_GenericAlloc, /* tp_alloc */
781 PyType_GenericNew, /* tp_new */
Benjamin Peterson81071762012-07-08 11:03:46 -0700782 PyObject_GC_Del, /* tp_free */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000783};
784
785
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000786static PyTypeObject* make_type(char *type, PyTypeObject* base, char**fields, int num_fields)
787{
INADA Naokifc489082017-01-25 22:33:43 +0900788 _Py_IDENTIFIER(__module__);
789 _Py_IDENTIFIER(_ast);
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000790 PyObject *fnames, *result;
791 int i;
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000792 fnames = PyTuple_New(num_fields);
793 if (!fnames) return NULL;
794 for (i = 0; i < num_fields; i++) {
Neal Norwitze4dc3242007-08-25 01:33:49 +0000795 PyObject *field = PyUnicode_FromString(fields[i]);
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000796 if (!field) {
797 Py_DECREF(fnames);
798 return NULL;
799 }
800 PyTuple_SET_ITEM(fnames, i, field);
801 }
INADA Naokifc489082017-01-25 22:33:43 +0900802 result = PyObject_CallFunction((PyObject*)&PyType_Type, "s(O){OOOO}",
803 type, base,
804 _PyUnicode_FromId(&PyId__fields), fnames,
805 _PyUnicode_FromId(&PyId___module__),
806 _PyUnicode_FromId(&PyId__ast));
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000807 Py_DECREF(fnames);
808 return (PyTypeObject*)result;
809}
810
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000811static int add_attributes(PyTypeObject* type, char**attrs, int num_fields)
812{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000813 int i, result;
Neal Norwitz207c9f32008-03-31 04:42:11 +0000814 PyObject *s, *l = PyTuple_New(num_fields);
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000815 if (!l)
816 return 0;
817 for (i = 0; i < num_fields; i++) {
Neal Norwitze4dc3242007-08-25 01:33:49 +0000818 s = PyUnicode_FromString(attrs[i]);
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000819 if (!s) {
820 Py_DECREF(l);
821 return 0;
822 }
Neal Norwitz207c9f32008-03-31 04:42:11 +0000823 PyTuple_SET_ITEM(l, i, s);
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000824 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200825 result = _PyObject_SetAttrId((PyObject*)type, &PyId__attributes, l) >= 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000826 Py_DECREF(l);
827 return result;
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000828}
829
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000830/* Conversion AST -> Python */
831
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000832static PyObject* ast2obj_list(asdl_seq *seq, PyObject* (*func)(void*))
833{
Benjamin Peterson77fa9372012-05-15 10:10:27 -0700834 Py_ssize_t i, n = asdl_seq_LEN(seq);
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000835 PyObject *result = PyList_New(n);
836 PyObject *value;
837 if (!result)
838 return NULL;
839 for (i = 0; i < n; i++) {
840 value = func(asdl_seq_GET(seq, i));
841 if (!value) {
842 Py_DECREF(result);
843 return NULL;
844 }
845 PyList_SET_ITEM(result, i, value);
846 }
847 return result;
848}
849
850static PyObject* ast2obj_object(void *o)
851{
852 if (!o)
853 o = Py_None;
854 Py_INCREF((PyObject*)o);
855 return (PyObject*)o;
856}
Benjamin Peterson442f2092012-12-06 17:41:04 -0500857#define ast2obj_singleton ast2obj_object
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100858#define ast2obj_constant ast2obj_object
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000859#define ast2obj_identifier ast2obj_object
860#define ast2obj_string ast2obj_object
Benjamin Petersone2498412011-08-09 16:08:39 -0500861#define ast2obj_bytes ast2obj_object
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000862
Thomas Woutersa44f3a32007-02-26 18:20:15 +0000863static PyObject* ast2obj_int(long b)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000864{
Christian Heimes2b1c5922007-12-02 22:43:00 +0000865 return PyLong_FromLong(b);
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000866}
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000867
868/* Conversion Python -> AST */
869
Benjamin Peterson442f2092012-12-06 17:41:04 -0500870static int obj2ast_singleton(PyObject *obj, PyObject** out, PyArena* arena)
871{
872 if (obj != Py_None && obj != Py_True && obj != Py_False) {
873 PyErr_SetString(PyExc_ValueError,
874 "AST singleton must be True, False, or None");
875 return 1;
876 }
877 *out = obj;
878 return 0;
879}
880
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000881static int obj2ast_object(PyObject* obj, PyObject** out, PyArena* arena)
882{
883 if (obj == Py_None)
884 obj = NULL;
Christian Heimes70c94e72013-07-27 00:33:13 +0200885 if (obj) {
886 if (PyArena_AddPyObject(arena, obj) < 0) {
887 *out = NULL;
888 return -1;
889 }
890 Py_INCREF(obj);
891 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000892 *out = obj;
893 return 0;
894}
895
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100896static int obj2ast_constant(PyObject* obj, PyObject** out, PyArena* arena)
897{
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100898 if (obj) {
899 if (PyArena_AddPyObject(arena, obj) < 0) {
900 *out = NULL;
901 return -1;
902 }
903 Py_INCREF(obj);
904 }
905 *out = obj;
906 return 0;
907}
908
Benjamin Peterson180e6352011-07-22 11:09:07 -0500909static int obj2ast_identifier(PyObject* obj, PyObject** out, PyArena* arena)
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500910{
Benjamin Peterson180e6352011-07-22 11:09:07 -0500911 if (!PyUnicode_CheckExact(obj) && obj != Py_None) {
912 PyErr_SetString(PyExc_TypeError, "AST identifier must be of type str");
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500913 return 1;
914 }
915 return obj2ast_object(obj, out, arena);
916}
917
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500918static int obj2ast_string(PyObject* obj, PyObject** out, PyArena* arena)
919{
Benjamin Peterson0224d4e2011-08-31 22:13:03 -0400920 if (!PyUnicode_CheckExact(obj) && !PyBytes_CheckExact(obj)) {
Benjamin Peterson180e6352011-07-22 11:09:07 -0500921 PyErr_SetString(PyExc_TypeError, "AST string must be of type str");
922 return 1;
923 }
924 return obj2ast_object(obj, out, arena);
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500925}
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000926
Benjamin Petersone2498412011-08-09 16:08:39 -0500927static int obj2ast_bytes(PyObject* obj, PyObject** out, PyArena* arena)
928{
929 if (!PyBytes_CheckExact(obj)) {
930 PyErr_SetString(PyExc_TypeError, "AST bytes must be of type bytes");
931 return 1;
932 }
933 return obj2ast_object(obj, out, arena);
934}
935
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000936static int obj2ast_int(PyObject* obj, int* out, PyArena* arena)
937{
938 int i;
939 if (!PyLong_Check(obj)) {
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100940 PyErr_Format(PyExc_ValueError, "invalid integer value: %R", obj);
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000941 return 1;
942 }
943
Serhiy Storchaka481d3af2015-09-06 23:29:04 +0300944 i = _PyLong_AsInt(obj);
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000945 if (i == -1 && PyErr_Occurred())
946 return 1;
947 *out = i;
948 return 0;
949}
950
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +0000951static int add_ast_fields(void)
Benjamin Peterson206e3072008-10-19 14:07:49 +0000952{
953 PyObject *empty_tuple, *d;
954 if (PyType_Ready(&AST_type) < 0)
955 return -1;
956 d = AST_type.tp_dict;
957 empty_tuple = PyTuple_New(0);
958 if (!empty_tuple ||
INADA Naokifc489082017-01-25 22:33:43 +0900959 _PyDict_SetItemId(d, &PyId__fields, empty_tuple) < 0 ||
960 _PyDict_SetItemId(d, &PyId__attributes, empty_tuple) < 0) {
Benjamin Peterson206e3072008-10-19 14:07:49 +0000961 Py_XDECREF(empty_tuple);
962 return -1;
963 }
964 Py_DECREF(empty_tuple);
965 return 0;
966}
967
Serhiy Storchakabba22392017-11-11 16:41:32 +0200968static PyObject *get_not_none(PyObject *obj, _Py_Identifier *id)
Benjamin Petersonb72406b2013-03-18 23:24:41 -0700969{
970 PyObject *attr = _PyObject_GetAttrId(obj, id);
971 if (!attr) {
Serhiy Storchakabba22392017-11-11 16:41:32 +0200972 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
973 PyErr_Clear();
974 }
975 return NULL;
Benjamin Petersonb72406b2013-03-18 23:24:41 -0700976 }
Serhiy Storchakabba22392017-11-11 16:41:32 +0200977 else if (attr == Py_None) {
978 Py_DECREF(attr);
979 return NULL;
980 }
981 return attr;
Benjamin Petersonb72406b2013-03-18 23:24:41 -0700982}
983
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000984""", 0, reflow=False)
985
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000986 self.emit("static int init_types(void)",0)
987 self.emit("{", 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000988 self.emit("static int initialized;", 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000989 self.emit("if (initialized) return 1;", 1)
Benjamin Peterson206e3072008-10-19 14:07:49 +0000990 self.emit("if (add_ast_fields() < 0) return 0;", 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000991 for dfn in mod.dfns:
992 self.visit(dfn)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000993 self.emit("initialized = 1;", 1)
994 self.emit("return 1;", 1);
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000995 self.emit("}", 0)
996
997 def visitProduct(self, prod, name):
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000998 if prod.fields:
Eli Bendersky5e3d3382014-05-09 17:58:22 -0700999 fields = name+"_fields"
Martin v. Löwis8d0701d2006-02-26 23:40:20 +00001000 else:
1001 fields = "NULL"
Neal Norwitz207c9f32008-03-31 04:42:11 +00001002 self.emit('%s_type = make_type("%s", &AST_type, %s, %d);' %
Martin v. Löwis8d0701d2006-02-26 23:40:20 +00001003 (name, name, fields, len(prod.fields)), 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001004 self.emit("if (!%s_type) return 0;" % name, 1)
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001005 if prod.attributes:
1006 self.emit("if (!add_attributes(%s_type, %s_attributes, %d)) return 0;" %
1007 (name, name, len(prod.attributes)), 1)
1008 else:
1009 self.emit("if (!add_attributes(%s_type, NULL, 0)) return 0;" % name, 1)
Tim Peters710ab3b2006-02-28 18:30:36 +00001010
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001011 def visitSum(self, sum, name):
Neal Norwitz207c9f32008-03-31 04:42:11 +00001012 self.emit('%s_type = make_type("%s", &AST_type, NULL, 0);' %
1013 (name, name), 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001014 self.emit("if (!%s_type) return 0;" % name, 1)
1015 if sum.attributes:
Tim Peters710ab3b2006-02-28 18:30:36 +00001016 self.emit("if (!add_attributes(%s_type, %s_attributes, %d)) return 0;" %
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001017 (name, name, len(sum.attributes)), 1)
1018 else:
1019 self.emit("if (!add_attributes(%s_type, NULL, 0)) return 0;" % name, 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001020 simple = is_simple(sum)
1021 for t in sum.types:
1022 self.visitConstructor(t, name, simple)
Tim Peters710ab3b2006-02-28 18:30:36 +00001023
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001024 def visitConstructor(self, cons, name, simple):
Martin v. Löwis8d0701d2006-02-26 23:40:20 +00001025 if cons.fields:
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001026 fields = cons.name+"_fields"
Martin v. Löwis8d0701d2006-02-26 23:40:20 +00001027 else:
1028 fields = "NULL"
Tim Peters710ab3b2006-02-28 18:30:36 +00001029 self.emit('%s_type = make_type("%s", %s_type, %s, %d);' %
Martin v. Löwis8d0701d2006-02-26 23:40:20 +00001030 (cons.name, cons.name, name, fields, len(cons.fields)), 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001031 self.emit("if (!%s_type) return 0;" % cons.name, 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001032 if simple:
1033 self.emit("%s_singleton = PyType_GenericNew(%s_type, NULL, NULL);" %
1034 (cons.name, cons.name), 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001035 self.emit("if (!%s_singleton) return 0;" % cons.name, 1)
Tim Peters710ab3b2006-02-28 18:30:36 +00001036
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001037
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001038class ASTModuleVisitor(PickleVisitor):
1039
1040 def visitModule(self, mod):
Martin v. Löwis1a214512008-06-11 05:26:20 +00001041 self.emit("static struct PyModuleDef _astmodule = {", 0)
1042 self.emit(' PyModuleDef_HEAD_INIT, "_ast"', 0)
1043 self.emit("};", 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001044 self.emit("PyMODINIT_FUNC", 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001045 self.emit("PyInit__ast(void)", 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001046 self.emit("{", 0)
1047 self.emit("PyObject *m, *d;", 1)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001048 self.emit("if (!init_types()) return NULL;", 1)
1049 self.emit('m = PyModule_Create(&_astmodule);', 1)
1050 self.emit("if (!m) return NULL;", 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001051 self.emit("d = PyModule_GetDict(m);", 1)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001052 self.emit('if (PyDict_SetItemString(d, "AST", (PyObject*)&AST_type) < 0) return NULL;', 1)
Benjamin Peterson8d89c2a2013-05-20 10:28:48 -07001053 self.emit('if (PyModule_AddIntMacro(m, PyCF_ONLY_AST) < 0)', 1)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001054 self.emit("return NULL;", 2)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001055 for dfn in mod.dfns:
1056 self.visit(dfn)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001057 self.emit("return m;", 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001058 self.emit("}", 0)
1059
1060 def visitProduct(self, prod, name):
1061 self.addObj(name)
Tim Peters710ab3b2006-02-28 18:30:36 +00001062
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001063 def visitSum(self, sum, name):
1064 self.addObj(name)
1065 for t in sum.types:
1066 self.visitConstructor(t, name)
Tim Peters710ab3b2006-02-28 18:30:36 +00001067
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001068 def visitConstructor(self, cons, name):
1069 self.addObj(cons.name)
Tim Peters710ab3b2006-02-28 18:30:36 +00001070
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001071 def addObj(self, name):
Martin v. Löwis1a214512008-06-11 05:26:20 +00001072 self.emit('if (PyDict_SetItemString(d, "%s", (PyObject*)%s_type) < 0) return NULL;' % (name, name), 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001073
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001074
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001075_SPECIALIZED_SEQUENCES = ('stmt', 'expr')
1076
1077def find_sequence(fields, doing_specialization):
1078 """Return True if any field uses a sequence."""
1079 for f in fields:
1080 if f.seq:
1081 if not doing_specialization:
1082 return True
1083 if str(f.type) not in _SPECIALIZED_SEQUENCES:
1084 return True
1085 return False
1086
1087def has_sequence(types, doing_specialization):
1088 for t in types:
1089 if find_sequence(t.fields, doing_specialization):
1090 return True
1091 return False
1092
1093
1094class StaticVisitor(PickleVisitor):
Ezio Melotti7c4a7e62013-08-26 01:32:56 +03001095 CODE = '''Very simple, always emit this static code. Override CODE'''
Neal Norwitz7b5a6042005-11-13 19:14:20 +00001096
1097 def visit(self, object):
1098 self.emit(self.CODE, 0, reflow=False)
1099
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001100
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001101class ObjVisitor(PickleVisitor):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001102
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001103 def func_begin(self, name):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001104 ctype = get_c_type(name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001105 self.emit("PyObject*", 0)
1106 self.emit("ast2obj_%s(void* _o)" % (name), 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001107 self.emit("{", 0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001108 self.emit("%s o = (%s)_o;" % (ctype, ctype), 1)
1109 self.emit("PyObject *result = NULL, *value = NULL;", 1)
1110 self.emit('if (!o) {', 1)
INADA Naokifc489082017-01-25 22:33:43 +09001111 self.emit("Py_RETURN_NONE;", 2)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001112 self.emit("}", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001113 self.emit('', 0)
1114
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001115 def func_end(self):
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001116 self.emit("return result;", 1)
1117 self.emit("failed:", 0)
1118 self.emit("Py_XDECREF(value);", 1)
1119 self.emit("Py_XDECREF(result);", 1)
1120 self.emit("return NULL;", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001121 self.emit("}", 0)
1122 self.emit("", 0)
1123
1124 def visitSum(self, sum, name):
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001125 if is_simple(sum):
1126 self.simpleSum(sum, name)
1127 return
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001128 self.func_begin(name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001129 self.emit("switch (o->kind) {", 1)
1130 for i in range(len(sum.types)):
1131 t = sum.types[i]
1132 self.visitConstructor(t, i + 1, name)
1133 self.emit("}", 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001134 for a in sum.attributes:
1135 self.emit("value = ast2obj_%s(o->%s);" % (a.type, a.name), 1)
1136 self.emit("if (!value) goto failed;", 1)
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001137 self.emit('if (_PyObject_SetAttrId(result, &PyId_%s, value) < 0)' % a.name, 1)
Martin v. Löwis03e5bc02006-03-02 00:31:27 +00001138 self.emit('goto failed;', 2)
1139 self.emit('Py_DECREF(value);', 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001140 self.func_end()
Tim Peters710ab3b2006-02-28 18:30:36 +00001141
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001142 def simpleSum(self, sum, name):
1143 self.emit("PyObject* ast2obj_%s(%s_ty o)" % (name, name), 0)
1144 self.emit("{", 0)
1145 self.emit("switch(o) {", 1)
1146 for t in sum.types:
1147 self.emit("case %s:" % t.name, 2)
1148 self.emit("Py_INCREF(%s_singleton);" % t.name, 3)
1149 self.emit("return %s_singleton;" % t.name, 3)
Ezio Melotticb2916a2012-09-30 22:41:37 +03001150 self.emit("default:", 2)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001151 self.emit('/* should never happen, but just in case ... */', 3)
1152 code = "PyErr_Format(PyExc_SystemError, \"unknown %s found\");" % name
1153 self.emit(code, 3, reflow=False)
1154 self.emit("return NULL;", 3)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001155 self.emit("}", 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001156 self.emit("}", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001157
1158 def visitProduct(self, prod, name):
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001159 self.func_begin(name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001160 self.emit("result = PyType_GenericNew(%s_type, NULL, NULL);" % name, 1);
1161 self.emit("if (!result) return NULL;", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162 for field in prod.fields:
1163 self.visitField(field, name, 1, True)
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001164 for a in prod.attributes:
1165 self.emit("value = ast2obj_%s(o->%s);" % (a.type, a.name), 1)
1166 self.emit("if (!value) goto failed;", 1)
1167 self.emit('if (_PyObject_SetAttrId(result, &PyId_%s, value) < 0)' % a.name, 1)
1168 self.emit('goto failed;', 2)
1169 self.emit('Py_DECREF(value);', 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001170 self.func_end()
Tim Peters536cf992005-12-25 23:18:31 +00001171
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001172 def visitConstructor(self, cons, enum, name):
1173 self.emit("case %s_kind:" % cons.name, 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001174 self.emit("result = PyType_GenericNew(%s_type, NULL, NULL);" % cons.name, 2);
1175 self.emit("if (!result) goto failed;", 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001176 for f in cons.fields:
1177 self.visitField(f, cons.name, 2, False)
1178 self.emit("break;", 2)
1179
1180 def visitField(self, field, name, depth, product):
1181 def emit(s, d):
1182 self.emit(s, depth + d)
1183 if product:
1184 value = "o->%s" % field.name
1185 else:
1186 value = "o->v.%s.%s" % (name, field.name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001187 self.set(field, value, depth)
1188 emit("if (!value) goto failed;", 0)
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001189 emit('if (_PyObject_SetAttrId(result, &PyId_%s, value) == -1)' % field.name, 0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001190 emit("goto failed;", 1)
1191 emit("Py_DECREF(value);", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001192
1193 def emitSeq(self, field, value, depth, emit):
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001194 emit("seq = %s;" % value, 0)
1195 emit("n = asdl_seq_LEN(seq);", 0)
1196 emit("value = PyList_New(n);", 0)
1197 emit("if (!value) goto failed;", 0)
1198 emit("for (i = 0; i < n; i++) {", 0)
1199 self.set("value", field, "asdl_seq_GET(seq, i)", depth + 1)
1200 emit("if (!value1) goto failed;", 1)
1201 emit("PyList_SET_ITEM(value, i, value1);", 1)
1202 emit("value1 = NULL;", 1)
1203 emit("}", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001204
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001205 def set(self, field, value, depth):
1206 if field.seq:
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001207 # XXX should really check for is_simple, but that requires a symbol table
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001208 if field.type == "cmpop":
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001209 # While the sequence elements are stored as void*,
1210 # ast2obj_cmpop expects an enum
1211 self.emit("{", depth)
Benjamin Peterson77fa9372012-05-15 10:10:27 -07001212 self.emit("Py_ssize_t i, n = asdl_seq_LEN(%s);" % value, depth+1)
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001213 self.emit("value = PyList_New(n);", depth+1)
1214 self.emit("if (!value) goto failed;", depth+1)
1215 self.emit("for(i = 0; i < n; i++)", depth+1)
1216 # This cannot fail, so no need for error handling
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001217 self.emit("PyList_SET_ITEM(value, i, ast2obj_cmpop((cmpop_ty)asdl_seq_GET(%s, i)));" % value,
1218 depth+2, reflow=False)
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001219 self.emit("}", depth)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001220 else:
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001221 self.emit("value = ast2obj_list(%s, ast2obj_%s);" % (value, field.type), depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001222 else:
1223 ctype = get_c_type(field.type)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001224 self.emit("value = ast2obj_%s(%s);" % (field.type, value), depth, reflow=False)
Tim Peters536cf992005-12-25 23:18:31 +00001225
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001226
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001227class PartingShots(StaticVisitor):
1228
1229 CODE = """
1230PyObject* PyAST_mod2obj(mod_ty t)
1231{
Victor Stinnerbdf630c2013-07-17 00:17:15 +02001232 if (!init_types())
1233 return NULL;
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001234 return ast2obj_mod(t);
1235}
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001236
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001237/* mode is 0 for "exec", 1 for "eval" and 2 for "single" input */
1238mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001239{
1240 mod_ty res;
Benjamin Petersonc2f665e2014-02-10 22:19:02 -05001241 PyObject *req_type[3];
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001242 char *req_name[] = {"Module", "Expression", "Interactive"};
Benjamin Peterson97dd9872009-12-13 01:23:39 +00001243 int isinstance;
Benjamin Petersonc2f665e2014-02-10 22:19:02 -05001244
1245 req_type[0] = (PyObject*)Module_type;
1246 req_type[1] = (PyObject*)Expression_type;
1247 req_type[2] = (PyObject*)Interactive_type;
1248
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001249 assert(0 <= mode && mode <= 2);
1250
Victor Stinnerbdf630c2013-07-17 00:17:15 +02001251 if (!init_types())
1252 return NULL;
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001253
Benjamin Peterson97dd9872009-12-13 01:23:39 +00001254 isinstance = PyObject_IsInstance(ast, req_type[mode]);
1255 if (isinstance == -1)
1256 return NULL;
1257 if (!isinstance) {
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001258 PyErr_Format(PyExc_TypeError, "expected %s node, got %.400s",
1259 req_name[mode], Py_TYPE(ast)->tp_name);
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001260 return NULL;
1261 }
1262 if (obj2ast_mod(ast, &res, arena) != 0)
1263 return NULL;
1264 else
1265 return res;
1266}
1267
1268int PyAST_Check(PyObject* obj)
1269{
Victor Stinnerbdf630c2013-07-17 00:17:15 +02001270 if (!init_types())
1271 return -1;
Neal Norwitz207c9f32008-03-31 04:42:11 +00001272 return PyObject_IsInstance(obj, (PyObject*)&AST_type);
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001273}
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001274"""
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001275
1276class ChainOfVisitors:
1277 def __init__(self, *visitors):
1278 self.visitors = visitors
1279
1280 def visit(self, object):
1281 for v in self.visitors:
1282 v.visit(object)
Neal Norwitz7b5a6042005-11-13 19:14:20 +00001283 v.emit("", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001284
Guido van Rossum805365e2007-05-07 22:24:25 +00001285common_msg = "/* File automatically generated by %s. */\n\n"
Thomas Wouterscf297e42007-02-23 15:07:44 +00001286
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001287def main(srcfile, dump_module=False):
Neal Norwitz897ff812005-12-11 21:18:22 +00001288 argv0 = sys.argv[0]
Armin Rigo6b1793f2005-12-14 18:05:14 +00001289 components = argv0.split(os.sep)
1290 argv0 = os.sep.join(components[-2:])
Thomas Wouterscf297e42007-02-23 15:07:44 +00001291 auto_gen_msg = common_msg % argv0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001292 mod = asdl.parse(srcfile)
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001293 if dump_module:
1294 print('Parsed Module:')
1295 print(mod)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001296 if not asdl.check(mod):
1297 sys.exit(1)
Antoine Pitroub091bec2017-09-20 23:57:56 +02001298 if H_FILE:
1299 with open(H_FILE, "w") as f:
1300 f.write(auto_gen_msg)
1301 f.write('#include "asdl.h"\n\n')
1302 c = ChainOfVisitors(TypeDefVisitor(f),
1303 StructVisitor(f),
1304 PrototypeVisitor(f),
1305 )
1306 c.visit(mod)
1307 f.write("PyObject* PyAST_mod2obj(mod_ty t);\n")
1308 f.write("mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode);\n")
1309 f.write("int PyAST_Check(PyObject* obj);\n")
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001310
Antoine Pitroub091bec2017-09-20 23:57:56 +02001311 if C_FILE:
1312 with open(C_FILE, "w") as f:
1313 f.write(auto_gen_msg)
1314 f.write('#include <stddef.h>\n')
1315 f.write('\n')
1316 f.write('#include "Python.h"\n')
1317 f.write('#include "%s-ast.h"\n' % mod.name)
1318 f.write('\n')
1319 f.write("static PyTypeObject AST_type;\n")
1320 v = ChainOfVisitors(
1321 PyTypesDeclareVisitor(f),
1322 PyTypesVisitor(f),
1323 Obj2ModPrototypeVisitor(f),
1324 FunctionVisitor(f),
1325 ObjVisitor(f),
1326 Obj2ModVisitor(f),
1327 ASTModuleVisitor(f),
1328 PartingShots(f),
1329 )
1330 v.visit(mod)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001331
1332if __name__ == "__main__":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001333 import getopt
1334
Antoine Pitroub091bec2017-09-20 23:57:56 +02001335 H_FILE = ''
1336 C_FILE = ''
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001337 dump_module = False
1338 opts, args = getopt.getopt(sys.argv[1:], "dh:c:")
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001339 for o, v in opts:
1340 if o == '-h':
Antoine Pitroub091bec2017-09-20 23:57:56 +02001341 H_FILE = v
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001342 if o == '-c':
Antoine Pitroub091bec2017-09-20 23:57:56 +02001343 C_FILE = v
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001344 if o == '-d':
1345 dump_module = True
Antoine Pitroub091bec2017-09-20 23:57:56 +02001346 if H_FILE and C_FILE:
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001347 print('Must specify exactly one output file')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001348 sys.exit(1)
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001349 elif len(args) != 1:
1350 print('Must specify single input file')
1351 sys.exit(1)
1352 main(args[0], dump_module)