blob: 59bf03ef8df3d3d7dbafea3f90a7aa8fd53d084c [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
Batuhan Taşkaya4ab362c2020-03-16 11:12:53 +030063def reflow_c_string(s, depth):
64 return '"%s"' % s.replace('\n', '\\n"\n%s"' % (' ' * depth * TABSIZE))
65
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000066def is_simple(sum):
67 """Return True if a sum is a simple.
68
69 A sum is simple if its types have no fields, e.g.
70 unaryop = Invert | Not | UAdd | USub
71 """
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000072 for t in sum.types:
73 if t.fields:
74 return False
75 return True
76
Batuhan Taşkaya4ab362c2020-03-16 11:12:53 +030077def asdl_of(name, obj):
78 if isinstance(obj, asdl.Product) or isinstance(obj, asdl.Constructor):
79 fields = ", ".join(map(str, obj.fields))
80 if fields:
81 fields = "({})".format(fields)
82 return "{}{}".format(name, fields)
83 else:
84 if is_simple(obj):
85 types = " | ".join(type.name for type in obj.types)
86 else:
87 sep = "\n{}| ".format(" " * (len(name) + 1))
88 types = sep.join(
89 asdl_of(type.name, type) for type in obj.types
90 )
91 return "{} = {}".format(name, types)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +000092
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000093class EmitVisitor(asdl.VisitorBase):
94 """Visit that emits lines"""
95
96 def __init__(self, file):
97 self.file = file
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +020098 self.identifiers = set()
Dino Viehlandac46eb42019-09-11 10:16:34 -070099 self.singletons = set()
100 self.types = set()
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000101 super(EmitVisitor, self).__init__()
102
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200103 def emit_identifier(self, name):
Dino Viehlandac46eb42019-09-11 10:16:34 -0700104 self.identifiers.add(str(name))
105
106 def emit_singleton(self, name):
107 self.singletons.add(str(name))
108
109 def emit_type(self, name):
110 self.types.add(str(name))
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200111
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000112 def emit(self, s, depth, reflow=True):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000113 # XXX reflow long lines?
114 if reflow:
115 lines = reflow_lines(s, depth)
116 else:
117 lines = [s]
118 for line in lines:
Serhiy Storchaka5d84cb32017-09-15 06:28:22 +0300119 if line:
120 line = (" " * TABSIZE * depth) + line
121 self.file.write(line + "\n")
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000122
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000123
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000124class TypeDefVisitor(EmitVisitor):
125 def visitModule(self, mod):
126 for dfn in mod.dfns:
127 self.visit(dfn)
128
129 def visitType(self, type, depth=0):
130 self.visit(type.value, type.name, depth)
131
132 def visitSum(self, sum, name, depth):
133 if is_simple(sum):
134 self.simple_sum(sum, name, depth)
135 else:
136 self.sum_with_constructors(sum, name, depth)
137
138 def simple_sum(self, sum, name, depth):
139 enum = []
140 for i in range(len(sum.types)):
141 type = sum.types[i]
142 enum.append("%s=%d" % (type.name, i + 1))
143 enums = ", ".join(enum)
144 ctype = get_c_type(name)
145 s = "typedef enum _%s { %s } %s;" % (name, enums, ctype)
146 self.emit(s, depth)
147 self.emit("", depth)
148
149 def sum_with_constructors(self, sum, name, depth):
150 ctype = get_c_type(name)
151 s = "typedef struct _%(name)s *%(ctype)s;" % locals()
152 self.emit(s, depth)
153 self.emit("", depth)
154
155 def visitProduct(self, product, name, depth):
156 ctype = get_c_type(name)
157 s = "typedef struct _%(name)s *%(ctype)s;" % locals()
158 self.emit(s, depth)
159 self.emit("", depth)
160
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000161
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000162class StructVisitor(EmitVisitor):
Eli Bendersky5e3d3382014-05-09 17:58:22 -0700163 """Visitor to generate typedefs for AST."""
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000164
165 def visitModule(self, mod):
166 for dfn in mod.dfns:
167 self.visit(dfn)
168
169 def visitType(self, type, depth=0):
170 self.visit(type.value, type.name, depth)
171
172 def visitSum(self, sum, name, depth):
173 if not is_simple(sum):
174 self.sum_with_constructors(sum, name, depth)
175
176 def sum_with_constructors(self, sum, name, depth):
177 def emit(s, depth=depth):
178 self.emit(s % sys._getframe(1).f_locals, depth)
179 enum = []
180 for i in range(len(sum.types)):
181 type = sum.types[i]
182 enum.append("%s_kind=%d" % (type.name, i + 1))
183
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000184 emit("enum _%(name)s_kind {" + ", ".join(enum) + "};")
185
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186 emit("struct _%(name)s {")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000187 emit("enum _%(name)s_kind kind;", depth + 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188 emit("union {", depth + 1)
189 for t in sum.types:
190 self.visit(t, depth + 2)
191 emit("} v;", depth + 1)
192 for field in sum.attributes:
193 # rudimentary attribute handling
194 type = str(field.type)
195 assert type in asdl.builtin_types, type
196 emit("%s %s;" % (type, field.name), depth + 1);
197 emit("};")
198 emit("")
199
200 def visitConstructor(self, cons, depth):
201 if cons.fields:
202 self.emit("struct {", depth)
203 for f in cons.fields:
204 self.visit(f, depth + 1)
205 self.emit("} %s;" % cons.name, depth)
206 self.emit("", depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000207
208 def visitField(self, field, depth):
209 # XXX need to lookup field.type, because it might be something
210 # like a builtin...
211 ctype = get_c_type(field.type)
212 name = field.name
213 if field.seq:
Eli Bendersky5e3d3382014-05-09 17:58:22 -0700214 if field.type == 'cmpop':
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000215 self.emit("asdl_int_seq *%(name)s;" % locals(), depth)
216 else:
217 self.emit("asdl_seq *%(name)s;" % locals(), depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000218 else:
219 self.emit("%(ctype)s %(name)s;" % locals(), depth)
220
221 def visitProduct(self, product, name, depth):
222 self.emit("struct _%(name)s {" % locals(), depth)
223 for f in product.fields:
224 self.visit(f, depth + 1)
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700225 for field in product.attributes:
226 # rudimentary attribute handling
227 type = str(field.type)
228 assert type in asdl.builtin_types, type
229 self.emit("%s %s;" % (type, field.name), depth + 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000230 self.emit("};", depth)
231 self.emit("", depth)
232
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000233
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000234class PrototypeVisitor(EmitVisitor):
235 """Generate function prototypes for the .h file"""
236
237 def visitModule(self, mod):
238 for dfn in mod.dfns:
239 self.visit(dfn)
240
241 def visitType(self, type):
242 self.visit(type.value, type.name)
243
244 def visitSum(self, sum, name):
245 if is_simple(sum):
246 pass # XXX
247 else:
248 for t in sum.types:
249 self.visit(t, name, sum.attributes)
250
251 def get_args(self, fields):
252 """Return list of C argument into, one for each field.
253
254 Argument info is 3-tuple of a C type, variable name, and flag
255 that is true if type can be NULL.
256 """
257 args = []
258 unnamed = {}
259 for f in fields:
260 if f.name is None:
261 name = f.type
262 c = unnamed[name] = unnamed.get(name, 0) + 1
263 if c > 1:
264 name = "name%d" % (c - 1)
265 else:
266 name = f.name
267 # XXX should extend get_c_type() to handle this
268 if f.seq:
Eli Bendersky5e3d3382014-05-09 17:58:22 -0700269 if f.type == 'cmpop':
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000270 ctype = "asdl_int_seq *"
271 else:
272 ctype = "asdl_seq *"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000273 else:
274 ctype = get_c_type(f.type)
275 args.append((ctype, name, f.opt or f.seq))
276 return args
277
278 def visitConstructor(self, cons, type, attrs):
279 args = self.get_args(cons.fields)
280 attrs = self.get_args(attrs)
281 ctype = get_c_type(type)
282 self.emit_function(cons.name, ctype, args, attrs)
283
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000284 def emit_function(self, name, ctype, args, attrs, union=True):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000285 args = args + attrs
286 if args:
287 argstr = ", ".join(["%s %s" % (atype, aname)
288 for atype, aname, opt in args])
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000289 argstr += ", PyArena *arena"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000290 else:
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000291 argstr = "PyArena *arena"
Thomas Woutersb2137042007-02-01 18:02:27 +0000292 margs = "a0"
293 for i in range(1, len(args)+1):
294 margs += ", a%d" % i
295 self.emit("#define %s(%s) _Py_%s(%s)" % (name, margs, name, margs), 0,
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000296 reflow=False)
297 self.emit("%s _Py_%s(%s);" % (ctype, name, argstr), False)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298
299 def visitProduct(self, prod, name):
300 self.emit_function(name, get_c_type(name),
Victor Stinnerc106c682015-11-06 17:01:48 +0100301 self.get_args(prod.fields),
302 self.get_args(prod.attributes),
303 union=False)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000304
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000305
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000306class FunctionVisitor(PrototypeVisitor):
307 """Visitor to generate constructor functions for AST."""
308
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000309 def emit_function(self, name, ctype, args, attrs, union=True):
310 def emit(s, depth=0, reflow=True):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000311 self.emit(s, depth, reflow)
312 argstr = ", ".join(["%s %s" % (atype, aname)
313 for atype, aname, opt in args + attrs])
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000314 if argstr:
315 argstr += ", PyArena *arena"
316 else:
317 argstr = "PyArena *arena"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000318 self.emit("%s" % ctype, 0)
319 emit("%s(%s)" % (name, argstr))
320 emit("{")
321 emit("%s p;" % ctype, 1)
322 for argtype, argname, opt in args:
Neal Norwitz3591bbe2007-02-26 19:04:49 +0000323 if not opt and argtype != "int":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000324 emit("if (!%s) {" % argname, 1)
325 emit("PyErr_SetString(PyExc_ValueError,", 2)
Batuhan Taskaya091951a2020-05-06 17:29:32 +0300326 msg = "field '%s' is required for %s" % (argname, name)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000327 emit(' "%s");' % msg,
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000328 2, reflow=False)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329 emit('return NULL;', 2)
330 emit('}', 1)
331
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000332 emit("p = (%s)PyArena_Malloc(arena, sizeof(*p));" % ctype, 1);
Thomas Woutersa44f3a32007-02-26 18:20:15 +0000333 emit("if (!p)", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000334 emit("return NULL;", 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000335 if union:
336 self.emit_body_union(name, args, attrs)
337 else:
338 self.emit_body_struct(name, args, attrs)
339 emit("return p;", 1)
340 emit("}")
341 emit("")
342
343 def emit_body_union(self, name, args, attrs):
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000344 def emit(s, depth=0, reflow=True):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345 self.emit(s, depth, reflow)
346 emit("p->kind = %s_kind;" % name, 1)
347 for argtype, argname, opt in args:
348 emit("p->v.%s.%s = %s;" % (name, argname, argname), 1)
349 for argtype, argname, opt in attrs:
350 emit("p->%s = %s;" % (argname, argname), 1)
351
352 def emit_body_struct(self, name, args, attrs):
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000353 def emit(s, depth=0, reflow=True):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354 self.emit(s, depth, reflow)
355 for argtype, argname, opt in args:
356 emit("p->%s = %s;" % (argname, argname), 1)
Victor Stinnerc106c682015-11-06 17:01:48 +0100357 for argtype, argname, opt in attrs:
358 emit("p->%s = %s;" % (argname, argname), 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000359
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000360
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000361class PickleVisitor(EmitVisitor):
362
363 def visitModule(self, mod):
364 for dfn in mod.dfns:
365 self.visit(dfn)
366
367 def visitType(self, type):
368 self.visit(type.value, type.name)
369
370 def visitSum(self, sum, name):
371 pass
372
373 def visitProduct(self, sum, name):
374 pass
375
376 def visitConstructor(self, cons, name):
377 pass
378
379 def visitField(self, sum):
380 pass
381
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000382
383class Obj2ModPrototypeVisitor(PickleVisitor):
384 def visitProduct(self, prod, name):
385 code = "static int obj2ast_%s(PyObject* obj, %s* out, PyArena* arena);"
386 self.emit(code % (name, get_c_type(name)), 0)
387
388 visitSum = visitProduct
389
390
391class Obj2ModVisitor(PickleVisitor):
392 def funcHeader(self, name):
393 ctype = get_c_type(name)
394 self.emit("int", 0)
395 self.emit("obj2ast_%s(PyObject* obj, %s* out, PyArena* arena)" % (name, ctype), 0)
396 self.emit("{", 0)
Benjamin Peterson0e9e98e2010-11-20 02:01:45 +0000397 self.emit("int isinstance;", 1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000398 self.emit("", 0)
399
Benjamin Peterson5b066812010-11-20 01:38:49 +0000400 def sumTrailer(self, name, add_label=False):
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000401 self.emit("", 0)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000402 # there's really nothing more we can do if this fails ...
Benjamin Peterson5b066812010-11-20 01:38:49 +0000403 error = "expected some sort of %s, but got %%R" % name
404 format = "PyErr_Format(PyExc_TypeError, \"%s\", obj);"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000405 self.emit(format % error, 1, reflow=False)
Benjamin Peterson5b066812010-11-20 01:38:49 +0000406 if add_label:
407 self.emit("failed:", 1)
Benjamin Peterson0a4dae52010-11-21 15:12:34 +0000408 self.emit("Py_XDECREF(tmp);", 1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000409 self.emit("return 1;", 1)
410 self.emit("}", 0)
411 self.emit("", 0)
412
413 def simpleSum(self, sum, name):
414 self.funcHeader(name)
415 for t in sum.types:
Benjamin Peterson97dd9872009-12-13 01:23:39 +0000416 line = ("isinstance = PyObject_IsInstance(obj, "
Dino Viehlandac46eb42019-09-11 10:16:34 -0700417 "astmodulestate_global->%s_type);")
Benjamin Peterson97dd9872009-12-13 01:23:39 +0000418 self.emit(line % (t.name,), 1)
419 self.emit("if (isinstance == -1) {", 1)
420 self.emit("return 1;", 2)
421 self.emit("}", 1)
422 self.emit("if (isinstance) {", 1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000423 self.emit("*out = %s;" % t.name, 2)
424 self.emit("return 0;", 2)
425 self.emit("}", 1)
426 self.sumTrailer(name)
427
428 def buildArgs(self, fields):
429 return ", ".join(fields + ["arena"])
430
431 def complexSum(self, sum, name):
432 self.funcHeader(name)
Benjamin Petersond8f65972010-11-20 04:31:07 +0000433 self.emit("PyObject *tmp = NULL;", 1)
Dino Viehlandac46eb42019-09-11 10:16:34 -0700434 self.emit("PyObject *tp;", 1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000435 for a in sum.attributes:
436 self.visitAttributeDeclaration(a, name, sum=sum)
437 self.emit("", 0)
438 # XXX: should we only do this for 'expr'?
439 self.emit("if (obj == Py_None) {", 1)
440 self.emit("*out = NULL;", 2)
441 self.emit("return 0;", 2)
442 self.emit("}", 1)
443 for a in sum.attributes:
444 self.visitField(a, name, sum=sum, depth=1)
445 for t in sum.types:
Dino Viehlandac46eb42019-09-11 10:16:34 -0700446 self.emit("tp = astmodulestate_global->%s_type;" % (t.name,), 1)
447 self.emit("isinstance = PyObject_IsInstance(obj, tp);", 1)
Benjamin Peterson97dd9872009-12-13 01:23:39 +0000448 self.emit("if (isinstance == -1) {", 1)
449 self.emit("return 1;", 2)
450 self.emit("}", 1)
451 self.emit("if (isinstance) {", 1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000452 for f in t.fields:
453 self.visitFieldDeclaration(f, t.name, sum=sum, depth=2)
454 self.emit("", 0)
455 for f in t.fields:
456 self.visitField(f, t.name, sum=sum, depth=2)
Eli Bendersky5e3d3382014-05-09 17:58:22 -0700457 args = [f.name for f in t.fields] + [a.name for a in sum.attributes]
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000458 self.emit("*out = %s(%s);" % (t.name, self.buildArgs(args)), 2)
459 self.emit("if (*out == NULL) goto failed;", 2)
460 self.emit("return 0;", 2)
461 self.emit("}", 1)
Benjamin Peterson5b066812010-11-20 01:38:49 +0000462 self.sumTrailer(name, True)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000463
464 def visitAttributeDeclaration(self, a, name, sum=sum):
465 ctype = get_c_type(a.type)
466 self.emit("%s %s;" % (ctype, a.name), 1)
467
468 def visitSum(self, sum, name):
469 if is_simple(sum):
470 self.simpleSum(sum, name)
471 else:
472 self.complexSum(sum, name)
473
474 def visitProduct(self, prod, name):
475 ctype = get_c_type(name)
476 self.emit("int", 0)
477 self.emit("obj2ast_%s(PyObject* obj, %s* out, PyArena* arena)" % (name, ctype), 0)
478 self.emit("{", 0)
479 self.emit("PyObject* tmp = NULL;", 1)
480 for f in prod.fields:
481 self.visitFieldDeclaration(f, name, prod=prod, depth=1)
Victor Stinnerc106c682015-11-06 17:01:48 +0100482 for a in prod.attributes:
483 self.visitFieldDeclaration(a, name, prod=prod, depth=1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000484 self.emit("", 0)
485 for f in prod.fields:
486 self.visitField(f, name, prod=prod, depth=1)
Victor Stinnerc106c682015-11-06 17:01:48 +0100487 for a in prod.attributes:
488 self.visitField(a, name, prod=prod, depth=1)
Eli Bendersky5e3d3382014-05-09 17:58:22 -0700489 args = [f.name for f in prod.fields]
Victor Stinnerc106c682015-11-06 17:01:48 +0100490 args.extend([a.name for a in prod.attributes])
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000491 self.emit("*out = %s(%s);" % (name, self.buildArgs(args)), 1)
492 self.emit("return 0;", 1)
493 self.emit("failed:", 0)
494 self.emit("Py_XDECREF(tmp);", 1)
495 self.emit("return 1;", 1)
496 self.emit("}", 0)
497 self.emit("", 0)
498
499 def visitFieldDeclaration(self, field, name, sum=None, prod=None, depth=0):
500 ctype = get_c_type(field.type)
501 if field.seq:
502 if self.isSimpleType(field):
503 self.emit("asdl_int_seq* %s;" % field.name, depth)
504 else:
505 self.emit("asdl_seq* %s;" % field.name, depth)
506 else:
507 ctype = get_c_type(field.type)
508 self.emit("%s %s;" % (ctype, field.name), depth)
509
510 def isSimpleSum(self, field):
511 # XXX can the members of this list be determined automatically?
Eli Bendersky5e3d3382014-05-09 17:58:22 -0700512 return field.type in ('expr_context', 'boolop', 'operator',
513 'unaryop', 'cmpop')
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000514
515 def isNumeric(self, field):
516 return get_c_type(field.type) in ("int", "bool")
517
518 def isSimpleType(self, field):
519 return self.isSimpleSum(field) or self.isNumeric(field)
520
521 def visitField(self, field, name, sum=None, prod=None, depth=0):
522 ctype = get_c_type(field.type)
Dino Viehlandac46eb42019-09-11 10:16:34 -0700523 line = "if (_PyObject_LookupAttr(obj, astmodulestate_global->%s, &tmp) < 0) {"
524 self.emit(line % field.name, depth)
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200525 self.emit("return 1;", depth+1)
526 self.emit("}", depth)
Serhiy Storchakabba22392017-11-11 16:41:32 +0200527 if not field.opt:
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200528 self.emit("if (tmp == NULL) {", depth)
529 message = "required field \\\"%s\\\" missing from %s" % (field.name, name)
530 format = "PyErr_SetString(PyExc_TypeError, \"%s\");"
531 self.emit(format % message, depth+1, reflow=False)
532 self.emit("return 1;", depth+1)
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700533 else:
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200534 self.emit("if (tmp == NULL || tmp == Py_None) {", depth)
535 self.emit("Py_CLEAR(tmp);", depth+1)
536 if self.isNumeric(field):
537 self.emit("%s = 0;" % field.name, depth+1)
538 elif not self.isSimpleType(field):
539 self.emit("%s = NULL;" % field.name, depth+1)
540 else:
541 raise TypeError("could not determine the default value for %s" % field.name)
542 self.emit("}", depth)
543 self.emit("else {", depth)
544
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000545 self.emit("int res;", depth+1)
546 if field.seq:
547 self.emit("Py_ssize_t len;", depth+1)
548 self.emit("Py_ssize_t i;", depth+1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000549 self.emit("if (!PyList_Check(tmp)) {", depth+1)
550 self.emit("PyErr_Format(PyExc_TypeError, \"%s field \\\"%s\\\" must "
Dino Viehlandac46eb42019-09-11 10:16:34 -0700551 "be a list, not a %%.200s\", _PyType_Name(Py_TYPE(tmp)));" %
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000552 (name, field.name),
553 depth+2, reflow=False)
554 self.emit("goto failed;", depth+2)
555 self.emit("}", depth+1)
556 self.emit("len = PyList_GET_SIZE(tmp);", depth+1)
557 if self.isSimpleType(field):
Antoine Pitroud01d396e2013-10-12 22:52:43 +0200558 self.emit("%s = _Py_asdl_int_seq_new(len, arena);" % field.name, depth+1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000559 else:
Antoine Pitroud01d396e2013-10-12 22:52:43 +0200560 self.emit("%s = _Py_asdl_seq_new(len, arena);" % field.name, depth+1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000561 self.emit("if (%s == NULL) goto failed;" % field.name, depth+1)
562 self.emit("for (i = 0; i < len; i++) {", depth+1)
Yuan Chao Chou2af565b2017-08-04 10:53:12 -0700563 self.emit("%s val;" % ctype, depth+2)
Serhiy Storchaka43c97312019-09-10 13:02:30 +0300564 self.emit("PyObject *tmp2 = PyList_GET_ITEM(tmp, i);", depth+2)
565 self.emit("Py_INCREF(tmp2);", depth+2)
566 self.emit("res = obj2ast_%s(tmp2, &val, arena);" %
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000567 field.type, depth+2, reflow=False)
Serhiy Storchaka43c97312019-09-10 13:02:30 +0300568 self.emit("Py_DECREF(tmp2);", depth+2)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000569 self.emit("if (res != 0) goto failed;", depth+2)
Serhiy Storchakacf380602016-10-07 21:51:28 +0300570 self.emit("if (len != PyList_GET_SIZE(tmp)) {", depth+2)
571 self.emit("PyErr_SetString(PyExc_RuntimeError, \"%s field \\\"%s\\\" "
572 "changed size during iteration\");" %
573 (name, field.name),
574 depth+3, reflow=False)
575 self.emit("goto failed;", depth+3)
576 self.emit("}", depth+2)
Yuan Chao Chou2af565b2017-08-04 10:53:12 -0700577 self.emit("asdl_seq_SET(%s, i, val);" % field.name, depth+2)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000578 self.emit("}", depth+1)
579 else:
580 self.emit("res = obj2ast_%s(tmp, &%s, arena);" %
581 (field.type, field.name), depth+1)
582 self.emit("if (res != 0) goto failed;", depth+1)
583
Victor Stinner1acc1292013-07-27 00:03:47 +0200584 self.emit("Py_CLEAR(tmp);", depth+1)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000585 self.emit("}", depth)
586
587
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000588class MarshalPrototypeVisitor(PickleVisitor):
589
590 def prototype(self, sum, name):
591 ctype = get_c_type(name)
Neal Norwitz6576bd82005-11-13 18:41:28 +0000592 self.emit("static int marshal_write_%s(PyObject **, int *, %s);"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000593 % (name, ctype), 0)
594
595 visitProduct = visitSum = prototype
596
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000597
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000598class PyTypesDeclareVisitor(PickleVisitor):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000599
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000600 def visitProduct(self, prod, name):
Dino Viehlandac46eb42019-09-11 10:16:34 -0700601 self.emit_type("%s_type" % name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000602 self.emit("static PyObject* ast2obj_%s(void*);" % name, 0)
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700603 if prod.attributes:
604 for a in prod.attributes:
605 self.emit_identifier(a.name)
Serhiy Storchaka43c97312019-09-10 13:02:30 +0300606 self.emit("static const char * const %s_attributes[] = {" % name, 0)
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700607 for a in prod.attributes:
608 self.emit('"%s",' % a.name, 1)
609 self.emit("};", 0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000610 if prod.fields:
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200611 for f in prod.fields:
612 self.emit_identifier(f.name)
Serhiy Storchaka43c97312019-09-10 13:02:30 +0300613 self.emit("static const char * const %s_fields[]={" % name,0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000614 for f in prod.fields:
615 self.emit('"%s",' % f.name, 1)
616 self.emit("};", 0)
Tim Peters710ab3b2006-02-28 18:30:36 +0000617
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000618 def visitSum(self, sum, name):
Dino Viehlandac46eb42019-09-11 10:16:34 -0700619 self.emit_type("%s_type" % name)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000620 if sum.attributes:
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200621 for a in sum.attributes:
622 self.emit_identifier(a.name)
Serhiy Storchaka43c97312019-09-10 13:02:30 +0300623 self.emit("static const char * const %s_attributes[] = {" % name, 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000624 for a in sum.attributes:
625 self.emit('"%s",' % a.name, 1)
626 self.emit("};", 0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000627 ptype = "void*"
628 if is_simple(sum):
629 ptype = get_c_type(name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000630 for t in sum.types:
Dino Viehlandac46eb42019-09-11 10:16:34 -0700631 self.emit_singleton("%s_singleton" % t.name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000632 self.emit("static PyObject* ast2obj_%s(%s);" % (name, ptype), 0)
633 for t in sum.types:
634 self.visitConstructor(t, name)
Tim Peters710ab3b2006-02-28 18:30:36 +0000635
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000636 def visitConstructor(self, cons, name):
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000637 if cons.fields:
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200638 for t in cons.fields:
639 self.emit_identifier(t.name)
Serhiy Storchaka43c97312019-09-10 13:02:30 +0300640 self.emit("static const char * const %s_fields[]={" % cons.name, 0)
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000641 for t in cons.fields:
642 self.emit('"%s",' % t.name, 1)
643 self.emit("};",0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000644
645class PyTypesVisitor(PickleVisitor):
646
647 def visitModule(self, mod):
648 self.emit("""
INADA Naokifc489082017-01-25 22:33:43 +0900649
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700650typedef struct {
Victor Stinner45e50de2012-03-13 01:17:31 +0100651 PyObject_HEAD
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700652 PyObject *dict;
653} AST_object;
654
Benjamin Peterson1767e022012-03-14 21:50:29 -0500655static void
656ast_dealloc(AST_object *self)
657{
INADA Naokia6296d32017-08-24 14:55:17 +0900658 /* bpo-31095: UnTrack is needed before calling any callbacks */
Eddie Elizondo0247e802019-09-14 09:38:17 -0400659 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +0900660 PyObject_GC_UnTrack(self);
Benjamin Peterson1767e022012-03-14 21:50:29 -0500661 Py_CLEAR(self->dict);
Eddie Elizondo0247e802019-09-14 09:38:17 -0400662 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
663 assert(free_func != NULL);
664 free_func(self);
665 Py_DECREF(tp);
Benjamin Peterson1767e022012-03-14 21:50:29 -0500666}
667
Neal Norwitz207c9f32008-03-31 04:42:11 +0000668static int
Benjamin Peterson81071762012-07-08 11:03:46 -0700669ast_traverse(AST_object *self, visitproc visit, void *arg)
670{
671 Py_VISIT(self->dict);
672 return 0;
673}
674
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300675static int
Benjamin Peterson81071762012-07-08 11:03:46 -0700676ast_clear(AST_object *self)
677{
678 Py_CLEAR(self->dict);
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300679 return 0;
Benjamin Peterson81071762012-07-08 11:03:46 -0700680}
681
682static int
Neal Norwitz207c9f32008-03-31 04:42:11 +0000683ast_type_init(PyObject *self, PyObject *args, PyObject *kw)
684{
685 Py_ssize_t i, numfields = 0;
686 int res = -1;
687 PyObject *key, *value, *fields;
Dino Viehlandac46eb42019-09-11 10:16:34 -0700688 if (_PyObject_LookupAttr((PyObject*)Py_TYPE(self), astmodulestate_global->_fields, &fields) < 0) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200689 goto cleanup;
690 }
Neal Norwitz207c9f32008-03-31 04:42:11 +0000691 if (fields) {
692 numfields = PySequence_Size(fields);
693 if (numfields == -1)
694 goto cleanup;
695 }
INADA Naoki4c78c522017-02-24 02:48:17 +0900696
Neal Norwitz207c9f32008-03-31 04:42:11 +0000697 res = 0; /* if no error occurs, this stays 0 to the end */
INADA Naoki4c78c522017-02-24 02:48:17 +0900698 if (numfields < PyTuple_GET_SIZE(args)) {
699 PyErr_Format(PyExc_TypeError, "%.400s constructor takes at most "
700 "%zd positional argument%s",
Dino Viehlandac46eb42019-09-11 10:16:34 -0700701 _PyType_Name(Py_TYPE(self)),
INADA Naoki4c78c522017-02-24 02:48:17 +0900702 numfields, numfields == 1 ? "" : "s");
703 res = -1;
704 goto cleanup;
705 }
706 for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
707 /* cannot be reached when fields is NULL */
708 PyObject *name = PySequence_GetItem(fields, i);
709 if (!name) {
Neal Norwitz207c9f32008-03-31 04:42:11 +0000710 res = -1;
711 goto cleanup;
712 }
INADA Naoki4c78c522017-02-24 02:48:17 +0900713 res = PyObject_SetAttr(self, name, PyTuple_GET_ITEM(args, i));
714 Py_DECREF(name);
715 if (res < 0)
716 goto cleanup;
Neal Norwitz207c9f32008-03-31 04:42:11 +0000717 }
718 if (kw) {
719 i = 0; /* needed by PyDict_Next */
720 while (PyDict_Next(kw, &i, &key, &value)) {
721 res = PyObject_SetAttr(self, key, value);
722 if (res < 0)
723 goto cleanup;
724 }
725 }
726 cleanup:
727 Py_XDECREF(fields);
728 return res;
729}
730
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000731/* Pickling support */
732static PyObject *
733ast_type_reduce(PyObject *self, PyObject *unused)
734{
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200735 PyObject *dict;
Dino Viehlandac46eb42019-09-11 10:16:34 -0700736 if (_PyObject_LookupAttr(self, astmodulestate_global->__dict__, &dict) < 0) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200737 return NULL;
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000738 }
739 if (dict) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200740 return Py_BuildValue("O()N", Py_TYPE(self), dict);
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000741 }
742 return Py_BuildValue("O()", Py_TYPE(self));
743}
744
Eddie Elizondo3368f3c2019-09-19 09:29:05 -0700745static PyMemberDef ast_type_members[] = {
746 {"__dictoffset__", T_PYSSIZET, offsetof(AST_object, dict), READONLY},
747 {NULL} /* Sentinel */
748};
749
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000750static PyMethodDef ast_type_methods[] = {
751 {"__reduce__", ast_type_reduce, METH_NOARGS, NULL},
752 {NULL}
753};
754
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700755static PyGetSetDef ast_type_getsets[] = {
756 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
757 {NULL}
758};
759
Dino Viehlandac46eb42019-09-11 10:16:34 -0700760static PyType_Slot AST_type_slots[] = {
761 {Py_tp_dealloc, ast_dealloc},
762 {Py_tp_getattro, PyObject_GenericGetAttr},
763 {Py_tp_setattro, PyObject_GenericSetAttr},
764 {Py_tp_traverse, ast_traverse},
765 {Py_tp_clear, ast_clear},
Eddie Elizondo3368f3c2019-09-19 09:29:05 -0700766 {Py_tp_members, ast_type_members},
Dino Viehlandac46eb42019-09-11 10:16:34 -0700767 {Py_tp_methods, ast_type_methods},
768 {Py_tp_getset, ast_type_getsets},
769 {Py_tp_init, ast_type_init},
770 {Py_tp_alloc, PyType_GenericAlloc},
771 {Py_tp_new, PyType_GenericNew},
Dino Viehlandac46eb42019-09-11 10:16:34 -0700772 {Py_tp_free, PyObject_GC_Del},
773 {0, 0},
774};
775
776static PyType_Spec AST_type_spec = {
Serhiy Storchakabace59d2020-03-22 20:33:34 +0200777 "ast.AST",
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700778 sizeof(AST_object),
Neal Norwitz207c9f32008-03-31 04:42:11 +0000779 0,
Dino Viehlandac46eb42019-09-11 10:16:34 -0700780 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
781 AST_type_slots
Neal Norwitz207c9f32008-03-31 04:42:11 +0000782};
783
Dino Viehlandac46eb42019-09-11 10:16:34 -0700784static PyObject *
Batuhan Taşkaya4ab362c2020-03-16 11:12:53 +0300785make_type(const char *type, PyObject* base, const char* const* fields, int num_fields, const char *doc)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000786{
787 PyObject *fnames, *result;
788 int i;
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000789 fnames = PyTuple_New(num_fields);
790 if (!fnames) return NULL;
791 for (i = 0; i < num_fields; i++) {
Serhiy Storchaka43c97312019-09-10 13:02:30 +0300792 PyObject *field = PyUnicode_InternFromString(fields[i]);
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000793 if (!field) {
794 Py_DECREF(fnames);
795 return NULL;
796 }
797 PyTuple_SET_ITEM(fnames, i, field);
798 }
Batuhan Taşkaya4ab362c2020-03-16 11:12:53 +0300799 result = PyObject_CallFunction((PyObject*)&PyType_Type, "s(O){OOOOOs}",
INADA Naokifc489082017-01-25 22:33:43 +0900800 type, base,
Dino Viehlandac46eb42019-09-11 10:16:34 -0700801 astmodulestate_global->_fields, fnames,
802 astmodulestate_global->__module__,
Serhiy Storchakabace59d2020-03-22 20:33:34 +0200803 astmodulestate_global->ast,
Batuhan Taşkaya4ab362c2020-03-16 11:12:53 +0300804 astmodulestate_global->__doc__, doc);
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000805 Py_DECREF(fnames);
Dino Viehlandac46eb42019-09-11 10:16:34 -0700806 return result;
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000807}
808
Serhiy Storchaka43c97312019-09-10 13:02:30 +0300809static int
Dino Viehlandac46eb42019-09-11 10:16:34 -0700810add_attributes(PyObject *type, const char * const *attrs, int num_fields)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000811{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000812 int i, result;
Neal Norwitz207c9f32008-03-31 04:42:11 +0000813 PyObject *s, *l = PyTuple_New(num_fields);
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000814 if (!l)
815 return 0;
816 for (i = 0; i < num_fields; i++) {
Serhiy Storchaka43c97312019-09-10 13:02:30 +0300817 s = PyUnicode_InternFromString(attrs[i]);
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000818 if (!s) {
819 Py_DECREF(l);
820 return 0;
821 }
Neal Norwitz207c9f32008-03-31 04:42:11 +0000822 PyTuple_SET_ITEM(l, i, s);
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000823 }
Dino Viehlandac46eb42019-09-11 10:16:34 -0700824 result = PyObject_SetAttr(type, astmodulestate_global->_attributes, l) >= 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000825 Py_DECREF(l);
826 return result;
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000827}
828
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000829/* Conversion AST -> Python */
830
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000831static PyObject* ast2obj_list(asdl_seq *seq, PyObject* (*func)(void*))
832{
Benjamin Peterson77fa9372012-05-15 10:10:27 -0700833 Py_ssize_t i, n = asdl_seq_LEN(seq);
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000834 PyObject *result = PyList_New(n);
835 PyObject *value;
836 if (!result)
837 return NULL;
838 for (i = 0; i < n; i++) {
839 value = func(asdl_seq_GET(seq, i));
840 if (!value) {
841 Py_DECREF(result);
842 return NULL;
843 }
844 PyList_SET_ITEM(result, i, value);
845 }
846 return result;
847}
848
849static PyObject* ast2obj_object(void *o)
850{
851 if (!o)
852 o = Py_None;
853 Py_INCREF((PyObject*)o);
854 return (PyObject*)o;
855}
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100856#define ast2obj_constant ast2obj_object
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000857#define ast2obj_identifier ast2obj_object
858#define ast2obj_string ast2obj_object
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000859
Thomas Woutersa44f3a32007-02-26 18:20:15 +0000860static PyObject* ast2obj_int(long b)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000861{
Christian Heimes2b1c5922007-12-02 22:43:00 +0000862 return PyLong_FromLong(b);
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000863}
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000864
865/* Conversion Python -> AST */
866
867static int obj2ast_object(PyObject* obj, PyObject** out, PyArena* arena)
868{
869 if (obj == Py_None)
870 obj = NULL;
Christian Heimes70c94e72013-07-27 00:33:13 +0200871 if (obj) {
872 if (PyArena_AddPyObject(arena, obj) < 0) {
873 *out = NULL;
874 return -1;
875 }
876 Py_INCREF(obj);
877 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000878 *out = obj;
879 return 0;
880}
881
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100882static int obj2ast_constant(PyObject* obj, PyObject** out, PyArena* arena)
883{
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300884 if (PyArena_AddPyObject(arena, obj) < 0) {
885 *out = NULL;
886 return -1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100887 }
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300888 Py_INCREF(obj);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100889 *out = obj;
890 return 0;
891}
892
Benjamin Peterson180e6352011-07-22 11:09:07 -0500893static int obj2ast_identifier(PyObject* obj, PyObject** out, PyArena* arena)
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500894{
Benjamin Peterson180e6352011-07-22 11:09:07 -0500895 if (!PyUnicode_CheckExact(obj) && obj != Py_None) {
896 PyErr_SetString(PyExc_TypeError, "AST identifier must be of type str");
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500897 return 1;
898 }
899 return obj2ast_object(obj, out, arena);
900}
901
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800902static int obj2ast_string(PyObject* obj, PyObject** out, PyArena* arena)
903{
904 if (!PyUnicode_CheckExact(obj) && !PyBytes_CheckExact(obj)) {
905 PyErr_SetString(PyExc_TypeError, "AST string must be of type str");
906 return 1;
907 }
908 return obj2ast_object(obj, out, arena);
909}
910
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000911static int obj2ast_int(PyObject* obj, int* out, PyArena* arena)
912{
913 int i;
914 if (!PyLong_Check(obj)) {
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100915 PyErr_Format(PyExc_ValueError, "invalid integer value: %R", obj);
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000916 return 1;
917 }
918
Serhiy Storchaka481d3af2015-09-06 23:29:04 +0300919 i = _PyLong_AsInt(obj);
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000920 if (i == -1 && PyErr_Occurred())
921 return 1;
922 *out = i;
923 return 0;
924}
925
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +0000926static int add_ast_fields(void)
Benjamin Peterson206e3072008-10-19 14:07:49 +0000927{
Dino Viehlandac46eb42019-09-11 10:16:34 -0700928 PyObject *empty_tuple;
Benjamin Peterson206e3072008-10-19 14:07:49 +0000929 empty_tuple = PyTuple_New(0);
930 if (!empty_tuple ||
Dino Viehlandac46eb42019-09-11 10:16:34 -0700931 PyObject_SetAttrString(astmodulestate_global->AST_type, "_fields", empty_tuple) < 0 ||
932 PyObject_SetAttrString(astmodulestate_global->AST_type, "_attributes", empty_tuple) < 0) {
Benjamin Peterson206e3072008-10-19 14:07:49 +0000933 Py_XDECREF(empty_tuple);
934 return -1;
935 }
936 Py_DECREF(empty_tuple);
937 return 0;
938}
939
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000940""", 0, reflow=False)
941
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000942 self.emit("static int init_types(void)",0)
943 self.emit("{", 0)
Dino Viehlandac46eb42019-09-11 10:16:34 -0700944 self.emit("PyObject *m;", 1)
945 self.emit("if (PyState_FindModule(&_astmodule) == NULL) {", 1)
946 self.emit("m = PyModule_Create(&_astmodule);", 2)
947 self.emit("if (!m) return 0;", 2)
948 self.emit("PyState_AddModule(m, &_astmodule);", 2)
949 self.emit("}", 1)
950 self.emit("astmodulestate *state = astmodulestate_global;", 1)
951 self.emit("if (state->initialized) return 1;", 1)
952 self.emit("if (init_identifiers() < 0) return 0;", 1)
953 self.emit("state->AST_type = PyType_FromSpec(&AST_type_spec);", 1)
954 self.emit("if (!state->AST_type) return 0;", 1)
Benjamin Peterson206e3072008-10-19 14:07:49 +0000955 self.emit("if (add_ast_fields() < 0) return 0;", 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000956 for dfn in mod.dfns:
957 self.visit(dfn)
Dino Viehlandac46eb42019-09-11 10:16:34 -0700958 self.emit("state->initialized = 1;", 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000959 self.emit("return 1;", 1);
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000960 self.emit("}", 0)
961
962 def visitProduct(self, prod, name):
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000963 if prod.fields:
Eli Bendersky5e3d3382014-05-09 17:58:22 -0700964 fields = name+"_fields"
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000965 else:
966 fields = "NULL"
Batuhan Taşkaya4ab362c2020-03-16 11:12:53 +0300967 self.emit('state->%s_type = make_type("%s", state->AST_type, %s, %d,' %
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000968 (name, name, fields, len(prod.fields)), 1)
Batuhan Taşkaya4ab362c2020-03-16 11:12:53 +0300969 self.emit('%s);' % reflow_c_string(asdl_of(name, prod), 2), 2, reflow=False)
Dino Viehlandac46eb42019-09-11 10:16:34 -0700970 self.emit("if (!state->%s_type) return 0;" % name, 1)
971 self.emit_type("AST_type")
972 self.emit_type("%s_type" % name)
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700973 if prod.attributes:
Dino Viehlandac46eb42019-09-11 10:16:34 -0700974 self.emit("if (!add_attributes(state->%s_type, %s_attributes, %d)) return 0;" %
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700975 (name, name, len(prod.attributes)), 1)
976 else:
Dino Viehlandac46eb42019-09-11 10:16:34 -0700977 self.emit("if (!add_attributes(state->%s_type, NULL, 0)) return 0;" % name, 1)
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200978 self.emit_defaults(name, prod.fields, 1)
979 self.emit_defaults(name, prod.attributes, 1)
Tim Peters710ab3b2006-02-28 18:30:36 +0000980
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000981 def visitSum(self, sum, name):
Batuhan Taşkaya4ab362c2020-03-16 11:12:53 +0300982 self.emit('state->%s_type = make_type("%s", state->AST_type, NULL, 0,' %
Neal Norwitz207c9f32008-03-31 04:42:11 +0000983 (name, name), 1)
Batuhan Taşkaya4ab362c2020-03-16 11:12:53 +0300984 self.emit('%s);' % reflow_c_string(asdl_of(name, sum), 2), 2, reflow=False)
Dino Viehlandac46eb42019-09-11 10:16:34 -0700985 self.emit_type("%s_type" % name)
986 self.emit("if (!state->%s_type) return 0;" % name, 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000987 if sum.attributes:
Dino Viehlandac46eb42019-09-11 10:16:34 -0700988 self.emit("if (!add_attributes(state->%s_type, %s_attributes, %d)) return 0;" %
Martin v. Löwis577b5b92006-02-27 15:23:19 +0000989 (name, name, len(sum.attributes)), 1)
990 else:
Dino Viehlandac46eb42019-09-11 10:16:34 -0700991 self.emit("if (!add_attributes(state->%s_type, NULL, 0)) return 0;" % name, 1)
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200992 self.emit_defaults(name, sum.attributes, 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000993 simple = is_simple(sum)
994 for t in sum.types:
995 self.visitConstructor(t, name, simple)
Tim Peters710ab3b2006-02-28 18:30:36 +0000996
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000997 def visitConstructor(self, cons, name, simple):
Martin v. Löwis8d0701d2006-02-26 23:40:20 +0000998 if cons.fields:
Eli Bendersky5e3d3382014-05-09 17:58:22 -0700999 fields = cons.name+"_fields"
Martin v. Löwis8d0701d2006-02-26 23:40:20 +00001000 else:
1001 fields = "NULL"
Batuhan Taşkaya4ab362c2020-03-16 11:12:53 +03001002 self.emit('state->%s_type = make_type("%s", state->%s_type, %s, %d,' %
Martin v. Löwis8d0701d2006-02-26 23:40:20 +00001003 (cons.name, cons.name, name, fields, len(cons.fields)), 1)
Batuhan Taşkaya4ab362c2020-03-16 11:12:53 +03001004 self.emit('%s);' % reflow_c_string(asdl_of(cons.name, cons), 2), 2, reflow=False)
Dino Viehlandac46eb42019-09-11 10:16:34 -07001005 self.emit("if (!state->%s_type) return 0;" % cons.name, 1)
1006 self.emit_type("%s_type" % cons.name)
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001007 self.emit_defaults(cons.name, cons.fields, 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001008 if simple:
Dino Viehlandac46eb42019-09-11 10:16:34 -07001009 self.emit("state->%s_singleton = PyType_GenericNew((PyTypeObject *)"
1010 "state->%s_type, NULL, NULL);" %
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001011 (cons.name, cons.name), 1)
Dino Viehlandac46eb42019-09-11 10:16:34 -07001012 self.emit("if (!state->%s_singleton) return 0;" % cons.name, 1)
Tim Peters710ab3b2006-02-28 18:30:36 +00001013
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001014 def emit_defaults(self, name, fields, depth):
1015 for field in fields:
1016 if field.opt:
1017 self.emit('if (PyObject_SetAttr(state->%s_type, state->%s, Py_None) == -1)' %
1018 (name, field.name), depth)
1019 self.emit("return 0;", depth+1)
1020
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001021
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001022class ASTModuleVisitor(PickleVisitor):
1023
1024 def visitModule(self, mod):
1025 self.emit("PyMODINIT_FUNC", 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001026 self.emit("PyInit__ast(void)", 0)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001027 self.emit("{", 0)
Dino Viehlandac46eb42019-09-11 10:16:34 -07001028 self.emit("PyObject *m;", 1)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001029 self.emit("if (!init_types()) return NULL;", 1)
Dino Viehlandac46eb42019-09-11 10:16:34 -07001030 self.emit('m = PyState_FindModule(&_astmodule);', 1)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001031 self.emit("if (!m) return NULL;", 1)
Brandt Bucherd2f96672020-02-06 06:45:46 -08001032 self.emit('if (PyModule_AddObject(m, "AST", astmodulestate_global->AST_type) < 0) {', 1)
1033 self.emit('goto error;', 2)
1034 self.emit('}', 1)
Dino Viehlandac46eb42019-09-11 10:16:34 -07001035 self.emit('Py_INCREF(astmodulestate(m)->AST_type);', 1)
Brandt Bucherd2f96672020-02-06 06:45:46 -08001036 self.emit('if (PyModule_AddIntMacro(m, PyCF_ALLOW_TOP_LEVEL_AWAIT) < 0) {', 1)
1037 self.emit("goto error;", 2)
1038 self.emit('}', 1)
1039 self.emit('if (PyModule_AddIntMacro(m, PyCF_ONLY_AST) < 0) {', 1)
1040 self.emit("goto error;", 2)
1041 self.emit('}', 1)
1042 self.emit('if (PyModule_AddIntMacro(m, PyCF_TYPE_COMMENTS) < 0) {', 1)
1043 self.emit("goto error;", 2)
1044 self.emit('}', 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001045 for dfn in mod.dfns:
1046 self.visit(dfn)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001047 self.emit("return m;", 1)
Brandt Bucherd2f96672020-02-06 06:45:46 -08001048 self.emit("error:", 0)
1049 self.emit("Py_DECREF(m);", 1)
1050 self.emit("return NULL;", 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001051 self.emit("}", 0)
1052
1053 def visitProduct(self, prod, name):
1054 self.addObj(name)
Tim Peters710ab3b2006-02-28 18:30:36 +00001055
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001056 def visitSum(self, sum, name):
1057 self.addObj(name)
1058 for t in sum.types:
1059 self.visitConstructor(t, name)
Tim Peters710ab3b2006-02-28 18:30:36 +00001060
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001061 def visitConstructor(self, cons, name):
1062 self.addObj(cons.name)
Tim Peters710ab3b2006-02-28 18:30:36 +00001063
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001064 def addObj(self, name):
Dino Viehlandac46eb42019-09-11 10:16:34 -07001065 self.emit("if (PyModule_AddObject(m, \"%s\", "
Brandt Bucherd2f96672020-02-06 06:45:46 -08001066 "astmodulestate_global->%s_type) < 0) {" % (name, name), 1)
1067 self.emit("goto error;", 2)
1068 self.emit('}', 1)
Dino Viehlandac46eb42019-09-11 10:16:34 -07001069 self.emit("Py_INCREF(astmodulestate(m)->%s_type);" % name, 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001070
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001071
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001072_SPECIALIZED_SEQUENCES = ('stmt', 'expr')
1073
1074def find_sequence(fields, doing_specialization):
1075 """Return True if any field uses a sequence."""
1076 for f in fields:
1077 if f.seq:
1078 if not doing_specialization:
1079 return True
1080 if str(f.type) not in _SPECIALIZED_SEQUENCES:
1081 return True
1082 return False
1083
1084def has_sequence(types, doing_specialization):
1085 for t in types:
1086 if find_sequence(t.fields, doing_specialization):
1087 return True
1088 return False
1089
1090
1091class StaticVisitor(PickleVisitor):
Ezio Melotti7c4a7e62013-08-26 01:32:56 +03001092 CODE = '''Very simple, always emit this static code. Override CODE'''
Neal Norwitz7b5a6042005-11-13 19:14:20 +00001093
1094 def visit(self, object):
1095 self.emit(self.CODE, 0, reflow=False)
1096
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001097
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001098class ObjVisitor(PickleVisitor):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001099
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001100 def func_begin(self, name):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001101 ctype = get_c_type(name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001102 self.emit("PyObject*", 0)
1103 self.emit("ast2obj_%s(void* _o)" % (name), 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001104 self.emit("{", 0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001105 self.emit("%s o = (%s)_o;" % (ctype, ctype), 1)
1106 self.emit("PyObject *result = NULL, *value = NULL;", 1)
Dino Viehlandac46eb42019-09-11 10:16:34 -07001107 self.emit("PyTypeObject *tp;", 1)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001108 self.emit('if (!o) {', 1)
INADA Naokifc489082017-01-25 22:33:43 +09001109 self.emit("Py_RETURN_NONE;", 2)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001110 self.emit("}", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001111 self.emit('', 0)
1112
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001113 def func_end(self):
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001114 self.emit("return result;", 1)
1115 self.emit("failed:", 0)
1116 self.emit("Py_XDECREF(value);", 1)
1117 self.emit("Py_XDECREF(result);", 1)
1118 self.emit("return NULL;", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001119 self.emit("}", 0)
1120 self.emit("", 0)
1121
1122 def visitSum(self, sum, name):
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001123 if is_simple(sum):
1124 self.simpleSum(sum, name)
1125 return
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001126 self.func_begin(name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001127 self.emit("switch (o->kind) {", 1)
1128 for i in range(len(sum.types)):
1129 t = sum.types[i]
1130 self.visitConstructor(t, i + 1, name)
1131 self.emit("}", 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001132 for a in sum.attributes:
1133 self.emit("value = ast2obj_%s(o->%s);" % (a.type, a.name), 1)
1134 self.emit("if (!value) goto failed;", 1)
Dino Viehlandac46eb42019-09-11 10:16:34 -07001135 self.emit('if (PyObject_SetAttr(result, astmodulestate_global->%s, value) < 0)' % a.name, 1)
Martin v. Löwis03e5bc02006-03-02 00:31:27 +00001136 self.emit('goto failed;', 2)
1137 self.emit('Py_DECREF(value);', 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001138 self.func_end()
Tim Peters710ab3b2006-02-28 18:30:36 +00001139
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001140 def simpleSum(self, sum, name):
1141 self.emit("PyObject* ast2obj_%s(%s_ty o)" % (name, name), 0)
1142 self.emit("{", 0)
1143 self.emit("switch(o) {", 1)
1144 for t in sum.types:
1145 self.emit("case %s:" % t.name, 2)
Dino Viehlandac46eb42019-09-11 10:16:34 -07001146 self.emit("Py_INCREF(astmodulestate_global->%s_singleton);" % t.name, 3)
1147 self.emit("return astmodulestate_global->%s_singleton;" % t.name, 3)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001148 self.emit("}", 1)
Batuhan Taskaya091951a2020-05-06 17:29:32 +03001149 self.emit("Py_UNREACHABLE();", 1);
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001150 self.emit("}", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001151
1152 def visitProduct(self, prod, name):
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001153 self.func_begin(name)
Dino Viehlandac46eb42019-09-11 10:16:34 -07001154 self.emit("tp = (PyTypeObject *)astmodulestate_global->%s_type;" % name, 1)
1155 self.emit("result = PyType_GenericNew(tp, NULL, NULL);", 1);
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001156 self.emit("if (!result) return NULL;", 1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001157 for field in prod.fields:
1158 self.visitField(field, name, 1, True)
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001159 for a in prod.attributes:
1160 self.emit("value = ast2obj_%s(o->%s);" % (a.type, a.name), 1)
1161 self.emit("if (!value) goto failed;", 1)
Dino Viehlandac46eb42019-09-11 10:16:34 -07001162 self.emit("if (PyObject_SetAttr(result, astmodulestate_global->%s, value) < 0)" % a.name, 1)
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001163 self.emit('goto failed;', 2)
1164 self.emit('Py_DECREF(value);', 1)
Martin v. Löwis577b5b92006-02-27 15:23:19 +00001165 self.func_end()
Tim Peters536cf992005-12-25 23:18:31 +00001166
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167 def visitConstructor(self, cons, enum, name):
1168 self.emit("case %s_kind:" % cons.name, 1)
Dino Viehlandac46eb42019-09-11 10:16:34 -07001169 self.emit("tp = (PyTypeObject *)astmodulestate_global->%s_type;" % cons.name, 2)
1170 self.emit("result = PyType_GenericNew(tp, NULL, NULL);", 2);
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001171 self.emit("if (!result) goto failed;", 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001172 for f in cons.fields:
1173 self.visitField(f, cons.name, 2, False)
1174 self.emit("break;", 2)
1175
1176 def visitField(self, field, name, depth, product):
1177 def emit(s, d):
1178 self.emit(s, depth + d)
1179 if product:
1180 value = "o->%s" % field.name
1181 else:
1182 value = "o->v.%s.%s" % (name, field.name)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001183 self.set(field, value, depth)
1184 emit("if (!value) goto failed;", 0)
Dino Viehlandac46eb42019-09-11 10:16:34 -07001185 emit("if (PyObject_SetAttr(result, astmodulestate_global->%s, value) == -1)" % field.name, 0)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001186 emit("goto failed;", 1)
1187 emit("Py_DECREF(value);", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001188
1189 def emitSeq(self, field, value, depth, emit):
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001190 emit("seq = %s;" % value, 0)
1191 emit("n = asdl_seq_LEN(seq);", 0)
1192 emit("value = PyList_New(n);", 0)
1193 emit("if (!value) goto failed;", 0)
1194 emit("for (i = 0; i < n; i++) {", 0)
1195 self.set("value", field, "asdl_seq_GET(seq, i)", depth + 1)
1196 emit("if (!value1) goto failed;", 1)
1197 emit("PyList_SET_ITEM(value, i, value1);", 1)
1198 emit("value1 = NULL;", 1)
1199 emit("}", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001200
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001201 def set(self, field, value, depth):
1202 if field.seq:
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001203 # XXX should really check for is_simple, but that requires a symbol table
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001204 if field.type == "cmpop":
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001205 # While the sequence elements are stored as void*,
1206 # ast2obj_cmpop expects an enum
1207 self.emit("{", depth)
Benjamin Peterson77fa9372012-05-15 10:10:27 -07001208 self.emit("Py_ssize_t i, n = asdl_seq_LEN(%s);" % value, depth+1)
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001209 self.emit("value = PyList_New(n);", depth+1)
1210 self.emit("if (!value) goto failed;", depth+1)
1211 self.emit("for(i = 0; i < n; i++)", depth+1)
1212 # This cannot fail, so no need for error handling
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001213 self.emit("PyList_SET_ITEM(value, i, ast2obj_cmpop((cmpop_ty)asdl_seq_GET(%s, i)));" % value,
1214 depth+2, reflow=False)
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001215 self.emit("}", depth)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001216 else:
Martin v. Löwisce1d5d22006-02-26 20:51:25 +00001217 self.emit("value = ast2obj_list(%s, ast2obj_%s);" % (value, field.type), depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218 else:
1219 ctype = get_c_type(field.type)
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001220 self.emit("value = ast2obj_%s(%s);" % (field.type, value), depth, reflow=False)
Tim Peters536cf992005-12-25 23:18:31 +00001221
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001222
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001223class PartingShots(StaticVisitor):
1224
1225 CODE = """
1226PyObject* PyAST_mod2obj(mod_ty t)
1227{
Victor Stinnerbdf630c2013-07-17 00:17:15 +02001228 if (!init_types())
1229 return NULL;
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001230 return ast2obj_mod(t);
1231}
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001232
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001233/* mode is 0 for "exec", 1 for "eval" and 2 for "single" input */
1234mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001235{
Benjamin Petersonc2f665e2014-02-10 22:19:02 -05001236 PyObject *req_type[3];
Serhiy Storchaka43c97312019-09-10 13:02:30 +03001237 const char * const req_name[] = {"Module", "Expression", "Interactive"};
Benjamin Peterson97dd9872009-12-13 01:23:39 +00001238 int isinstance;
Benjamin Petersonc2f665e2014-02-10 22:19:02 -05001239
Steve Dowerb82e17e2019-05-23 08:45:22 -07001240 if (PySys_Audit("compile", "OO", ast, Py_None) < 0) {
1241 return NULL;
1242 }
1243
Dino Viehlandac46eb42019-09-11 10:16:34 -07001244 req_type[0] = astmodulestate_global->Module_type;
1245 req_type[1] = astmodulestate_global->Expression_type;
1246 req_type[2] = astmodulestate_global->Interactive_type;
Benjamin Petersonc2f665e2014-02-10 22:19:02 -05001247
Guido van Rossum3a32e3b2019-02-01 11:37:34 -08001248 assert(0 <= mode && mode <= 2);
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001249
Victor Stinnerbdf630c2013-07-17 00:17:15 +02001250 if (!init_types())
1251 return NULL;
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001252
Benjamin Peterson97dd9872009-12-13 01:23:39 +00001253 isinstance = PyObject_IsInstance(ast, req_type[mode]);
1254 if (isinstance == -1)
1255 return NULL;
1256 if (!isinstance) {
Neal Norwitzdb4115f2008-03-31 04:20:05 +00001257 PyErr_Format(PyExc_TypeError, "expected %s node, got %.400s",
Dino Viehlandac46eb42019-09-11 10:16:34 -07001258 req_name[mode], _PyType_Name(Py_TYPE(ast)));
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001259 return NULL;
1260 }
Dong-hee Naa05fcd32019-10-10 16:41:26 +09001261
1262 mod_ty res = NULL;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001263 if (obj2ast_mod(ast, &res, arena) != 0)
1264 return NULL;
1265 else
1266 return res;
1267}
1268
1269int PyAST_Check(PyObject* obj)
1270{
Victor Stinnerbdf630c2013-07-17 00:17:15 +02001271 if (!init_types())
1272 return -1;
Dino Viehlandac46eb42019-09-11 10:16:34 -07001273 return PyObject_IsInstance(obj, astmodulestate_global->AST_type);
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00001274}
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001275"""
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001276
1277class ChainOfVisitors:
1278 def __init__(self, *visitors):
1279 self.visitors = visitors
1280
1281 def visit(self, object):
1282 for v in self.visitors:
1283 v.visit(object)
Neal Norwitz7b5a6042005-11-13 19:14:20 +00001284 v.emit("", 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001285
Dino Viehlandac46eb42019-09-11 10:16:34 -07001286
1287def generate_module_def(f, mod):
1288 # Gather all the data needed for ModuleSpec
1289 visitor_list = set()
1290 with open(os.devnull, "w") as devnull:
1291 visitor = PyTypesDeclareVisitor(devnull)
1292 visitor.visit(mod)
1293 visitor_list.add(visitor)
1294 visitor = PyTypesVisitor(devnull)
1295 visitor.visit(mod)
1296 visitor_list.add(visitor)
1297
Batuhan Taşkaya4ab362c2020-03-16 11:12:53 +03001298 state_strings = {
Serhiy Storchakabace59d2020-03-22 20:33:34 +02001299 "ast",
Batuhan Taşkaya4ab362c2020-03-16 11:12:53 +03001300 "_fields",
1301 "__doc__",
1302 "__dict__",
1303 "__module__",
1304 "_attributes",
1305 }
1306 module_state = state_strings.copy()
Dino Viehlandac46eb42019-09-11 10:16:34 -07001307 for visitor in visitor_list:
1308 for identifier in visitor.identifiers:
1309 module_state.add(identifier)
1310 state_strings.add(identifier)
1311 for singleton in visitor.singletons:
1312 module_state.add(singleton)
1313 for tp in visitor.types:
1314 module_state.add(tp)
1315 state_strings = sorted(state_strings)
1316 module_state = sorted(module_state)
1317 f.write('typedef struct {\n')
1318 f.write(' int initialized;\n')
1319 for s in module_state:
1320 f.write(' PyObject *' + s + ';\n')
1321 f.write('} astmodulestate;\n\n')
1322 f.write("""
1323#define astmodulestate(o) ((astmodulestate *)PyModule_GetState(o))
1324
1325static int astmodule_clear(PyObject *module)
1326{
1327""")
1328 for s in module_state:
1329 f.write(" Py_CLEAR(astmodulestate(module)->" + s + ');\n')
1330 f.write("""
1331 return 0;
1332}
1333
1334static int astmodule_traverse(PyObject *module, visitproc visit, void* arg)
1335{
1336""")
1337 for s in module_state:
1338 f.write(" Py_VISIT(astmodulestate(module)->" + s + ');\n')
1339 f.write("""
1340 return 0;
1341}
1342
1343static void astmodule_free(void* module) {
1344 astmodule_clear((PyObject*)module);
1345}
1346
1347static struct PyModuleDef _astmodule = {
1348 PyModuleDef_HEAD_INIT,
1349 "_ast",
1350 NULL,
1351 sizeof(astmodulestate),
1352 NULL,
1353 NULL,
1354 astmodule_traverse,
1355 astmodule_clear,
1356 astmodule_free,
1357};
1358
1359#define astmodulestate_global ((astmodulestate *)PyModule_GetState(PyState_FindModule(&_astmodule)))
1360
1361""")
1362 f.write('static int init_identifiers(void)\n')
1363 f.write('{\n')
1364 f.write(' astmodulestate *state = astmodulestate_global;\n')
1365 for identifier in state_strings:
1366 f.write(' if ((state->' + identifier)
1367 f.write(' = PyUnicode_InternFromString("')
1368 f.write(identifier + '")) == NULL) return 0;\n')
1369 f.write(' return 1;\n')
1370 f.write('};\n\n')
1371
1372
Guido van Rossum805365e2007-05-07 22:24:25 +00001373common_msg = "/* File automatically generated by %s. */\n\n"
Thomas Wouterscf297e42007-02-23 15:07:44 +00001374
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001375def main(srcfile, dump_module=False):
Neal Norwitz897ff812005-12-11 21:18:22 +00001376 argv0 = sys.argv[0]
Armin Rigo6b1793f2005-12-14 18:05:14 +00001377 components = argv0.split(os.sep)
Steve Dowera9d0a6a2019-12-17 14:14:13 -08001378 # Always join with '/' so different OS does not keep changing the file
1379 argv0 = '/'.join(components[-2:])
Thomas Wouterscf297e42007-02-23 15:07:44 +00001380 auto_gen_msg = common_msg % argv0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001381 mod = asdl.parse(srcfile)
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001382 if dump_module:
1383 print('Parsed Module:')
1384 print(mod)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001385 if not asdl.check(mod):
1386 sys.exit(1)
Antoine Pitroub091bec2017-09-20 23:57:56 +02001387 if H_FILE:
1388 with open(H_FILE, "w") as f:
1389 f.write(auto_gen_msg)
Victor Stinner5f2df882018-11-12 00:56:19 +01001390 f.write('#ifndef Py_PYTHON_AST_H\n')
1391 f.write('#define Py_PYTHON_AST_H\n')
1392 f.write('#ifdef __cplusplus\n')
1393 f.write('extern "C" {\n')
1394 f.write('#endif\n')
1395 f.write('\n')
Zackery Spytz421a72a2019-09-12 03:27:14 -06001396 f.write('#ifndef Py_LIMITED_API\n')
Victor Stinner5f2df882018-11-12 00:56:19 +01001397 f.write('#include "asdl.h"\n')
1398 f.write('\n')
Victor Stinner3bb183d2018-11-22 18:38:38 +01001399 f.write('#undef Yield /* undefine macro conflicting with <winbase.h> */\n')
Victor Stinner5f2df882018-11-12 00:56:19 +01001400 f.write('\n')
Antoine Pitroub091bec2017-09-20 23:57:56 +02001401 c = ChainOfVisitors(TypeDefVisitor(f),
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00001402 StructVisitor(f))
1403
Antoine Pitroub091bec2017-09-20 23:57:56 +02001404 c.visit(mod)
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00001405 f.write("// Note: these macros affect function definitions, not only call sites.\n")
1406 PrototypeVisitor(f).visit(mod)
1407 f.write("\n")
Antoine Pitroub091bec2017-09-20 23:57:56 +02001408 f.write("PyObject* PyAST_mod2obj(mod_ty t);\n")
1409 f.write("mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode);\n")
1410 f.write("int PyAST_Check(PyObject* obj);\n")
Zackery Spytz421a72a2019-09-12 03:27:14 -06001411 f.write("#endif /* !Py_LIMITED_API */\n")
Victor Stinner5f2df882018-11-12 00:56:19 +01001412 f.write('\n')
1413 f.write('#ifdef __cplusplus\n')
1414 f.write('}\n')
1415 f.write('#endif\n')
1416 f.write('#endif /* !Py_PYTHON_AST_H */\n')
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001417
Antoine Pitroub091bec2017-09-20 23:57:56 +02001418 if C_FILE:
1419 with open(C_FILE, "w") as f:
1420 f.write(auto_gen_msg)
1421 f.write('#include <stddef.h>\n')
1422 f.write('\n')
1423 f.write('#include "Python.h"\n')
1424 f.write('#include "%s-ast.h"\n' % mod.name)
Victor Stinner4a21e572020-04-15 02:35:41 +02001425 f.write('#include "structmember.h" // PyMemberDef\n')
Antoine Pitroub091bec2017-09-20 23:57:56 +02001426 f.write('\n')
Dino Viehlandac46eb42019-09-11 10:16:34 -07001427
1428 generate_module_def(f, mod)
1429
Antoine Pitroub091bec2017-09-20 23:57:56 +02001430 v = ChainOfVisitors(
1431 PyTypesDeclareVisitor(f),
1432 PyTypesVisitor(f),
1433 Obj2ModPrototypeVisitor(f),
1434 FunctionVisitor(f),
1435 ObjVisitor(f),
1436 Obj2ModVisitor(f),
1437 ASTModuleVisitor(f),
1438 PartingShots(f),
1439 )
1440 v.visit(mod)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441
1442if __name__ == "__main__":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443 import getopt
1444
Antoine Pitroub091bec2017-09-20 23:57:56 +02001445 H_FILE = ''
1446 C_FILE = ''
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001447 dump_module = False
1448 opts, args = getopt.getopt(sys.argv[1:], "dh:c:")
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449 for o, v in opts:
1450 if o == '-h':
Antoine Pitroub091bec2017-09-20 23:57:56 +02001451 H_FILE = v
Emmanuel Ariased5e29c2019-03-21 01:39:17 -03001452 elif o == '-c':
Antoine Pitroub091bec2017-09-20 23:57:56 +02001453 C_FILE = v
Emmanuel Ariased5e29c2019-03-21 01:39:17 -03001454 elif o == '-d':
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001455 dump_module = True
Antoine Pitroub091bec2017-09-20 23:57:56 +02001456 if H_FILE and C_FILE:
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001457 print('Must specify exactly one output file')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001458 sys.exit(1)
Eli Bendersky5e3d3382014-05-09 17:58:22 -07001459 elif len(args) != 1:
1460 print('Must specify single input file')
1461 sys.exit(1)
1462 main(args[0], dump_module)