blob: 582c6ca57b65c4b816f3bc2ce8a53c62314ce38c [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 Storchakaf320be72018-01-25 10:49:40 +0200500 self.emit("if (_PyObject_LookupAttrId(obj, &PyId_%s, &tmp) < 0) {" % field.name, depth)
501 self.emit("return 1;", depth+1)
502 self.emit("}", depth)
Serhiy Storchakabba22392017-11-11 16:41:32 +0200503 if not field.opt:
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200504 self.emit("if (tmp == NULL) {", depth)
505 message = "required field \\\"%s\\\" missing from %s" % (field.name, name)
506 format = "PyErr_SetString(PyExc_TypeError, \"%s\");"
507 self.emit(format % message, depth+1, reflow=False)
508 self.emit("return 1;", depth+1)
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700509 else:
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200510 self.emit("if (tmp == NULL || tmp == Py_None) {", depth)
511 self.emit("Py_CLEAR(tmp);", depth+1)
512 if self.isNumeric(field):
513 self.emit("%s = 0;" % field.name, depth+1)
514 elif not self.isSimpleType(field):
515 self.emit("%s = NULL;" % field.name, depth+1)
516 else:
517 raise TypeError("could not determine the default value for %s" % field.name)
518 self.emit("}", depth)
519 self.emit("else {", depth)
520
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000521 self.emit("int res;", depth+1)
522 if field.seq:
523 self.emit("Py_ssize_t len;", depth+1)
524 self.emit("Py_ssize_t i;", depth+1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000525 self.emit("if (!PyList_Check(tmp)) {", depth+1)
526 self.emit("PyErr_Format(PyExc_TypeError, \"%s field \\\"%s\\\" must "
527 "be a list, not a %%.200s\", tmp->ob_type->tp_name);" %
528 (name, field.name),
529 depth+2, reflow=False)
530 self.emit("goto failed;", depth+2)
531 self.emit("}", depth+1)
532 self.emit("len = PyList_GET_SIZE(tmp);", depth+1)
533 if self.isSimpleType(field):
Antoine Pitroud01d396e2013-10-12 22:52:43 +0200534 self.emit("%s = _Py_asdl_int_seq_new(len, arena);" % field.name, depth+1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000535 else:
Antoine Pitroud01d396e2013-10-12 22:52:43 +0200536 self.emit("%s = _Py_asdl_seq_new(len, arena);" % field.name, depth+1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000537 self.emit("if (%s == NULL) goto failed;" % field.name, depth+1)
538 self.emit("for (i = 0; i < len; i++) {", depth+1)
Yuan Chao Chou2af565b2017-08-04 10:53:12 -0700539 self.emit("%s val;" % ctype, depth+2)
540 self.emit("res = obj2ast_%s(PyList_GET_ITEM(tmp, i), &val, arena);" %
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000541 field.type, depth+2, reflow=False)
542 self.emit("if (res != 0) goto failed;", depth+2)
Serhiy Storchakacf380602016-10-07 21:51:28 +0300543 self.emit("if (len != PyList_GET_SIZE(tmp)) {", depth+2)
544 self.emit("PyErr_SetString(PyExc_RuntimeError, \"%s field \\\"%s\\\" "
545 "changed size during iteration\");" %
546 (name, field.name),
547 depth+3, reflow=False)
548 self.emit("goto failed;", depth+3)
549 self.emit("}", depth+2)
Yuan Chao Chou2af565b2017-08-04 10:53:12 -0700550 self.emit("asdl_seq_SET(%s, i, val);" % field.name, depth+2)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000551 self.emit("}", depth+1)
552 else:
553 self.emit("res = obj2ast_%s(tmp, &%s, arena);" %
554 (field.type, field.name), depth+1)
555 self.emit("if (res != 0) goto failed;", depth+1)
556
Victor Stinner1acc1292013-07-27 00:03:47 +0200557 self.emit("Py_CLEAR(tmp);", depth+1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000558 self.emit("}", depth)
559
560
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000561class MarshalPrototypeVisitor(PickleVisitor):
562
563 def prototype(self, sum, name):
564 ctype = get_c_type(name)
Neal Norwitz6576bd82005-11-13 18:41:28 +0000565 self.emit("static int marshal_write_%s(PyObject **, int *, %s);"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000566 % (name, ctype), 0)
567
568 visitProduct = visitSum = prototype
569
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000570
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000571class PyTypesDeclareVisitor(PickleVisitor):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000572
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000573 def visitProduct(self, prod, name):
Neal Norwitz53d960c2006-02-28 22:47:29 +0000574 self.emit("static PyTypeObject *%s_type;" % name, 0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000575 self.emit("static PyObject* ast2obj_%s(void*);" % name, 0)
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700576 if prod.attributes:
577 for a in prod.attributes:
578 self.emit_identifier(a.name)
579 self.emit("static char *%s_attributes[] = {" % name, 0)
580 for a in prod.attributes:
581 self.emit('"%s",' % a.name, 1)
582 self.emit("};", 0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000583 if prod.fields:
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200584 for f in prod.fields:
585 self.emit_identifier(f.name)
Neal Norwitz53d960c2006-02-28 22:47:29 +0000586 self.emit("static char *%s_fields[]={" % name,0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000587 for f in prod.fields:
588 self.emit('"%s",' % f.name, 1)
589 self.emit("};", 0)
Tim Peters710ab3b2006-02-28 18:30:36 +0000590
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000591 def visitSum(self, sum, name):
Neal Norwitz53d960c2006-02-28 22:47:29 +0000592 self.emit("static PyTypeObject *%s_type;" % name, 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000593 if sum.attributes:
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200594 for a in sum.attributes:
595 self.emit_identifier(a.name)
Neal Norwitz53d960c2006-02-28 22:47:29 +0000596 self.emit("static char *%s_attributes[] = {" % name, 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000597 for a in sum.attributes:
598 self.emit('"%s",' % a.name, 1)
599 self.emit("};", 0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000600 ptype = "void*"
601 if is_simple(sum):
602 ptype = get_c_type(name)
603 tnames = []
604 for t in sum.types:
605 tnames.append(str(t.name)+"_singleton")
606 tnames = ", *".join(tnames)
607 self.emit("static PyObject *%s;" % tnames, 0)
608 self.emit("static PyObject* ast2obj_%s(%s);" % (name, ptype), 0)
609 for t in sum.types:
610 self.visitConstructor(t, name)
Tim Peters710ab3b2006-02-28 18:30:36 +0000611
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000612 def visitConstructor(self, cons, name):
Neal Norwitz53d960c2006-02-28 22:47:29 +0000613 self.emit("static PyTypeObject *%s_type;" % cons.name, 0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000614 if cons.fields:
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200615 for t in cons.fields:
616 self.emit_identifier(t.name)
Neal Norwitz53d960c2006-02-28 22:47:29 +0000617 self.emit("static char *%s_fields[]={" % cons.name, 0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000618 for t in cons.fields:
619 self.emit('"%s",' % t.name, 1)
620 self.emit("};",0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000621
622class PyTypesVisitor(PickleVisitor):
623
624 def visitModule(self, mod):
625 self.emit("""
INADA Naokifc489082017-01-25 22:33:43 +0900626_Py_IDENTIFIER(_fields);
627_Py_IDENTIFIER(_attributes);
628
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700629typedef struct {
Victor Stinner45e50de2012-03-13 01:17:31 +0100630 PyObject_HEAD
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700631 PyObject *dict;
632} AST_object;
633
Benjamin Peterson1767e022012-03-14 21:50:29 -0500634static void
635ast_dealloc(AST_object *self)
636{
INADA Naokia6296d32017-08-24 14:55:17 +0900637 /* bpo-31095: UnTrack is needed before calling any callbacks */
638 PyObject_GC_UnTrack(self);
Benjamin Peterson1767e022012-03-14 21:50:29 -0500639 Py_CLEAR(self->dict);
Antoine Pitrou50750742012-07-08 12:43:32 +0200640 Py_TYPE(self)->tp_free(self);
Benjamin Peterson1767e022012-03-14 21:50:29 -0500641}
642
Neal Norwitz207c9f32008-03-31 04:42:11 +0000643static int
Benjamin Peterson81071762012-07-08 11:03:46 -0700644ast_traverse(AST_object *self, visitproc visit, void *arg)
645{
646 Py_VISIT(self->dict);
647 return 0;
648}
649
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300650static int
Benjamin Peterson81071762012-07-08 11:03:46 -0700651ast_clear(AST_object *self)
652{
653 Py_CLEAR(self->dict);
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300654 return 0;
Benjamin Peterson81071762012-07-08 11:03:46 -0700655}
656
657static int
Neal Norwitz207c9f32008-03-31 04:42:11 +0000658ast_type_init(PyObject *self, PyObject *args, PyObject *kw)
659{
660 Py_ssize_t i, numfields = 0;
661 int res = -1;
662 PyObject *key, *value, *fields;
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200663 if (_PyObject_LookupAttrId((PyObject*)Py_TYPE(self), &PyId__fields, &fields) < 0) {
664 goto cleanup;
665 }
Neal Norwitz207c9f32008-03-31 04:42:11 +0000666 if (fields) {
667 numfields = PySequence_Size(fields);
668 if (numfields == -1)
669 goto cleanup;
670 }
INADA Naoki4c78c522017-02-24 02:48:17 +0900671
Neal Norwitz207c9f32008-03-31 04:42:11 +0000672 res = 0; /* if no error occurs, this stays 0 to the end */
INADA Naoki4c78c522017-02-24 02:48:17 +0900673 if (numfields < PyTuple_GET_SIZE(args)) {
674 PyErr_Format(PyExc_TypeError, "%.400s constructor takes at most "
675 "%zd positional argument%s",
676 Py_TYPE(self)->tp_name,
677 numfields, numfields == 1 ? "" : "s");
678 res = -1;
679 goto cleanup;
680 }
681 for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
682 /* cannot be reached when fields is NULL */
683 PyObject *name = PySequence_GetItem(fields, i);
684 if (!name) {
Neal Norwitz207c9f32008-03-31 04:42:11 +0000685 res = -1;
686 goto cleanup;
687 }
INADA Naoki4c78c522017-02-24 02:48:17 +0900688 res = PyObject_SetAttr(self, name, PyTuple_GET_ITEM(args, i));
689 Py_DECREF(name);
690 if (res < 0)
691 goto cleanup;
Neal Norwitz207c9f32008-03-31 04:42:11 +0000692 }
693 if (kw) {
694 i = 0; /* needed by PyDict_Next */
695 while (PyDict_Next(kw, &i, &key, &value)) {
696 res = PyObject_SetAttr(self, key, value);
697 if (res < 0)
698 goto cleanup;
699 }
700 }
701 cleanup:
702 Py_XDECREF(fields);
703 return res;
704}
705
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000706/* Pickling support */
707static PyObject *
708ast_type_reduce(PyObject *self, PyObject *unused)
709{
Meador Inge70d86bd2011-10-22 14:06:50 -0500710 _Py_IDENTIFIER(__dict__);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200711 PyObject *dict;
712 if (_PyObject_LookupAttrId(self, &PyId___dict__, &dict) < 0) {
713 return NULL;
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000714 }
715 if (dict) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200716 return Py_BuildValue("O()N", Py_TYPE(self), dict);
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000717 }
718 return Py_BuildValue("O()", Py_TYPE(self));
719}
720
721static PyMethodDef ast_type_methods[] = {
722 {"__reduce__", ast_type_reduce, METH_NOARGS, NULL},
723 {NULL}
724};
725
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700726static PyGetSetDef ast_type_getsets[] = {
727 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
728 {NULL}
729};
730
Neal Norwitz207c9f32008-03-31 04:42:11 +0000731static PyTypeObject AST_type = {
732 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000733 "_ast.AST",
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700734 sizeof(AST_object),
Neal Norwitz207c9f32008-03-31 04:42:11 +0000735 0,
Benjamin Peterson1767e022012-03-14 21:50:29 -0500736 (destructor)ast_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200737 0, /* tp_vectorcall_offset */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000738 0, /* tp_getattr */
739 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200740 0, /* tp_as_async */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000741 0, /* tp_repr */
742 0, /* tp_as_number */
743 0, /* tp_as_sequence */
744 0, /* tp_as_mapping */
745 0, /* tp_hash */
746 0, /* tp_call */
747 0, /* tp_str */
748 PyObject_GenericGetAttr, /* tp_getattro */
749 PyObject_GenericSetAttr, /* tp_setattro */
750 0, /* tp_as_buffer */
Benjamin Peterson81071762012-07-08 11:03:46 -0700751 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000752 0, /* tp_doc */
Benjamin Peterson81071762012-07-08 11:03:46 -0700753 (traverseproc)ast_traverse, /* tp_traverse */
754 (inquiry)ast_clear, /* tp_clear */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000755 0, /* tp_richcompare */
756 0, /* tp_weaklistoffset */
757 0, /* tp_iter */
758 0, /* tp_iternext */
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000759 ast_type_methods, /* tp_methods */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000760 0, /* tp_members */
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700761 ast_type_getsets, /* tp_getset */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000762 0, /* tp_base */
763 0, /* tp_dict */
764 0, /* tp_descr_get */
765 0, /* tp_descr_set */
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700766 offsetof(AST_object, dict),/* tp_dictoffset */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000767 (initproc)ast_type_init, /* tp_init */
768 PyType_GenericAlloc, /* tp_alloc */
769 PyType_GenericNew, /* tp_new */
Benjamin Peterson81071762012-07-08 11:03:46 -0700770 PyObject_GC_Del, /* tp_free */
Neal Norwitz207c9f32008-03-31 04:42:11 +0000771};
772
773
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000774static PyTypeObject* make_type(char *type, PyTypeObject* base, char**fields, int num_fields)
775{
INADA Naokifc489082017-01-25 22:33:43 +0900776 _Py_IDENTIFIER(__module__);
777 _Py_IDENTIFIER(_ast);
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000778 PyObject *fnames, *result;
779 int i;
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000780 fnames = PyTuple_New(num_fields);
781 if (!fnames) return NULL;
782 for (i = 0; i < num_fields; i++) {
Neal Norwitze4dc3242007-08-25 01:33:49 +0000783 PyObject *field = PyUnicode_FromString(fields[i]);
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000784 if (!field) {
785 Py_DECREF(fnames);
786 return NULL;
787 }
788 PyTuple_SET_ITEM(fnames, i, field);
789 }
INADA Naokifc489082017-01-25 22:33:43 +0900790 result = PyObject_CallFunction((PyObject*)&PyType_Type, "s(O){OOOO}",
791 type, base,
792 _PyUnicode_FromId(&PyId__fields), fnames,
793 _PyUnicode_FromId(&PyId___module__),
794 _PyUnicode_FromId(&PyId__ast));
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000795 Py_DECREF(fnames);
796 return (PyTypeObject*)result;
797}
798
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000799static int add_attributes(PyTypeObject* type, char**attrs, int num_fields)
800{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000801 int i, result;
Neal Norwitz207c9f32008-03-31 04:42:11 +0000802 PyObject *s, *l = PyTuple_New(num_fields);
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000803 if (!l)
804 return 0;
805 for (i = 0; i < num_fields; i++) {
Neal Norwitze4dc3242007-08-25 01:33:49 +0000806 s = PyUnicode_FromString(attrs[i]);
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000807 if (!s) {
808 Py_DECREF(l);
809 return 0;
810 }
Neal Norwitz207c9f32008-03-31 04:42:11 +0000811 PyTuple_SET_ITEM(l, i, s);
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000812 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200813 result = _PyObject_SetAttrId((PyObject*)type, &PyId__attributes, l) >= 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000814 Py_DECREF(l);
815 return result;
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000816}
817
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000818/* Conversion AST -> Python */
819
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000820static PyObject* ast2obj_list(asdl_seq *seq, PyObject* (*func)(void*))
821{
Benjamin Peterson77fa9372012-05-15 10:10:27 -0700822 Py_ssize_t i, n = asdl_seq_LEN(seq);
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000823 PyObject *result = PyList_New(n);
824 PyObject *value;
825 if (!result)
826 return NULL;
827 for (i = 0; i < n; i++) {
828 value = func(asdl_seq_GET(seq, i));
829 if (!value) {
830 Py_DECREF(result);
831 return NULL;
832 }
833 PyList_SET_ITEM(result, i, value);
834 }
835 return result;
836}
837
838static PyObject* ast2obj_object(void *o)
839{
840 if (!o)
841 o = Py_None;
842 Py_INCREF((PyObject*)o);
843 return (PyObject*)o;
844}
Benjamin Peterson442f2092012-12-06 17:41:04 -0500845#define ast2obj_singleton ast2obj_object
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100846#define ast2obj_constant ast2obj_object
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000847#define ast2obj_identifier ast2obj_object
848#define ast2obj_string ast2obj_object
Benjamin Petersone2498412011-08-09 16:08:39 -0500849#define ast2obj_bytes ast2obj_object
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000850
Thomas Woutersa44f3a32007-02-26 18:20:15 +0000851static PyObject* ast2obj_int(long b)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000852{
Christian Heimes2b1c5922007-12-02 22:43:00 +0000853 return PyLong_FromLong(b);
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000854}
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000855
856/* Conversion Python -> AST */
857
858static int obj2ast_object(PyObject* obj, PyObject** out, PyArena* arena)
859{
860 if (obj == Py_None)
861 obj = NULL;
Christian Heimes70c94e72013-07-27 00:33:13 +0200862 if (obj) {
863 if (PyArena_AddPyObject(arena, obj) < 0) {
864 *out = NULL;
865 return -1;
866 }
867 Py_INCREF(obj);
868 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000869 *out = obj;
870 return 0;
871}
872
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100873static int obj2ast_constant(PyObject* obj, PyObject** out, PyArena* arena)
874{
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300875 if (PyArena_AddPyObject(arena, obj) < 0) {
876 *out = NULL;
877 return -1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100878 }
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300879 Py_INCREF(obj);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100880 *out = obj;
881 return 0;
882}
883
Benjamin Peterson180e6352011-07-22 11:09:07 -0500884static int obj2ast_identifier(PyObject* obj, PyObject** out, PyArena* arena)
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500885{
Benjamin Peterson180e6352011-07-22 11:09:07 -0500886 if (!PyUnicode_CheckExact(obj) && obj != Py_None) {
887 PyErr_SetString(PyExc_TypeError, "AST identifier must be of type str");
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500888 return 1;
889 }
890 return obj2ast_object(obj, out, arena);
891}
892
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800893static int obj2ast_string(PyObject* obj, PyObject** out, PyArena* arena)
894{
895 if (!PyUnicode_CheckExact(obj) && !PyBytes_CheckExact(obj)) {
896 PyErr_SetString(PyExc_TypeError, "AST string must be of type str");
897 return 1;
898 }
899 return obj2ast_object(obj, out, arena);
900}
901
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000902static int obj2ast_int(PyObject* obj, int* out, PyArena* arena)
903{
904 int i;
905 if (!PyLong_Check(obj)) {
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100906 PyErr_Format(PyExc_ValueError, "invalid integer value: %R", obj);
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000907 return 1;
908 }
909
Serhiy Storchaka481d3af2015-09-06 23:29:04 +0300910 i = _PyLong_AsInt(obj);
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000911 if (i == -1 && PyErr_Occurred())
912 return 1;
913 *out = i;
914 return 0;
915}
916
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +0000917static int add_ast_fields(void)
Benjamin Peterson206e3072008-10-19 14:07:49 +0000918{
919 PyObject *empty_tuple, *d;
920 if (PyType_Ready(&AST_type) < 0)
921 return -1;
922 d = AST_type.tp_dict;
923 empty_tuple = PyTuple_New(0);
924 if (!empty_tuple ||
INADA Naokifc489082017-01-25 22:33:43 +0900925 _PyDict_SetItemId(d, &PyId__fields, empty_tuple) < 0 ||
926 _PyDict_SetItemId(d, &PyId__attributes, empty_tuple) < 0) {
Benjamin Peterson206e3072008-10-19 14:07:49 +0000927 Py_XDECREF(empty_tuple);
928 return -1;
929 }
930 Py_DECREF(empty_tuple);
931 return 0;
932}
933
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000934""", 0, reflow=False)
935
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000936 self.emit("static int init_types(void)",0)
937 self.emit("{", 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000938 self.emit("static int initialized;", 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000939 self.emit("if (initialized) return 1;", 1)
Benjamin Peterson206e3072008-10-19 14:07:49 +0000940 self.emit("if (add_ast_fields() < 0) return 0;", 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000941 for dfn in mod.dfns:
942 self.visit(dfn)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000943 self.emit("initialized = 1;", 1)
944 self.emit("return 1;", 1);
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000945 self.emit("}", 0)
946
947 def visitProduct(self, prod, name):
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000948 if prod.fields:
Eli Bendersky5e3d3382014-05-09 17:58:22 -0700949 fields = name+"_fields"
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000950 else:
951 fields = "NULL"
Neal Norwitz207c9f32008-03-31 04:42:11 +0000952 self.emit('%s_type = make_type("%s", &AST_type, %s, %d);' %
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000953 (name, name, fields, len(prod.fields)), 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000954 self.emit("if (!%s_type) return 0;" % name, 1)
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700955 if prod.attributes:
956 self.emit("if (!add_attributes(%s_type, %s_attributes, %d)) return 0;" %
957 (name, name, len(prod.attributes)), 1)
958 else:
959 self.emit("if (!add_attributes(%s_type, NULL, 0)) return 0;" % name, 1)
Tim Peters710ab3b2006-02-28 18:30:36 +0000960
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000961 def visitSum(self, sum, name):
Neal Norwitz207c9f32008-03-31 04:42:11 +0000962 self.emit('%s_type = make_type("%s", &AST_type, NULL, 0);' %
963 (name, name), 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000964 self.emit("if (!%s_type) return 0;" % name, 1)
965 if sum.attributes:
Tim Peters710ab3b2006-02-28 18:30:36 +0000966 self.emit("if (!add_attributes(%s_type, %s_attributes, %d)) return 0;" %
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000967 (name, name, len(sum.attributes)), 1)
968 else:
969 self.emit("if (!add_attributes(%s_type, NULL, 0)) return 0;" % name, 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000970 simple = is_simple(sum)
971 for t in sum.types:
972 self.visitConstructor(t, name, simple)
Tim Peters710ab3b2006-02-28 18:30:36 +0000973
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000974 def visitConstructor(self, cons, name, simple):
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000975 if cons.fields:
Eli Bendersky5e3d3382014-05-09 17:58:22 -0700976 fields = cons.name+"_fields"
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000977 else:
978 fields = "NULL"
Tim Peters710ab3b2006-02-28 18:30:36 +0000979 self.emit('%s_type = make_type("%s", %s_type, %s, %d);' %
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000980 (cons.name, cons.name, name, fields, len(cons.fields)), 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000981 self.emit("if (!%s_type) return 0;" % cons.name, 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000982 if simple:
983 self.emit("%s_singleton = PyType_GenericNew(%s_type, NULL, NULL);" %
984 (cons.name, cons.name), 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000985 self.emit("if (!%s_singleton) return 0;" % cons.name, 1)
Tim Peters710ab3b2006-02-28 18:30:36 +0000986
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000987
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000988class ASTModuleVisitor(PickleVisitor):
989
990 def visitModule(self, mod):
Martin v. Löwis1a214512008-06-11 05:26:20 +0000991 self.emit("static struct PyModuleDef _astmodule = {", 0)
992 self.emit(' PyModuleDef_HEAD_INIT, "_ast"', 0)
993 self.emit("};", 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000994 self.emit("PyMODINIT_FUNC", 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000995 self.emit("PyInit__ast(void)", 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000996 self.emit("{", 0)
997 self.emit("PyObject *m, *d;", 1)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000998 self.emit("if (!init_types()) return NULL;", 1)
999 self.emit('m = PyModule_Create(&_astmodule);', 1)
1000 self.emit("if (!m) return NULL;", 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001001 self.emit("d = PyModule_GetDict(m);", 1)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001002 self.emit('if (PyDict_SetItemString(d, "AST", (PyObject*)&AST_type) < 0) return NULL;', 1)
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07001003 self.emit('if (PyModule_AddIntMacro(m, PyCF_ALLOW_TOP_LEVEL_AWAIT) < 0)', 1)
1004 self.emit("return NULL;", 2)
Benjamin Peterson8d89c2a2013-05-20 10:28:48 -07001005 self.emit('if (PyModule_AddIntMacro(m, PyCF_ONLY_AST) < 0)', 1)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001006 self.emit("return NULL;", 2)
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001007 self.emit('if (PyModule_AddIntMacro(m, PyCF_TYPE_COMMENTS) < 0)', 1)
1008 self.emit("return NULL;", 2)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001009 for dfn in mod.dfns:
1010 self.visit(dfn)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001011 self.emit("return m;", 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001012 self.emit("}", 0)
1013
1014 def visitProduct(self, prod, name):
1015 self.addObj(name)
Tim Peters710ab3b2006-02-28 18:30:36 +00001016
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001017 def visitSum(self, sum, name):
1018 self.addObj(name)
1019 for t in sum.types:
1020 self.visitConstructor(t, name)
Tim Peters710ab3b2006-02-28 18:30:36 +00001021
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001022 def visitConstructor(self, cons, name):
1023 self.addObj(cons.name)
Tim Peters710ab3b2006-02-28 18:30:36 +00001024
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001025 def addObj(self, name):
Martin v. Löwis1a214512008-06-11 05:26:20 +00001026 self.emit('if (PyDict_SetItemString(d, "%s", (PyObject*)%s_type) < 0) return NULL;' % (name, name), 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001027
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001028
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001029_SPECIALIZED_SEQUENCES = ('stmt', 'expr')
1030
1031def find_sequence(fields, doing_specialization):
1032 """Return True if any field uses a sequence."""
1033 for f in fields:
1034 if f.seq:
1035 if not doing_specialization:
1036 return True
1037 if str(f.type) not in _SPECIALIZED_SEQUENCES:
1038 return True
1039 return False
1040
1041def has_sequence(types, doing_specialization):
1042 for t in types:
1043 if find_sequence(t.fields, doing_specialization):
1044 return True
1045 return False
1046
1047
1048class StaticVisitor(PickleVisitor):
Ezio Melotti7c4a7e62013-08-26 01:32:56 +03001049 CODE = '''Very simple, always emit this static code. Override CODE'''
Neal Norwitz7b5a6042005-11-13 19:14:20 +00001050
1051 def visit(self, object):
1052 self.emit(self.CODE, 0, reflow=False)
1053
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001054
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001055class ObjVisitor(PickleVisitor):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001056
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001057 def func_begin(self, name):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001058 ctype = get_c_type(name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001059 self.emit("PyObject*", 0)
1060 self.emit("ast2obj_%s(void* _o)" % (name), 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001061 self.emit("{", 0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001062 self.emit("%s o = (%s)_o;" % (ctype, ctype), 1)
1063 self.emit("PyObject *result = NULL, *value = NULL;", 1)
1064 self.emit('if (!o) {', 1)
INADA Naokifc489082017-01-25 22:33:43 +09001065 self.emit("Py_RETURN_NONE;", 2)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001066 self.emit("}", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001067 self.emit('', 0)
1068
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001069 def func_end(self):
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001070 self.emit("return result;", 1)
1071 self.emit("failed:", 0)
1072 self.emit("Py_XDECREF(value);", 1)
1073 self.emit("Py_XDECREF(result);", 1)
1074 self.emit("return NULL;", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001075 self.emit("}", 0)
1076 self.emit("", 0)
1077
1078 def visitSum(self, sum, name):
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001079 if is_simple(sum):
1080 self.simpleSum(sum, name)
1081 return
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001082 self.func_begin(name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001083 self.emit("switch (o->kind) {", 1)
1084 for i in range(len(sum.types)):
1085 t = sum.types[i]
1086 self.visitConstructor(t, i + 1, name)
1087 self.emit("}", 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001088 for a in sum.attributes:
1089 self.emit("value = ast2obj_%s(o->%s);" % (a.type, a.name), 1)
1090 self.emit("if (!value) goto failed;", 1)
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001091 self.emit('if (_PyObject_SetAttrId(result, &PyId_%s, value) < 0)' % a.name, 1)
Martin v. Löwis03e5bc02006-03-02 00:31:27 +00001092 self.emit('goto failed;', 2)
1093 self.emit('Py_DECREF(value);', 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001094 self.func_end()
Tim Peters710ab3b2006-02-28 18:30:36 +00001095
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001096 def simpleSum(self, sum, name):
1097 self.emit("PyObject* ast2obj_%s(%s_ty o)" % (name, name), 0)
1098 self.emit("{", 0)
1099 self.emit("switch(o) {", 1)
1100 for t in sum.types:
1101 self.emit("case %s:" % t.name, 2)
1102 self.emit("Py_INCREF(%s_singleton);" % t.name, 3)
1103 self.emit("return %s_singleton;" % t.name, 3)
Ezio Melotticb2916a2012-09-30 22:41:37 +03001104 self.emit("default:", 2)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001105 self.emit('/* should never happen, but just in case ... */', 3)
1106 code = "PyErr_Format(PyExc_SystemError, \"unknown %s found\");" % name
1107 self.emit(code, 3, reflow=False)
1108 self.emit("return NULL;", 3)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001109 self.emit("}", 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001110 self.emit("}", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001111
1112 def visitProduct(self, prod, name):
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001113 self.func_begin(name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001114 self.emit("result = PyType_GenericNew(%s_type, NULL, NULL);" % name, 1);
1115 self.emit("if (!result) return NULL;", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001116 for field in prod.fields:
1117 self.visitField(field, name, 1, True)
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001118 for a in prod.attributes:
1119 self.emit("value = ast2obj_%s(o->%s);" % (a.type, a.name), 1)
1120 self.emit("if (!value) goto failed;", 1)
1121 self.emit('if (_PyObject_SetAttrId(result, &PyId_%s, value) < 0)' % a.name, 1)
1122 self.emit('goto failed;', 2)
1123 self.emit('Py_DECREF(value);', 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001124 self.func_end()
Tim Peters536cf992005-12-25 23:18:31 +00001125
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001126 def visitConstructor(self, cons, enum, name):
1127 self.emit("case %s_kind:" % cons.name, 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001128 self.emit("result = PyType_GenericNew(%s_type, NULL, NULL);" % cons.name, 2);
1129 self.emit("if (!result) goto failed;", 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001130 for f in cons.fields:
1131 self.visitField(f, cons.name, 2, False)
1132 self.emit("break;", 2)
1133
1134 def visitField(self, field, name, depth, product):
1135 def emit(s, d):
1136 self.emit(s, depth + d)
1137 if product:
1138 value = "o->%s" % field.name
1139 else:
1140 value = "o->v.%s.%s" % (name, field.name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001141 self.set(field, value, depth)
1142 emit("if (!value) goto failed;", 0)
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001143 emit('if (_PyObject_SetAttrId(result, &PyId_%s, value) == -1)' % field.name, 0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001144 emit("goto failed;", 1)
1145 emit("Py_DECREF(value);", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146
1147 def emitSeq(self, field, value, depth, emit):
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001148 emit("seq = %s;" % value, 0)
1149 emit("n = asdl_seq_LEN(seq);", 0)
1150 emit("value = PyList_New(n);", 0)
1151 emit("if (!value) goto failed;", 0)
1152 emit("for (i = 0; i < n; i++) {", 0)
1153 self.set("value", field, "asdl_seq_GET(seq, i)", depth + 1)
1154 emit("if (!value1) goto failed;", 1)
1155 emit("PyList_SET_ITEM(value, i, value1);", 1)
1156 emit("value1 = NULL;", 1)
1157 emit("}", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001158
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001159 def set(self, field, value, depth):
1160 if field.seq:
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001161 # XXX should really check for is_simple, but that requires a symbol table
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001162 if field.type == "cmpop":
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001163 # While the sequence elements are stored as void*,
1164 # ast2obj_cmpop expects an enum
1165 self.emit("{", depth)
Benjamin Peterson77fa9372012-05-15 10:10:27 -07001166 self.emit("Py_ssize_t i, n = asdl_seq_LEN(%s);" % value, depth+1)
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001167 self.emit("value = PyList_New(n);", depth+1)
1168 self.emit("if (!value) goto failed;", depth+1)
1169 self.emit("for(i = 0; i < n; i++)", depth+1)
1170 # This cannot fail, so no need for error handling
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001171 self.emit("PyList_SET_ITEM(value, i, ast2obj_cmpop((cmpop_ty)asdl_seq_GET(%s, i)));" % value,
1172 depth+2, reflow=False)
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001173 self.emit("}", depth)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001174 else:
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001175 self.emit("value = ast2obj_list(%s, ast2obj_%s);" % (value, field.type), depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001176 else:
1177 ctype = get_c_type(field.type)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001178 self.emit("value = ast2obj_%s(%s);" % (field.type, value), depth, reflow=False)
Tim Peters536cf992005-12-25 23:18:31 +00001179
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001180
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001181class PartingShots(StaticVisitor):
1182
1183 CODE = """
1184PyObject* PyAST_mod2obj(mod_ty t)
1185{
Victor Stinnerbdf630c2013-07-17 00:17:15 +02001186 if (!init_types())
1187 return NULL;
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001188 return ast2obj_mod(t);
1189}
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001190
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001191/* mode is 0 for "exec", 1 for "eval" and 2 for "single" input */
1192mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001193{
Guido van Rossum495da292019-03-07 12:38:08 -08001194 return PyAST_obj2mod_ex(ast, arena, mode, PY_MINOR_VERSION);
1195}
1196
1197mod_ty PyAST_obj2mod_ex(PyObject* ast, PyArena* arena, int mode, int feature_version)
1198{
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001199 mod_ty res;
Benjamin Petersonc2f665e2014-02-10 22:19:02 -05001200 PyObject *req_type[3];
Guido van Rossum3a32e3b2019-02-01 11:37:34 -08001201 char *req_name[] = {"Module", "Expression", "Interactive"};
Benjamin Peterson97dd9872009-12-13 01:23:39 +00001202 int isinstance;
Benjamin Petersonc2f665e2014-02-10 22:19:02 -05001203
Steve Dowerb82e17e2019-05-23 08:45:22 -07001204 if (PySys_Audit("compile", "OO", ast, Py_None) < 0) {
1205 return NULL;
1206 }
1207
Benjamin Petersonc2f665e2014-02-10 22:19:02 -05001208 req_type[0] = (PyObject*)Module_type;
1209 req_type[1] = (PyObject*)Expression_type;
1210 req_type[2] = (PyObject*)Interactive_type;
1211
Guido van Rossum3a32e3b2019-02-01 11:37:34 -08001212 assert(0 <= mode && mode <= 2);
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001213
Victor Stinnerbdf630c2013-07-17 00:17:15 +02001214 if (!init_types())
1215 return NULL;
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001216
Benjamin Peterson97dd9872009-12-13 01:23:39 +00001217 isinstance = PyObject_IsInstance(ast, req_type[mode]);
1218 if (isinstance == -1)
1219 return NULL;
1220 if (!isinstance) {
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001221 PyErr_Format(PyExc_TypeError, "expected %s node, got %.400s",
1222 req_name[mode], Py_TYPE(ast)->tp_name);
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001223 return NULL;
1224 }
1225 if (obj2ast_mod(ast, &res, arena) != 0)
1226 return NULL;
1227 else
1228 return res;
1229}
1230
1231int PyAST_Check(PyObject* obj)
1232{
Victor Stinnerbdf630c2013-07-17 00:17:15 +02001233 if (!init_types())
1234 return -1;
Neal Norwitz207c9f32008-03-31 04:42:11 +00001235 return PyObject_IsInstance(obj, (PyObject*)&AST_type);
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001236}
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001237"""
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001238
1239class ChainOfVisitors:
1240 def __init__(self, *visitors):
1241 self.visitors = visitors
1242
1243 def visit(self, object):
1244 for v in self.visitors:
1245 v.visit(object)
Neal Norwitz7b5a6042005-11-13 19:14:20 +00001246 v.emit("", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001247
Guido van Rossum805365e2007-05-07 22:24:25 +00001248common_msg = "/* File automatically generated by %s. */\n\n"
Thomas Wouterscf297e42007-02-23 15:07:44 +00001249
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001250def main(srcfile, dump_module=False):
Neal Norwitz897ff812005-12-11 21:18:22 +00001251 argv0 = sys.argv[0]
Armin Rigo6b1793f2005-12-14 18:05:14 +00001252 components = argv0.split(os.sep)
1253 argv0 = os.sep.join(components[-2:])
Thomas Wouterscf297e42007-02-23 15:07:44 +00001254 auto_gen_msg = common_msg % argv0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001255 mod = asdl.parse(srcfile)
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001256 if dump_module:
1257 print('Parsed Module:')
1258 print(mod)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001259 if not asdl.check(mod):
1260 sys.exit(1)
Antoine Pitroub091bec2017-09-20 23:57:56 +02001261 if H_FILE:
1262 with open(H_FILE, "w") as f:
1263 f.write(auto_gen_msg)
Victor Stinner5f2df882018-11-12 00:56:19 +01001264 f.write('#ifndef Py_PYTHON_AST_H\n')
1265 f.write('#define Py_PYTHON_AST_H\n')
1266 f.write('#ifdef __cplusplus\n')
1267 f.write('extern "C" {\n')
1268 f.write('#endif\n')
1269 f.write('\n')
1270 f.write('#include "asdl.h"\n')
1271 f.write('\n')
Victor Stinner3bb183d2018-11-22 18:38:38 +01001272 f.write('#undef Yield /* undefine macro conflicting with <winbase.h> */\n')
Victor Stinner5f2df882018-11-12 00:56:19 +01001273 f.write('\n')
Antoine Pitroub091bec2017-09-20 23:57:56 +02001274 c = ChainOfVisitors(TypeDefVisitor(f),
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00001275 StructVisitor(f))
1276
Antoine Pitroub091bec2017-09-20 23:57:56 +02001277 c.visit(mod)
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00001278 f.write("// Note: these macros affect function definitions, not only call sites.\n")
1279 PrototypeVisitor(f).visit(mod)
1280 f.write("\n")
Antoine Pitroub091bec2017-09-20 23:57:56 +02001281 f.write("PyObject* PyAST_mod2obj(mod_ty t);\n")
1282 f.write("mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode);\n")
Guido van Rossum495da292019-03-07 12:38:08 -08001283 f.write("mod_ty PyAST_obj2mod_ex(PyObject* ast, PyArena* arena, int mode, int feature_version);\n")
Antoine Pitroub091bec2017-09-20 23:57:56 +02001284 f.write("int PyAST_Check(PyObject* obj);\n")
Victor Stinner5f2df882018-11-12 00:56:19 +01001285 f.write('\n')
1286 f.write('#ifdef __cplusplus\n')
1287 f.write('}\n')
1288 f.write('#endif\n')
1289 f.write('#endif /* !Py_PYTHON_AST_H */\n')
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001290
Antoine Pitroub091bec2017-09-20 23:57:56 +02001291 if C_FILE:
1292 with open(C_FILE, "w") as f:
1293 f.write(auto_gen_msg)
1294 f.write('#include <stddef.h>\n')
1295 f.write('\n')
1296 f.write('#include "Python.h"\n')
1297 f.write('#include "%s-ast.h"\n' % mod.name)
1298 f.write('\n')
1299 f.write("static PyTypeObject AST_type;\n")
1300 v = ChainOfVisitors(
1301 PyTypesDeclareVisitor(f),
1302 PyTypesVisitor(f),
1303 Obj2ModPrototypeVisitor(f),
1304 FunctionVisitor(f),
1305 ObjVisitor(f),
1306 Obj2ModVisitor(f),
1307 ASTModuleVisitor(f),
1308 PartingShots(f),
1309 )
1310 v.visit(mod)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001311
1312if __name__ == "__main__":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001313 import getopt
1314
Antoine Pitroub091bec2017-09-20 23:57:56 +02001315 H_FILE = ''
1316 C_FILE = ''
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001317 dump_module = False
1318 opts, args = getopt.getopt(sys.argv[1:], "dh:c:")
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001319 for o, v in opts:
1320 if o == '-h':
Antoine Pitroub091bec2017-09-20 23:57:56 +02001321 H_FILE = v
Emmanuel Ariased5e29c2019-03-21 01:39:17 -03001322 elif o == '-c':
Antoine Pitroub091bec2017-09-20 23:57:56 +02001323 C_FILE = v
Emmanuel Ariased5e29c2019-03-21 01:39:17 -03001324 elif o == '-d':
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001325 dump_module = True
Antoine Pitroub091bec2017-09-20 23:57:56 +02001326 if H_FILE and C_FILE:
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001327 print('Must specify exactly one output file')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001328 sys.exit(1)
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001329 elif len(args) != 1:
1330 print('Must specify single input file')
1331 sys.exit(1)
1332 main(args[0], dump_module)