blob: d5c7ce6982d105d9b73cfde68486e155dede00c0 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file includes functions to transform a concrete syntax tree (CST) to
Benjamin Peterson832bfe22011-08-09 16:15:04 -05003 * an abstract syntax tree (AST). The main function is PyAST_FromNode().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004 *
5 */
6#include "Python.h"
7#include "Python-ast.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00008#include "node.h"
9#include "ast.h"
10#include "token.h"
Ɓukasz Langae7c566c2017-09-06 17:27:58 -070011#include "pythonrun.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012
13#include <assert.h>
Serhiy Storchakaddbce132017-11-15 17:39:37 +020014#include <stdbool.h>
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000015
Benjamin Peterson832bfe22011-08-09 16:15:04 -050016static int validate_stmts(asdl_seq *);
17static int validate_exprs(asdl_seq *, expr_context_ty, int);
18static int validate_nonempty_seq(asdl_seq *, const char *, const char *);
19static int validate_stmt(stmt_ty);
20static int validate_expr(expr_ty, expr_context_ty);
21
22static int
23validate_comprehension(asdl_seq *gens)
24{
25 int i;
26 if (!asdl_seq_LEN(gens)) {
27 PyErr_SetString(PyExc_ValueError, "comprehension with no generators");
28 return 0;
29 }
30 for (i = 0; i < asdl_seq_LEN(gens); i++) {
31 comprehension_ty comp = asdl_seq_GET(gens, i);
32 if (!validate_expr(comp->target, Store) ||
33 !validate_expr(comp->iter, Load) ||
34 !validate_exprs(comp->ifs, Load, 0))
35 return 0;
36 }
37 return 1;
38}
39
40static int
41validate_slice(slice_ty slice)
42{
43 switch (slice->kind) {
44 case Slice_kind:
45 return (!slice->v.Slice.lower || validate_expr(slice->v.Slice.lower, Load)) &&
46 (!slice->v.Slice.upper || validate_expr(slice->v.Slice.upper, Load)) &&
47 (!slice->v.Slice.step || validate_expr(slice->v.Slice.step, Load));
48 case ExtSlice_kind: {
49 int i;
50 if (!validate_nonempty_seq(slice->v.ExtSlice.dims, "dims", "ExtSlice"))
51 return 0;
52 for (i = 0; i < asdl_seq_LEN(slice->v.ExtSlice.dims); i++)
53 if (!validate_slice(asdl_seq_GET(slice->v.ExtSlice.dims, i)))
54 return 0;
55 return 1;
56 }
57 case Index_kind:
58 return validate_expr(slice->v.Index.value, Load);
59 default:
60 PyErr_SetString(PyExc_SystemError, "unknown slice node");
61 return 0;
62 }
63}
64
65static int
66validate_keywords(asdl_seq *keywords)
67{
68 int i;
69 for (i = 0; i < asdl_seq_LEN(keywords); i++)
70 if (!validate_expr(((keyword_ty)asdl_seq_GET(keywords, i))->value, Load))
71 return 0;
72 return 1;
73}
74
75static int
76validate_args(asdl_seq *args)
77{
78 int i;
79 for (i = 0; i < asdl_seq_LEN(args); i++) {
80 arg_ty arg = asdl_seq_GET(args, i);
81 if (arg->annotation && !validate_expr(arg->annotation, Load))
82 return 0;
83 }
84 return 1;
85}
86
87static const char *
88expr_context_name(expr_context_ty ctx)
89{
90 switch (ctx) {
91 case Load:
92 return "Load";
93 case Store:
94 return "Store";
95 case Del:
96 return "Del";
97 case AugLoad:
98 return "AugLoad";
99 case AugStore:
100 return "AugStore";
101 case Param:
102 return "Param";
103 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700104 Py_UNREACHABLE();
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500105 }
106}
107
108static int
109validate_arguments(arguments_ty args)
110{
111 if (!validate_args(args->args))
112 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700113 if (args->vararg && args->vararg->annotation
114 && !validate_expr(args->vararg->annotation, Load)) {
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500115 return 0;
116 }
117 if (!validate_args(args->kwonlyargs))
118 return 0;
Victor Stinner0c39b1b2015-03-18 15:02:06 +0100119 if (args->kwarg && args->kwarg->annotation
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700120 && !validate_expr(args->kwarg->annotation, Load)) {
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500121 return 0;
122 }
123 if (asdl_seq_LEN(args->defaults) > asdl_seq_LEN(args->args)) {
124 PyErr_SetString(PyExc_ValueError, "more positional defaults than args on arguments");
125 return 0;
126 }
127 if (asdl_seq_LEN(args->kw_defaults) != asdl_seq_LEN(args->kwonlyargs)) {
128 PyErr_SetString(PyExc_ValueError, "length of kwonlyargs is not the same as "
129 "kw_defaults on arguments");
130 return 0;
131 }
132 return validate_exprs(args->defaults, Load, 0) && validate_exprs(args->kw_defaults, Load, 1);
133}
134
135static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100136validate_constant(PyObject *value)
137{
138 if (value == Py_None || value == Py_Ellipsis)
139 return 1;
140
141 if (PyLong_CheckExact(value)
142 || PyFloat_CheckExact(value)
143 || PyComplex_CheckExact(value)
144 || PyBool_Check(value)
145 || PyUnicode_CheckExact(value)
146 || PyBytes_CheckExact(value))
147 return 1;
148
149 if (PyTuple_CheckExact(value) || PyFrozenSet_CheckExact(value)) {
150 PyObject *it;
151
152 it = PyObject_GetIter(value);
153 if (it == NULL)
154 return 0;
155
156 while (1) {
157 PyObject *item = PyIter_Next(it);
158 if (item == NULL) {
159 if (PyErr_Occurred()) {
160 Py_DECREF(it);
161 return 0;
162 }
163 break;
164 }
165
166 if (!validate_constant(item)) {
167 Py_DECREF(it);
Victor Stinner726f6902016-01-27 00:11:47 +0100168 Py_DECREF(item);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100169 return 0;
170 }
Victor Stinner726f6902016-01-27 00:11:47 +0100171 Py_DECREF(item);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100172 }
173
174 Py_DECREF(it);
175 return 1;
176 }
177
178 return 0;
179}
180
181static int
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500182validate_expr(expr_ty exp, expr_context_ty ctx)
183{
184 int check_ctx = 1;
185 expr_context_ty actual_ctx;
186
187 /* First check expression context. */
188 switch (exp->kind) {
189 case Attribute_kind:
190 actual_ctx = exp->v.Attribute.ctx;
191 break;
192 case Subscript_kind:
193 actual_ctx = exp->v.Subscript.ctx;
194 break;
195 case Starred_kind:
196 actual_ctx = exp->v.Starred.ctx;
197 break;
198 case Name_kind:
199 actual_ctx = exp->v.Name.ctx;
200 break;
201 case List_kind:
202 actual_ctx = exp->v.List.ctx;
203 break;
204 case Tuple_kind:
205 actual_ctx = exp->v.Tuple.ctx;
206 break;
207 default:
208 if (ctx != Load) {
209 PyErr_Format(PyExc_ValueError, "expression which can't be "
210 "assigned to in %s context", expr_context_name(ctx));
211 return 0;
212 }
213 check_ctx = 0;
Victor Stinner0c39b1b2015-03-18 15:02:06 +0100214 /* set actual_ctx to prevent gcc warning */
215 actual_ctx = 0;
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500216 }
217 if (check_ctx && actual_ctx != ctx) {
218 PyErr_Format(PyExc_ValueError, "expression must have %s context but has %s instead",
219 expr_context_name(ctx), expr_context_name(actual_ctx));
220 return 0;
221 }
222
223 /* Now validate expression. */
224 switch (exp->kind) {
225 case BoolOp_kind:
226 if (asdl_seq_LEN(exp->v.BoolOp.values) < 2) {
227 PyErr_SetString(PyExc_ValueError, "BoolOp with less than 2 values");
228 return 0;
229 }
230 return validate_exprs(exp->v.BoolOp.values, Load, 0);
231 case BinOp_kind:
232 return validate_expr(exp->v.BinOp.left, Load) &&
233 validate_expr(exp->v.BinOp.right, Load);
234 case UnaryOp_kind:
235 return validate_expr(exp->v.UnaryOp.operand, Load);
236 case Lambda_kind:
237 return validate_arguments(exp->v.Lambda.args) &&
238 validate_expr(exp->v.Lambda.body, Load);
239 case IfExp_kind:
240 return validate_expr(exp->v.IfExp.test, Load) &&
241 validate_expr(exp->v.IfExp.body, Load) &&
242 validate_expr(exp->v.IfExp.orelse, Load);
243 case Dict_kind:
244 if (asdl_seq_LEN(exp->v.Dict.keys) != asdl_seq_LEN(exp->v.Dict.values)) {
245 PyErr_SetString(PyExc_ValueError,
246 "Dict doesn't have the same number of keys as values");
247 return 0;
248 }
Yury Selivanovb3d53132015-09-01 16:10:49 -0400249 /* null_ok=1 for keys expressions to allow dict unpacking to work in
250 dict literals, i.e. ``{**{a:b}}`` */
251 return validate_exprs(exp->v.Dict.keys, Load, /*null_ok=*/ 1) &&
252 validate_exprs(exp->v.Dict.values, Load, /*null_ok=*/ 0);
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500253 case Set_kind:
254 return validate_exprs(exp->v.Set.elts, Load, 0);
255#define COMP(NAME) \
256 case NAME ## _kind: \
257 return validate_comprehension(exp->v.NAME.generators) && \
258 validate_expr(exp->v.NAME.elt, Load);
259 COMP(ListComp)
260 COMP(SetComp)
261 COMP(GeneratorExp)
262#undef COMP
263 case DictComp_kind:
264 return validate_comprehension(exp->v.DictComp.generators) &&
265 validate_expr(exp->v.DictComp.key, Load) &&
266 validate_expr(exp->v.DictComp.value, Load);
267 case Yield_kind:
268 return !exp->v.Yield.value || validate_expr(exp->v.Yield.value, Load);
Benjamin Peterson527c6222012-01-14 08:58:23 -0500269 case YieldFrom_kind:
Mark Dickinsonded35ae2012-11-25 14:36:26 +0000270 return validate_expr(exp->v.YieldFrom.value, Load);
Yury Selivanov75445082015-05-11 22:57:16 -0400271 case Await_kind:
272 return validate_expr(exp->v.Await.value, Load);
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500273 case Compare_kind:
274 if (!asdl_seq_LEN(exp->v.Compare.comparators)) {
275 PyErr_SetString(PyExc_ValueError, "Compare with no comparators");
276 return 0;
277 }
278 if (asdl_seq_LEN(exp->v.Compare.comparators) !=
279 asdl_seq_LEN(exp->v.Compare.ops)) {
280 PyErr_SetString(PyExc_ValueError, "Compare has a different number "
281 "of comparators and operands");
282 return 0;
283 }
284 return validate_exprs(exp->v.Compare.comparators, Load, 0) &&
285 validate_expr(exp->v.Compare.left, Load);
286 case Call_kind:
287 return validate_expr(exp->v.Call.func, Load) &&
288 validate_exprs(exp->v.Call.args, Load, 0) &&
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400289 validate_keywords(exp->v.Call.keywords);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100290 case Constant_kind:
291 if (!validate_constant(exp->v.Constant.value)) {
Victor Stinnerbe59d142016-01-27 00:39:12 +0100292 PyErr_Format(PyExc_TypeError,
293 "got an invalid type in Constant: %s",
294 Py_TYPE(exp->v.Constant.value)->tp_name);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100295 return 0;
296 }
297 return 1;
Eric V. Smith235a6f02015-09-19 14:51:32 -0400298 case JoinedStr_kind:
299 return validate_exprs(exp->v.JoinedStr.values, Load, 0);
300 case FormattedValue_kind:
301 if (validate_expr(exp->v.FormattedValue.value, Load) == 0)
302 return 0;
303 if (exp->v.FormattedValue.format_spec)
304 return validate_expr(exp->v.FormattedValue.format_spec, Load);
305 return 1;
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500306 case Attribute_kind:
307 return validate_expr(exp->v.Attribute.value, Load);
308 case Subscript_kind:
309 return validate_slice(exp->v.Subscript.slice) &&
310 validate_expr(exp->v.Subscript.value, Load);
311 case Starred_kind:
312 return validate_expr(exp->v.Starred.value, ctx);
313 case List_kind:
314 return validate_exprs(exp->v.List.elts, ctx, 0);
315 case Tuple_kind:
316 return validate_exprs(exp->v.Tuple.elts, ctx, 0);
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300317 /* This last case doesn't have any checking. */
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500318 case Name_kind:
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500319 return 1;
320 default:
321 PyErr_SetString(PyExc_SystemError, "unexpected expression");
322 return 0;
323 }
324}
325
326static int
327validate_nonempty_seq(asdl_seq *seq, const char *what, const char *owner)
328{
329 if (asdl_seq_LEN(seq))
330 return 1;
331 PyErr_Format(PyExc_ValueError, "empty %s on %s", what, owner);
332 return 0;
333}
334
335static int
336validate_assignlist(asdl_seq *targets, expr_context_ty ctx)
337{
338 return validate_nonempty_seq(targets, "targets", ctx == Del ? "Delete" : "Assign") &&
339 validate_exprs(targets, ctx, 0);
340}
341
342static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300343validate_body(asdl_seq *body, const char *owner)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500344{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300345 return validate_nonempty_seq(body, "body", owner) && validate_stmts(body);
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500346}
347
348static int
349validate_stmt(stmt_ty stmt)
350{
351 int i;
352 switch (stmt->kind) {
353 case FunctionDef_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300354 return validate_body(stmt->v.FunctionDef.body, "FunctionDef") &&
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500355 validate_arguments(stmt->v.FunctionDef.args) &&
356 validate_exprs(stmt->v.FunctionDef.decorator_list, Load, 0) &&
357 (!stmt->v.FunctionDef.returns ||
358 validate_expr(stmt->v.FunctionDef.returns, Load));
359 case ClassDef_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300360 return validate_body(stmt->v.ClassDef.body, "ClassDef") &&
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500361 validate_exprs(stmt->v.ClassDef.bases, Load, 0) &&
362 validate_keywords(stmt->v.ClassDef.keywords) &&
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400363 validate_exprs(stmt->v.ClassDef.decorator_list, Load, 0);
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500364 case Return_kind:
365 return !stmt->v.Return.value || validate_expr(stmt->v.Return.value, Load);
366 case Delete_kind:
367 return validate_assignlist(stmt->v.Delete.targets, Del);
368 case Assign_kind:
369 return validate_assignlist(stmt->v.Assign.targets, Store) &&
370 validate_expr(stmt->v.Assign.value, Load);
371 case AugAssign_kind:
372 return validate_expr(stmt->v.AugAssign.target, Store) &&
373 validate_expr(stmt->v.AugAssign.value, Load);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700374 case AnnAssign_kind:
375 if (stmt->v.AnnAssign.target->kind != Name_kind &&
376 stmt->v.AnnAssign.simple) {
377 PyErr_SetString(PyExc_TypeError,
378 "AnnAssign with simple non-Name target");
379 return 0;
380 }
381 return validate_expr(stmt->v.AnnAssign.target, Store) &&
382 (!stmt->v.AnnAssign.value ||
383 validate_expr(stmt->v.AnnAssign.value, Load)) &&
384 validate_expr(stmt->v.AnnAssign.annotation, Load);
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500385 case For_kind:
386 return validate_expr(stmt->v.For.target, Store) &&
387 validate_expr(stmt->v.For.iter, Load) &&
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300388 validate_body(stmt->v.For.body, "For") &&
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500389 validate_stmts(stmt->v.For.orelse);
Yury Selivanov75445082015-05-11 22:57:16 -0400390 case AsyncFor_kind:
391 return validate_expr(stmt->v.AsyncFor.target, Store) &&
392 validate_expr(stmt->v.AsyncFor.iter, Load) &&
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300393 validate_body(stmt->v.AsyncFor.body, "AsyncFor") &&
Yury Selivanov75445082015-05-11 22:57:16 -0400394 validate_stmts(stmt->v.AsyncFor.orelse);
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500395 case While_kind:
396 return validate_expr(stmt->v.While.test, Load) &&
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300397 validate_body(stmt->v.While.body, "While") &&
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500398 validate_stmts(stmt->v.While.orelse);
399 case If_kind:
400 return validate_expr(stmt->v.If.test, Load) &&
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300401 validate_body(stmt->v.If.body, "If") &&
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500402 validate_stmts(stmt->v.If.orelse);
403 case With_kind:
404 if (!validate_nonempty_seq(stmt->v.With.items, "items", "With"))
405 return 0;
406 for (i = 0; i < asdl_seq_LEN(stmt->v.With.items); i++) {
407 withitem_ty item = asdl_seq_GET(stmt->v.With.items, i);
408 if (!validate_expr(item->context_expr, Load) ||
409 (item->optional_vars && !validate_expr(item->optional_vars, Store)))
410 return 0;
411 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300412 return validate_body(stmt->v.With.body, "With");
Yury Selivanov75445082015-05-11 22:57:16 -0400413 case AsyncWith_kind:
414 if (!validate_nonempty_seq(stmt->v.AsyncWith.items, "items", "AsyncWith"))
415 return 0;
416 for (i = 0; i < asdl_seq_LEN(stmt->v.AsyncWith.items); i++) {
417 withitem_ty item = asdl_seq_GET(stmt->v.AsyncWith.items, i);
418 if (!validate_expr(item->context_expr, Load) ||
419 (item->optional_vars && !validate_expr(item->optional_vars, Store)))
420 return 0;
421 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300422 return validate_body(stmt->v.AsyncWith.body, "AsyncWith");
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500423 case Raise_kind:
424 if (stmt->v.Raise.exc) {
425 return validate_expr(stmt->v.Raise.exc, Load) &&
426 (!stmt->v.Raise.cause || validate_expr(stmt->v.Raise.cause, Load));
427 }
428 if (stmt->v.Raise.cause) {
429 PyErr_SetString(PyExc_ValueError, "Raise with cause but no exception");
430 return 0;
431 }
432 return 1;
433 case Try_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300434 if (!validate_body(stmt->v.Try.body, "Try"))
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500435 return 0;
436 if (!asdl_seq_LEN(stmt->v.Try.handlers) &&
437 !asdl_seq_LEN(stmt->v.Try.finalbody)) {
438 PyErr_SetString(PyExc_ValueError, "Try has neither except handlers nor finalbody");
439 return 0;
440 }
441 if (!asdl_seq_LEN(stmt->v.Try.handlers) &&
442 asdl_seq_LEN(stmt->v.Try.orelse)) {
443 PyErr_SetString(PyExc_ValueError, "Try has orelse but no except handlers");
444 return 0;
445 }
446 for (i = 0; i < asdl_seq_LEN(stmt->v.Try.handlers); i++) {
447 excepthandler_ty handler = asdl_seq_GET(stmt->v.Try.handlers, i);
448 if ((handler->v.ExceptHandler.type &&
449 !validate_expr(handler->v.ExceptHandler.type, Load)) ||
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300450 !validate_body(handler->v.ExceptHandler.body, "ExceptHandler"))
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500451 return 0;
452 }
453 return (!asdl_seq_LEN(stmt->v.Try.finalbody) ||
454 validate_stmts(stmt->v.Try.finalbody)) &&
455 (!asdl_seq_LEN(stmt->v.Try.orelse) ||
456 validate_stmts(stmt->v.Try.orelse));
457 case Assert_kind:
458 return validate_expr(stmt->v.Assert.test, Load) &&
459 (!stmt->v.Assert.msg || validate_expr(stmt->v.Assert.msg, Load));
460 case Import_kind:
461 return validate_nonempty_seq(stmt->v.Import.names, "names", "Import");
462 case ImportFrom_kind:
Serhiy Storchakafbd15232016-06-27 21:39:12 +0300463 if (stmt->v.ImportFrom.level < 0) {
464 PyErr_SetString(PyExc_ValueError, "Negative ImportFrom level");
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500465 return 0;
466 }
467 return validate_nonempty_seq(stmt->v.ImportFrom.names, "names", "ImportFrom");
468 case Global_kind:
469 return validate_nonempty_seq(stmt->v.Global.names, "names", "Global");
470 case Nonlocal_kind:
471 return validate_nonempty_seq(stmt->v.Nonlocal.names, "names", "Nonlocal");
472 case Expr_kind:
473 return validate_expr(stmt->v.Expr.value, Load);
Yury Selivanov75445082015-05-11 22:57:16 -0400474 case AsyncFunctionDef_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300475 return validate_body(stmt->v.AsyncFunctionDef.body, "AsyncFunctionDef") &&
Yury Selivanov75445082015-05-11 22:57:16 -0400476 validate_arguments(stmt->v.AsyncFunctionDef.args) &&
477 validate_exprs(stmt->v.AsyncFunctionDef.decorator_list, Load, 0) &&
478 (!stmt->v.AsyncFunctionDef.returns ||
479 validate_expr(stmt->v.AsyncFunctionDef.returns, Load));
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500480 case Pass_kind:
481 case Break_kind:
482 case Continue_kind:
483 return 1;
484 default:
485 PyErr_SetString(PyExc_SystemError, "unexpected statement");
486 return 0;
487 }
488}
489
490static int
491validate_stmts(asdl_seq *seq)
492{
493 int i;
494 for (i = 0; i < asdl_seq_LEN(seq); i++) {
495 stmt_ty stmt = asdl_seq_GET(seq, i);
496 if (stmt) {
497 if (!validate_stmt(stmt))
498 return 0;
499 }
500 else {
501 PyErr_SetString(PyExc_ValueError,
502 "None disallowed in statement list");
503 return 0;
504 }
505 }
506 return 1;
507}
508
509static int
510validate_exprs(asdl_seq *exprs, expr_context_ty ctx, int null_ok)
511{
512 int i;
513 for (i = 0; i < asdl_seq_LEN(exprs); i++) {
514 expr_ty expr = asdl_seq_GET(exprs, i);
515 if (expr) {
516 if (!validate_expr(expr, ctx))
517 return 0;
518 }
519 else if (!null_ok) {
520 PyErr_SetString(PyExc_ValueError,
521 "None disallowed in expression list");
522 return 0;
523 }
Victor Stinner0c39b1b2015-03-18 15:02:06 +0100524
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500525 }
526 return 1;
527}
528
529int
530PyAST_Validate(mod_ty mod)
531{
532 int res = 0;
533
534 switch (mod->kind) {
535 case Module_kind:
536 res = validate_stmts(mod->v.Module.body);
537 break;
538 case Interactive_kind:
539 res = validate_stmts(mod->v.Interactive.body);
540 break;
541 case Expression_kind:
542 res = validate_expr(mod->v.Expression.body, Load);
543 break;
544 case Suite_kind:
545 PyErr_SetString(PyExc_ValueError, "Suite is not valid in the CPython compiler");
546 break;
547 default:
548 PyErr_SetString(PyExc_SystemError, "impossible module node");
549 res = 0;
550 break;
551 }
552 return res;
553}
554
Benjamin Petersond3af6e32012-01-16 09:56:35 -0500555/* This is done here, so defines like "test" don't interfere with AST use above. */
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500556#include "grammar.h"
557#include "parsetok.h"
558#include "graminit.h"
559
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000560/* Data structure used internally */
561struct compiling {
Eric V. Smith163b5c62015-08-21 09:40:38 -0400562 PyArena *c_arena; /* Arena for allocating memory. */
Victor Stinner14e461d2013-08-26 22:28:21 +0200563 PyObject *c_filename; /* filename */
Benjamin Peterson55e00432012-01-16 17:22:31 -0500564 PyObject *c_normalize; /* Normalization function from unicodedata. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000565};
566
567static asdl_seq *seq_for_testlist(struct compiling *, const node *);
568static expr_ty ast_for_expr(struct compiling *, const node *);
569static stmt_ty ast_for_stmt(struct compiling *, const node *);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300570static asdl_seq *ast_for_suite(struct compiling *c, const node *n);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000571static asdl_seq *ast_for_exprlist(struct compiling *, const node *,
572 expr_context_ty);
Neil Schemenauerc5dd10a2005-10-25 07:54:54 +0000573static expr_ty ast_for_testlist(struct compiling *, const node *);
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000574static stmt_ty ast_for_classdef(struct compiling *, const node *, asdl_seq *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000575
guoci90fc8982018-09-11 17:45:45 -0400576static stmt_ty ast_for_with_stmt(struct compiling *, const node *, bool);
577static stmt_ty ast_for_for_stmt(struct compiling *, const node *, bool);
Yury Selivanov75445082015-05-11 22:57:16 -0400578
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000579/* Note different signature for ast_for_call */
Serhiy Storchakaddbce132017-11-15 17:39:37 +0200580static expr_ty ast_for_call(struct compiling *, const node *, expr_ty, bool);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000581
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000582static PyObject *parsenumber(struct compiling *, const char *);
Eric V. Smith235a6f02015-09-19 14:51:32 -0400583static expr_ty parsestrplus(struct compiling *, const node *n);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000584
Nick Coghlan650f0d02007-04-15 12:05:43 +0000585#define COMP_GENEXP 0
586#define COMP_LISTCOMP 1
587#define COMP_SETCOMP 2
588
Benjamin Peterson55e00432012-01-16 17:22:31 -0500589static int
590init_normalization(struct compiling *c)
Martin v. Löwis47383402007-08-15 07:32:56 +0000591{
Benjamin Peterson55e00432012-01-16 17:22:31 -0500592 PyObject *m = PyImport_ImportModuleNoBlock("unicodedata");
593 if (!m)
594 return 0;
595 c->c_normalize = PyObject_GetAttrString(m, "normalize");
596 Py_DECREF(m);
597 if (!c->c_normalize)
598 return 0;
Benjamin Peterson55e00432012-01-16 17:22:31 -0500599 return 1;
600}
601
602static identifier
Benjamin Petersond40528f2012-09-02 16:37:09 -0400603new_identifier(const char *n, struct compiling *c)
Benjamin Peterson55e00432012-01-16 17:22:31 -0500604{
Benjamin Petersonc7dedb02012-09-02 16:36:01 -0400605 PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
Benjamin Peterson5eda9132012-01-16 09:47:42 -0500606 if (!id)
Benjamin Peterson30760062008-11-25 04:02:28 +0000607 return NULL;
Benjamin Peterson55e00432012-01-16 17:22:31 -0500608 /* PyUnicode_DecodeUTF8 should always return a ready string. */
Benjamin Peterson5eda9132012-01-16 09:47:42 -0500609 assert(PyUnicode_IS_READY(id));
Martin v. Löwis47383402007-08-15 07:32:56 +0000610 /* Check whether there are non-ASCII characters in the
611 identifier; if so, normalize to NFKC. */
Benjamin Petersonde5827d2012-01-16 09:55:53 -0500612 if (!PyUnicode_IS_ASCII(id)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200613 PyObject *id2;
Oren Milman7dc46d82017-09-30 20:16:24 +0300614 _Py_IDENTIFIER(NFKC);
Benjamin Peterson55e00432012-01-16 17:22:31 -0500615 if (!c->c_normalize && !init_normalization(c)) {
Benjamin Peterson0fa35ea2012-01-16 09:50:48 -0500616 Py_DECREF(id);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200617 return NULL;
Benjamin Peterson0fa35ea2012-01-16 09:50:48 -0500618 }
Oren Milman7dc46d82017-09-30 20:16:24 +0300619 PyObject *form = _PyUnicode_FromId(&PyId_NFKC);
620 if (form == NULL) {
621 Py_DECREF(id);
622 return NULL;
623 }
624 PyObject *args[2] = {form, id};
625 id2 = _PyObject_FastCall(c->c_normalize, args, 2);
Benjamin Peterson0fa35ea2012-01-16 09:50:48 -0500626 Py_DECREF(id);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200627 if (!id2)
628 return NULL;
Oren Milman7dc46d82017-09-30 20:16:24 +0300629 if (!PyUnicode_Check(id2)) {
630 PyErr_Format(PyExc_TypeError,
631 "unicodedata.normalize() must return a string, not "
632 "%.200s",
633 Py_TYPE(id2)->tp_name);
634 Py_DECREF(id2);
635 return NULL;
636 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200637 id = id2;
Martin v. Löwis47383402007-08-15 07:32:56 +0000638 }
Martin v. Löwis5b222132007-06-10 09:51:05 +0000639 PyUnicode_InternInPlace(&id);
Victor Stinner43d81952013-07-17 00:57:58 +0200640 if (PyArena_AddPyObject(c->c_arena, id) < 0) {
641 Py_DECREF(id);
642 return NULL;
643 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000644 return id;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000645}
646
Benjamin Peterson55e00432012-01-16 17:22:31 -0500647#define NEW_IDENTIFIER(n) new_identifier(STR(n), c)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000648
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000649static int
Benjamin Petersonbd0df502012-09-02 15:04:51 -0400650ast_error(struct compiling *c, const node *n, const char *errmsg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000651{
Benjamin Petersonbd0df502012-09-02 15:04:51 -0400652 PyObject *value, *errstr, *loc, *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000653
Victor Stinner14e461d2013-08-26 22:28:21 +0200654 loc = PyErr_ProgramTextObject(c->c_filename, LINENO(n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000655 if (!loc) {
Thomas Wouters89f507f2006-12-13 04:49:30 +0000656 Py_INCREF(Py_None);
657 loc = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000658 }
Ammar Askar025eb982018-09-24 17:12:49 -0400659 tmp = Py_BuildValue("(OiiN)", c->c_filename, LINENO(n), n->n_col_offset + 1, loc);
Benjamin Petersonbd0df502012-09-02 15:04:51 -0400660 if (!tmp)
661 return 0;
662 errstr = PyUnicode_FromString(errmsg);
663 if (!errstr) {
664 Py_DECREF(tmp);
665 return 0;
Neal Norwitz8ad64aa2005-12-11 20:08:33 +0000666 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000667 value = PyTuple_Pack(2, errstr, tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000668 Py_DECREF(errstr);
669 Py_DECREF(tmp);
Benjamin Petersonbd0df502012-09-02 15:04:51 -0400670 if (value) {
671 PyErr_SetObject(PyExc_SyntaxError, value);
672 Py_DECREF(value);
673 }
674 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000675}
676
677/* num_stmts() returns number of contained statements.
678
679 Use this routine to determine how big a sequence is needed for
680 the statements in a parse tree. Its raison d'etre is this bit of
681 grammar:
682
683 stmt: simple_stmt | compound_stmt
684 simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
685
686 A simple_stmt can contain multiple small_stmt elements joined
687 by semicolons. If the arg is a simple_stmt, the number of
688 small_stmt elements is returned.
689*/
690
691static int
692num_stmts(const node *n)
693{
694 int i, l;
695 node *ch;
696
697 switch (TYPE(n)) {
698 case single_input:
699 if (TYPE(CHILD(n, 0)) == NEWLINE)
700 return 0;
701 else
702 return num_stmts(CHILD(n, 0));
703 case file_input:
704 l = 0;
705 for (i = 0; i < NCH(n); i++) {
706 ch = CHILD(n, i);
707 if (TYPE(ch) == stmt)
708 l += num_stmts(ch);
709 }
710 return l;
711 case stmt:
712 return num_stmts(CHILD(n, 0));
713 case compound_stmt:
714 return 1;
715 case simple_stmt:
716 return NCH(n) / 2; /* Divide by 2 to remove count of semi-colons */
717 case suite:
718 if (NCH(n) == 1)
719 return num_stmts(CHILD(n, 0));
720 else {
721 l = 0;
722 for (i = 2; i < (NCH(n) - 1); i++)
723 l += num_stmts(CHILD(n, i));
724 return l;
725 }
726 default: {
727 char buf[128];
728
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000729 sprintf(buf, "Non-statement found: %d %d",
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000730 TYPE(n), NCH(n));
731 Py_FatalError(buf);
732 }
733 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700734 Py_UNREACHABLE();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000735}
736
737/* Transform the CST rooted at node * to the appropriate AST
738*/
739
740mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +0200741PyAST_FromNodeObject(const node *n, PyCompilerFlags *flags,
742 PyObject *filename, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000743{
Jeremy Hyltona8293132006-02-28 17:58:27 +0000744 int i, j, k, num;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000745 asdl_seq *stmts = NULL;
746 stmt_ty s;
747 node *ch;
748 struct compiling c;
Benjamin Peterson55e00432012-01-16 17:22:31 -0500749 mod_ty res = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000750
Benjamin Petersonbd0df502012-09-02 15:04:51 -0400751 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200752 /* borrowed reference */
Benjamin Petersonbd0df502012-09-02 15:04:51 -0400753 c.c_filename = filename;
Benjamin Peterson9d66d4a2016-02-25 23:25:14 -0800754 c.c_normalize = NULL;
Benjamin Peterson9d66d4a2016-02-25 23:25:14 -0800755
756 if (TYPE(n) == encoding_decl)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000757 n = CHILD(n, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000758
Jeremy Hyltona8293132006-02-28 17:58:27 +0000759 k = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000760 switch (TYPE(n)) {
761 case file_input:
Antoine Pitroud01d396e2013-10-12 22:52:43 +0200762 stmts = _Py_asdl_seq_new(num_stmts(n), arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000763 if (!stmts)
Benjamin Peterson55e00432012-01-16 17:22:31 -0500764 goto out;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765 for (i = 0; i < NCH(n) - 1; i++) {
766 ch = CHILD(n, i);
767 if (TYPE(ch) == NEWLINE)
768 continue;
769 REQ(ch, stmt);
770 num = num_stmts(ch);
771 if (num == 1) {
772 s = ast_for_stmt(&c, ch);
773 if (!s)
Benjamin Peterson55e00432012-01-16 17:22:31 -0500774 goto out;
Jeremy Hyltona8293132006-02-28 17:58:27 +0000775 asdl_seq_SET(stmts, k++, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776 }
777 else {
778 ch = CHILD(ch, 0);
779 REQ(ch, simple_stmt);
780 for (j = 0; j < num; j++) {
781 s = ast_for_stmt(&c, CHILD(ch, j * 2));
782 if (!s)
Benjamin Peterson55e00432012-01-16 17:22:31 -0500783 goto out;
Jeremy Hyltona8293132006-02-28 17:58:27 +0000784 asdl_seq_SET(stmts, k++, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000785 }
786 }
787 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300788 res = Module(stmts, arena);
Benjamin Peterson55e00432012-01-16 17:22:31 -0500789 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000790 case eval_input: {
791 expr_ty testlist_ast;
792
Nick Coghlan650f0d02007-04-15 12:05:43 +0000793 /* XXX Why not comp_for here? */
Neil Schemenauerc5dd10a2005-10-25 07:54:54 +0000794 testlist_ast = ast_for_testlist(&c, CHILD(n, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000795 if (!testlist_ast)
Benjamin Peterson55e00432012-01-16 17:22:31 -0500796 goto out;
797 res = Expression(testlist_ast, arena);
798 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000799 }
800 case single_input:
801 if (TYPE(CHILD(n, 0)) == NEWLINE) {
Antoine Pitroud01d396e2013-10-12 22:52:43 +0200802 stmts = _Py_asdl_seq_new(1, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000803 if (!stmts)
Benjamin Peterson55e00432012-01-16 17:22:31 -0500804 goto out;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000805 asdl_seq_SET(stmts, 0, Pass(n->n_lineno, n->n_col_offset,
806 arena));
Guido van Rossum360e4b82007-05-14 22:51:27 +0000807 if (!asdl_seq_GET(stmts, 0))
Benjamin Peterson55e00432012-01-16 17:22:31 -0500808 goto out;
809 res = Interactive(stmts, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000810 }
811 else {
812 n = CHILD(n, 0);
813 num = num_stmts(n);
Antoine Pitroud01d396e2013-10-12 22:52:43 +0200814 stmts = _Py_asdl_seq_new(num, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000815 if (!stmts)
Benjamin Peterson55e00432012-01-16 17:22:31 -0500816 goto out;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000817 if (num == 1) {
Thomas Wouters89f507f2006-12-13 04:49:30 +0000818 s = ast_for_stmt(&c, n);
819 if (!s)
Benjamin Peterson55e00432012-01-16 17:22:31 -0500820 goto out;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000821 asdl_seq_SET(stmts, 0, s);
822 }
823 else {
824 /* Only a simple_stmt can contain multiple statements. */
825 REQ(n, simple_stmt);
826 for (i = 0; i < NCH(n); i += 2) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000827 if (TYPE(CHILD(n, i)) == NEWLINE)
828 break;
829 s = ast_for_stmt(&c, CHILD(n, i));
830 if (!s)
Benjamin Peterson55e00432012-01-16 17:22:31 -0500831 goto out;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000832 asdl_seq_SET(stmts, i / 2, s);
833 }
834 }
835
Benjamin Peterson55e00432012-01-16 17:22:31 -0500836 res = Interactive(stmts, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000837 }
Benjamin Petersonc8909dd2012-01-16 17:44:12 -0500838 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000839 default:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000840 PyErr_Format(PyExc_SystemError,
841 "invalid node %d for PyAST_FromNode", TYPE(n));
Benjamin Peterson55e00432012-01-16 17:22:31 -0500842 goto out;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000843 }
Benjamin Peterson55e00432012-01-16 17:22:31 -0500844 out:
845 if (c.c_normalize) {
846 Py_DECREF(c.c_normalize);
Benjamin Peterson55e00432012-01-16 17:22:31 -0500847 }
Benjamin Peterson55e00432012-01-16 17:22:31 -0500848 return res;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000849}
850
Victor Stinner14e461d2013-08-26 22:28:21 +0200851mod_ty
852PyAST_FromNode(const node *n, PyCompilerFlags *flags, const char *filename_str,
853 PyArena *arena)
854{
855 mod_ty mod;
856 PyObject *filename;
857 filename = PyUnicode_DecodeFSDefault(filename_str);
858 if (filename == NULL)
859 return NULL;
860 mod = PyAST_FromNodeObject(n, flags, filename, arena);
861 Py_DECREF(filename);
862 return mod;
863
864}
865
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000866/* Return the AST repr. of the operator represented as syntax (|, ^, etc.)
867*/
868
869static operator_ty
870get_operator(const node *n)
871{
872 switch (TYPE(n)) {
873 case VBAR:
874 return BitOr;
875 case CIRCUMFLEX:
876 return BitXor;
877 case AMPER:
878 return BitAnd;
879 case LEFTSHIFT:
880 return LShift;
881 case RIGHTSHIFT:
882 return RShift;
883 case PLUS:
884 return Add;
885 case MINUS:
886 return Sub;
887 case STAR:
888 return Mult;
Benjamin Petersond51374e2014-04-09 23:55:56 -0400889 case AT:
890 return MatMult;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000891 case SLASH:
892 return Div;
893 case DOUBLESLASH:
894 return FloorDiv;
895 case PERCENT:
896 return Mod;
897 default:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000898 return (operator_ty)0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000899 }
900}
901
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200902static const char * const FORBIDDEN[] = {
Guido van Rossume7ba4952007-06-06 23:52:48 +0000903 "None",
904 "True",
905 "False",
906 NULL,
907};
908
909static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400910forbidden_name(struct compiling *c, identifier name, const node *n,
911 int full_checks)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000912{
Benjamin Peterson78565b22009-06-28 19:19:51 +0000913 assert(PyUnicode_Check(name));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200914 if (_PyUnicode_EqualToASCIIString(name, "__debug__")) {
Benjamin Petersonbd0df502012-09-02 15:04:51 -0400915 ast_error(c, n, "assignment to keyword");
Benjamin Peterson70f52762009-06-28 23:32:44 +0000916 return 1;
917 }
918 if (full_checks) {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200919 const char * const *p;
Benjamin Peterson70f52762009-06-28 23:32:44 +0000920 for (p = FORBIDDEN; *p; p++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200921 if (_PyUnicode_EqualToASCIIString(name, *p)) {
Benjamin Petersonbd0df502012-09-02 15:04:51 -0400922 ast_error(c, n, "assignment to keyword");
Benjamin Peterson70f52762009-06-28 23:32:44 +0000923 return 1;
924 }
Guido van Rossume7ba4952007-06-06 23:52:48 +0000925 }
926 }
927 return 0;
928}
929
Jeremy Hyltona8293132006-02-28 17:58:27 +0000930/* Set the context ctx for expr_ty e, recursively traversing e.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000931
932 Only sets context for expr kinds that "can appear in assignment context"
933 (according to ../Parser/Python.asdl). For other expr kinds, it sets
934 an appropriate syntax error and returns false.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000935*/
936
937static int
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000938set_context(struct compiling *c, expr_ty e, expr_context_ty ctx, const node *n)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000939{
940 asdl_seq *s = NULL;
Jeremy Hyltonc960f262006-01-27 15:18:39 +0000941 /* If a particular expression type can't be used for assign / delete,
942 set expr_name to its name and an error message will be generated.
943 */
944 const char* expr_name = NULL;
945
946 /* The ast defines augmented store and load contexts, but the
947 implementation here doesn't actually use them. The code may be
948 a little more complex than necessary as a result. It also means
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000949 that expressions in an augmented assignment have a Store context.
Jeremy Hyltonc960f262006-01-27 15:18:39 +0000950 Consider restructuring so that augmented assignment uses
Guido van Rossumc2e20742006-02-27 22:32:47 +0000951 set_context(), too.
Jeremy Hyltonc960f262006-01-27 15:18:39 +0000952 */
953 assert(ctx != AugStore && ctx != AugLoad);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000954
955 switch (e->kind) {
956 case Attribute_kind:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000957 e->v.Attribute.ctx = ctx;
Benjamin Petersonbd0df502012-09-02 15:04:51 -0400958 if (ctx == Store && forbidden_name(c, e->v.Attribute.attr, n, 1))
Benjamin Peterson70f52762009-06-28 23:32:44 +0000959 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000960 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000961 case Subscript_kind:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000962 e->v.Subscript.ctx = ctx;
963 break;
Guido van Rossum0368b722007-05-11 16:50:42 +0000964 case Starred_kind:
965 e->v.Starred.ctx = ctx;
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000966 if (!set_context(c, e->v.Starred.value, ctx, n))
Guido van Rossum0368b722007-05-11 16:50:42 +0000967 return 0;
968 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000969 case Name_kind:
Guido van Rossume7ba4952007-06-06 23:52:48 +0000970 if (ctx == Store) {
Benjamin Peterson442f2092012-12-06 17:41:04 -0500971 if (forbidden_name(c, e->v.Name.id, n, 0))
Guido van Rossume7ba4952007-06-06 23:52:48 +0000972 return 0; /* forbidden_name() calls ast_error() */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000973 }
974 e->v.Name.ctx = ctx;
975 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000976 case List_kind:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000977 e->v.List.ctx = ctx;
978 s = e->v.List.elts;
979 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000980 case Tuple_kind:
Berker Peksag094c9c92016-05-18 08:44:29 +0300981 e->v.Tuple.ctx = ctx;
982 s = e->v.Tuple.elts;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000983 break;
Jeremy Hyltonc960f262006-01-27 15:18:39 +0000984 case Lambda_kind:
985 expr_name = "lambda";
986 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000987 case Call_kind:
Jeremy Hyltonc960f262006-01-27 15:18:39 +0000988 expr_name = "function call";
Thomas Wouters89f507f2006-12-13 04:49:30 +0000989 break;
Jeremy Hyltonc960f262006-01-27 15:18:39 +0000990 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000991 case BinOp_kind:
Jeremy Hyltonc960f262006-01-27 15:18:39 +0000992 case UnaryOp_kind:
993 expr_name = "operator";
994 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000995 case GeneratorExp_kind:
Jeremy Hyltonc960f262006-01-27 15:18:39 +0000996 expr_name = "generator expression";
997 break;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000998 case Yield_kind:
Benjamin Peterson527c6222012-01-14 08:58:23 -0500999 case YieldFrom_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001000 expr_name = "yield expression";
1001 break;
Yury Selivanov75445082015-05-11 22:57:16 -04001002 case Await_kind:
1003 expr_name = "await expression";
1004 break;
Jeremy Hyltonc960f262006-01-27 15:18:39 +00001005 case ListComp_kind:
1006 expr_name = "list comprehension";
1007 break;
Guido van Rossum0368b722007-05-11 16:50:42 +00001008 case SetComp_kind:
1009 expr_name = "set comprehension";
1010 break;
Guido van Rossum992d4a32007-07-11 13:09:30 +00001011 case DictComp_kind:
1012 expr_name = "dict comprehension";
1013 break;
Jeremy Hyltonc960f262006-01-27 15:18:39 +00001014 case Dict_kind:
Neal Norwitzc1505362006-12-28 06:47:50 +00001015 case Set_kind:
Eric V. Smith235a6f02015-09-19 14:51:32 -04001016 case JoinedStr_kind:
1017 case FormattedValue_kind:
Jeremy Hyltonc960f262006-01-27 15:18:39 +00001018 expr_name = "literal";
1019 break;
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001020 case Constant_kind: {
1021 PyObject *value = e->v.Constant.value;
1022 if (value == Py_None || value == Py_False || value == Py_True) {
1023 expr_name = "keyword";
1024 }
1025 else if (value == Py_Ellipsis) {
1026 expr_name = "Ellipsis";
1027 }
1028 else {
1029 expr_name = "literal";
1030 }
Benjamin Peterson442f2092012-12-06 17:41:04 -05001031 break;
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001032 }
Jeremy Hyltonc960f262006-01-27 15:18:39 +00001033 case Compare_kind:
1034 expr_name = "comparison";
1035 break;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001036 case IfExp_kind:
1037 expr_name = "conditional expression";
1038 break;
Jeremy Hyltonc960f262006-01-27 15:18:39 +00001039 default:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 PyErr_Format(PyExc_SystemError,
1041 "unexpected expression in assignment %d (line %d)",
Jeremy Hyltonc960f262006-01-27 15:18:39 +00001042 e->kind, e->lineno);
1043 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001044 }
Jeremy Hyltonc960f262006-01-27 15:18:39 +00001045 /* Check for error string set by switch */
1046 if (expr_name) {
1047 char buf[300];
1048 PyOS_snprintf(buf, sizeof(buf),
1049 "can't %s %s",
1050 ctx == Store ? "assign to" : "delete",
1051 expr_name);
Benjamin Petersonbd0df502012-09-02 15:04:51 -04001052 return ast_error(c, n, buf);
Jeremy Hyltonc960f262006-01-27 15:18:39 +00001053 }
1054
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001055 /* If the LHS is a list or tuple, we need to set the assignment
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 context for all the contained elements.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001057 */
1058 if (s) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001059 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001060
Thomas Wouters89f507f2006-12-13 04:49:30 +00001061 for (i = 0; i < asdl_seq_LEN(s); i++) {
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001062 if (!set_context(c, (expr_ty)asdl_seq_GET(s, i), ctx, n))
Thomas Wouters89f507f2006-12-13 04:49:30 +00001063 return 0;
1064 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001065 }
1066 return 1;
1067}
1068
1069static operator_ty
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001070ast_for_augassign(struct compiling *c, const node *n)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001071{
1072 REQ(n, augassign);
1073 n = CHILD(n, 0);
1074 switch (STR(n)[0]) {
1075 case '+':
1076 return Add;
1077 case '-':
1078 return Sub;
1079 case '/':
1080 if (STR(n)[1] == '/')
1081 return FloorDiv;
1082 else
1083 return Div;
1084 case '%':
1085 return Mod;
1086 case '<':
1087 return LShift;
1088 case '>':
1089 return RShift;
1090 case '&':
1091 return BitAnd;
1092 case '^':
1093 return BitXor;
1094 case '|':
1095 return BitOr;
1096 case '*':
1097 if (STR(n)[1] == '*')
1098 return Pow;
1099 else
1100 return Mult;
Benjamin Petersond51374e2014-04-09 23:55:56 -04001101 case '@':
1102 return MatMult;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001103 default:
Neal Norwitz79792652005-11-14 04:25:03 +00001104 PyErr_Format(PyExc_SystemError, "invalid augassign: %s", STR(n));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001105 return (operator_ty)0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001106 }
1107}
1108
1109static cmpop_ty
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001110ast_for_comp_op(struct compiling *c, const node *n)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001111{
Guido van Rossumb053cd82006-08-24 03:53:23 +00001112 /* comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001113 |'is' 'not'
1114 */
1115 REQ(n, comp_op);
1116 if (NCH(n) == 1) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001117 n = CHILD(n, 0);
1118 switch (TYPE(n)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001119 case LESS:
1120 return Lt;
1121 case GREATER:
1122 return Gt;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001123 case EQEQUAL: /* == */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124 return Eq;
1125 case LESSEQUAL:
1126 return LtE;
1127 case GREATEREQUAL:
1128 return GtE;
1129 case NOTEQUAL:
1130 return NotEq;
1131 case NAME:
1132 if (strcmp(STR(n), "in") == 0)
1133 return In;
1134 if (strcmp(STR(n), "is") == 0)
1135 return Is;
Stefan Krahf432a322017-08-21 13:09:59 +02001136 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001137 default:
Neal Norwitz79792652005-11-14 04:25:03 +00001138 PyErr_Format(PyExc_SystemError, "invalid comp_op: %s",
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001139 STR(n));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001140 return (cmpop_ty)0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001141 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001142 }
1143 else if (NCH(n) == 2) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001144 /* handle "not in" and "is not" */
1145 switch (TYPE(CHILD(n, 0))) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146 case NAME:
1147 if (strcmp(STR(CHILD(n, 1)), "in") == 0)
1148 return NotIn;
1149 if (strcmp(STR(CHILD(n, 0)), "is") == 0)
1150 return IsNot;
Stefan Krahf432a322017-08-21 13:09:59 +02001151 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152 default:
Neal Norwitz79792652005-11-14 04:25:03 +00001153 PyErr_Format(PyExc_SystemError, "invalid comp_op: %s %s",
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154 STR(CHILD(n, 0)), STR(CHILD(n, 1)));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001155 return (cmpop_ty)0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001156 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001157 }
Neal Norwitz79792652005-11-14 04:25:03 +00001158 PyErr_Format(PyExc_SystemError, "invalid comp_op: has %d children",
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001159 NCH(n));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001160 return (cmpop_ty)0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161}
1162
1163static asdl_seq *
1164seq_for_testlist(struct compiling *c, const node *n)
1165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 /* testlist: test (',' test)* [',']
Benjamin Peterson4905e802009-09-27 02:43:28 +00001167 testlist_star_expr: test|star_expr (',' test|star_expr)* [',']
1168 */
Armin Rigo31441302005-10-21 12:57:31 +00001169 asdl_seq *seq;
1170 expr_ty expression;
1171 int i;
Benjamin Peterson4905e802009-09-27 02:43:28 +00001172 assert(TYPE(n) == testlist || TYPE(n) == testlist_star_expr || TYPE(n) == testlist_comp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001173
Antoine Pitroud01d396e2013-10-12 22:52:43 +02001174 seq = _Py_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001175 if (!seq)
1176 return NULL;
1177
1178 for (i = 0; i < NCH(n); i += 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 const node *ch = CHILD(n, i);
Benjamin Peterson4905e802009-09-27 02:43:28 +00001180 assert(TYPE(ch) == test || TYPE(ch) == test_nocond || TYPE(ch) == star_expr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001181
Benjamin Peterson4905e802009-09-27 02:43:28 +00001182 expression = ast_for_expr(c, ch);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001183 if (!expression)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001184 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001185
1186 assert(i / 2 < seq->size);
1187 asdl_seq_SET(seq, i / 2, expression);
1188 }
1189 return seq;
1190}
1191
Neal Norwitzc1505362006-12-28 06:47:50 +00001192static arg_ty
Benjamin Petersonbc4665e2012-03-12 11:00:41 -07001193ast_for_arg(struct compiling *c, const node *n)
Neal Norwitzc1505362006-12-28 06:47:50 +00001194{
1195 identifier name;
1196 expr_ty annotation = NULL;
1197 node *ch;
Benjamin Peterson7a66fc22015-02-02 10:51:20 -05001198 arg_ty ret;
Neal Norwitzc1505362006-12-28 06:47:50 +00001199
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001200 assert(TYPE(n) == tfpdef || TYPE(n) == vfpdef);
Neal Norwitzc1505362006-12-28 06:47:50 +00001201 ch = CHILD(n, 0);
Neal Norwitzc1505362006-12-28 06:47:50 +00001202 name = NEW_IDENTIFIER(ch);
1203 if (!name)
1204 return NULL;
Benjamin Petersonbd0df502012-09-02 15:04:51 -04001205 if (forbidden_name(c, name, ch, 0))
Benjamin Peterson70f52762009-06-28 23:32:44 +00001206 return NULL;
Neal Norwitzc1505362006-12-28 06:47:50 +00001207
1208 if (NCH(n) == 3 && TYPE(CHILD(n, 1)) == COLON) {
1209 annotation = ast_for_expr(c, CHILD(n, 2));
1210 if (!annotation)
1211 return NULL;
1212 }
1213
Victor Stinnerc106c682015-11-06 17:01:48 +01001214 ret = arg(name, annotation, LINENO(n), n->n_col_offset, c->c_arena);
Benjamin Peterson7a66fc22015-02-02 10:51:20 -05001215 if (!ret)
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001216 return NULL;
Benjamin Peterson7a66fc22015-02-02 10:51:20 -05001217 return ret;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218}
1219
Guido van Rossum4f72a782006-10-27 23:31:49 +00001220/* returns -1 if failed to handle keyword only arguments
1221 returns new position to keep processing if successful
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001222 (',' tfpdef ['=' test])*
Guido van Rossum4f72a782006-10-27 23:31:49 +00001223 ^^^
1224 start pointing here
1225 */
1226static int
1227handle_keywordonly_args(struct compiling *c, const node *n, int start,
1228 asdl_seq *kwonlyargs, asdl_seq *kwdefaults)
1229{
Benjamin Petersond951e7b2008-11-25 22:19:53 +00001230 PyObject *argname;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001231 node *ch;
Neal Norwitzc1505362006-12-28 06:47:50 +00001232 expr_ty expression, annotation;
1233 arg_ty arg;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001234 int i = start;
1235 int j = 0; /* index for kwdefaults and kwonlyargs */
Amaury Forgeot d'Arc40d3a672007-12-09 21:49:48 +00001236
1237 if (kwonlyargs == NULL) {
Benjamin Petersonbd0df502012-09-02 15:04:51 -04001238 ast_error(c, CHILD(n, start), "named arguments must follow bare *");
Amaury Forgeot d'Arc40d3a672007-12-09 21:49:48 +00001239 return -1;
1240 }
1241 assert(kwdefaults != NULL);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001242 while (i < NCH(n)) {
1243 ch = CHILD(n, i);
1244 switch (TYPE(ch)) {
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001245 case vfpdef:
1246 case tfpdef:
Guido van Rossum4f72a782006-10-27 23:31:49 +00001247 if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001248 expression = ast_for_expr(c, CHILD(n, i + 2));
Amaury Forgeot d'Arc92dc80a2010-08-19 17:43:15 +00001249 if (!expression)
Amaury Forgeot d'Arc12844e62010-08-19 21:32:38 +00001250 goto error;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001251 asdl_seq_SET(kwdefaults, j, expression);
1252 i += 2; /* '=' and test */
1253 }
1254 else { /* setting NULL if no default value exists */
1255 asdl_seq_SET(kwdefaults, j, NULL);
1256 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001257 if (NCH(ch) == 3) {
1258 /* ch is NAME ':' test */
1259 annotation = ast_for_expr(c, CHILD(ch, 2));
Amaury Forgeot d'Arc92dc80a2010-08-19 17:43:15 +00001260 if (!annotation)
Neal Norwitzc1505362006-12-28 06:47:50 +00001261 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001262 }
1263 else {
1264 annotation = NULL;
1265 }
1266 ch = CHILD(ch, 0);
Benjamin Petersond951e7b2008-11-25 22:19:53 +00001267 argname = NEW_IDENTIFIER(ch);
1268 if (!argname)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001269 goto error;
Benjamin Petersonbd0df502012-09-02 15:04:51 -04001270 if (forbidden_name(c, argname, ch, 0))
Benjamin Peterson70f52762009-06-28 23:32:44 +00001271 goto error;
Victor Stinnerc106c682015-11-06 17:01:48 +01001272 arg = arg(argname, annotation, LINENO(ch), ch->n_col_offset,
1273 c->c_arena);
Benjamin Petersond951e7b2008-11-25 22:19:53 +00001274 if (!arg)
1275 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001276 asdl_seq_SET(kwonlyargs, j++, arg);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001277 i += 2; /* the name and the comma */
1278 break;
1279 case DOUBLESTAR:
1280 return i;
1281 default:
Benjamin Petersonbd0df502012-09-02 15:04:51 -04001282 ast_error(c, ch, "unexpected node");
Guido van Rossum4f72a782006-10-27 23:31:49 +00001283 goto error;
1284 }
1285 }
1286 return i;
1287 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 return -1;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001289}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001290
Jeremy Hyltona8293132006-02-28 17:58:27 +00001291/* Create AST for argument list. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001292
1293static arguments_ty
1294ast_for_arguments(struct compiling *c, const node *n)
1295{
Neal Norwitzc1505362006-12-28 06:47:50 +00001296 /* This function handles both typedargslist (function definition)
1297 and varargslist (lambda definition).
1298
1299 parameters: '(' [typedargslist] ')'
Robert Collinsdf395992015-08-12 08:00:06 +12001300 typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [',' [
1301 '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]]
1302 | '**' tfpdef [',']]]
1303 | '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]]
1304 | '**' tfpdef [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001305 tfpdef: NAME [':' test]
Robert Collinsdf395992015-08-12 08:00:06 +12001306 varargslist: (vfpdef ['=' test] (',' vfpdef ['=' test])* [',' [
1307 '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]]
1308 | '**' vfpdef [',']]]
1309 | '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]]
1310 | '**' vfpdef [',']
1311 )
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001312 vfpdef: NAME
Robert Collinsdf395992015-08-12 08:00:06 +12001313
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001314 */
Guido van Rossum4f72a782006-10-27 23:31:49 +00001315 int i, j, k, nposargs = 0, nkwonlyargs = 0;
1316 int nposdefaults = 0, found_default = 0;
1317 asdl_seq *posargs, *posdefaults, *kwonlyargs, *kwdefaults;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001318 arg_ty vararg = NULL, kwarg = NULL;
Neal Norwitzc1505362006-12-28 06:47:50 +00001319 arg_ty arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001320 node *ch;
1321
1322 if (TYPE(n) == parameters) {
Guido van Rossum4f72a782006-10-27 23:31:49 +00001323 if (NCH(n) == 2) /* () as argument list */
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001324 return arguments(NULL, NULL, NULL, NULL, NULL, NULL, c->c_arena);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001325 n = CHILD(n, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001326 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001327 assert(TYPE(n) == typedargslist || TYPE(n) == varargslist);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001328
Jeremy Hyltone921e022008-07-17 16:37:17 +00001329 /* First count the number of positional args & defaults. The
1330 variable i is the loop index for this for loop and the next.
1331 The next loop picks up where the first leaves off.
1332 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001333 for (i = 0; i < NCH(n); i++) {
Guido van Rossum4f72a782006-10-27 23:31:49 +00001334 ch = CHILD(n, i);
1335 if (TYPE(ch) == STAR) {
Jeremy Hyltone921e022008-07-17 16:37:17 +00001336 /* skip star */
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001337 i++;
Jeremy Hyltone921e022008-07-17 16:37:17 +00001338 if (i < NCH(n) && /* skip argument following star */
1339 (TYPE(CHILD(n, i)) == tfpdef ||
1340 TYPE(CHILD(n, i)) == vfpdef)) {
1341 i++;
1342 }
1343 break;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001344 }
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001345 if (TYPE(ch) == DOUBLESTAR) break;
Neal Norwitzc1505362006-12-28 06:47:50 +00001346 if (TYPE(ch) == vfpdef || TYPE(ch) == tfpdef) nposargs++;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001347 if (TYPE(ch) == EQUAL) nposdefaults++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001348 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 /* count the number of keyword only args &
Guido van Rossum4f72a782006-10-27 23:31:49 +00001350 defaults for keyword only args */
1351 for ( ; i < NCH(n); ++i) {
1352 ch = CHILD(n, i);
1353 if (TYPE(ch) == DOUBLESTAR) break;
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001354 if (TYPE(ch) == tfpdef || TYPE(ch) == vfpdef) nkwonlyargs++;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001355 }
Antoine Pitroud01d396e2013-10-12 22:52:43 +02001356 posargs = (nposargs ? _Py_asdl_seq_new(nposargs, c->c_arena) : NULL);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001357 if (!posargs && nposargs)
Amaury Forgeot d'Arc92dc80a2010-08-19 17:43:15 +00001358 return NULL;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001359 kwonlyargs = (nkwonlyargs ?
Antoine Pitroud01d396e2013-10-12 22:52:43 +02001360 _Py_asdl_seq_new(nkwonlyargs, c->c_arena) : NULL);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001361 if (!kwonlyargs && nkwonlyargs)
Amaury Forgeot d'Arc92dc80a2010-08-19 17:43:15 +00001362 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 posdefaults = (nposdefaults ?
Antoine Pitroud01d396e2013-10-12 22:52:43 +02001364 _Py_asdl_seq_new(nposdefaults, c->c_arena) : NULL);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001365 if (!posdefaults && nposdefaults)
Amaury Forgeot d'Arc92dc80a2010-08-19 17:43:15 +00001366 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 /* The length of kwonlyargs and kwdefaults are same
Guido van Rossum4f72a782006-10-27 23:31:49 +00001368 since we set NULL as default for keyword only argument w/o default
1369 - we have sequence data structure, but no dictionary */
Neal Norwitzc1505362006-12-28 06:47:50 +00001370 kwdefaults = (nkwonlyargs ?
Antoine Pitroud01d396e2013-10-12 22:52:43 +02001371 _Py_asdl_seq_new(nkwonlyargs, c->c_arena) : NULL);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001372 if (!kwdefaults && nkwonlyargs)
Amaury Forgeot d'Arc92dc80a2010-08-19 17:43:15 +00001373 return NULL;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001374
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001375 /* tfpdef: NAME [':' test]
1376 vfpdef: NAME
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001377 */
1378 i = 0;
Jeremy Hyltona8293132006-02-28 17:58:27 +00001379 j = 0; /* index for defaults */
1380 k = 0; /* index for args */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001381 while (i < NCH(n)) {
Guido van Rossum4f72a782006-10-27 23:31:49 +00001382 ch = CHILD(n, i);
1383 switch (TYPE(ch)) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001384 case tfpdef:
1385 case vfpdef:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001386 /* XXX Need to worry about checking if TYPE(CHILD(n, i+1)) is
1387 anything other than EQUAL or a comma? */
1388 /* XXX Should NCH(n) check be made a separate check? */
1389 if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001390 expr_ty expression = ast_for_expr(c, CHILD(n, i + 2));
1391 if (!expression)
Amaury Forgeot d'Arc92dc80a2010-08-19 17:43:15 +00001392 return NULL;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001393 assert(posdefaults != NULL);
1394 asdl_seq_SET(posdefaults, j++, expression);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001395 i += 2;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001396 found_default = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001397 }
Guido van Rossum4f72a782006-10-27 23:31:49 +00001398 else if (found_default) {
Benjamin Petersonbd0df502012-09-02 15:04:51 -04001399 ast_error(c, n,
Guido van Rossum4f72a782006-10-27 23:31:49 +00001400 "non-default argument follows default argument");
Amaury Forgeot d'Arc92dc80a2010-08-19 17:43:15 +00001401 return NULL;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001402 }
Benjamin Petersonbc4665e2012-03-12 11:00:41 -07001403 arg = ast_for_arg(c, ch);
Neal Norwitzc1505362006-12-28 06:47:50 +00001404 if (!arg)
Amaury Forgeot d'Arc92dc80a2010-08-19 17:43:15 +00001405 return NULL;
Neal Norwitzc1505362006-12-28 06:47:50 +00001406 asdl_seq_SET(posargs, k++, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001407 i += 2; /* the name and the comma */
1408 break;
1409 case STAR:
Robert Collinsdf395992015-08-12 08:00:06 +12001410 if (i+1 >= NCH(n) ||
1411 (i+2 == NCH(n) && TYPE(CHILD(n, i+1)) == COMMA)) {
Benjamin Petersonbd0df502012-09-02 15:04:51 -04001412 ast_error(c, CHILD(n, i),
Amaury Forgeot d'Arc40d3a672007-12-09 21:49:48 +00001413 "named arguments must follow bare *");
Amaury Forgeot d'Arc92dc80a2010-08-19 17:43:15 +00001414 return NULL;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001415 }
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001416 ch = CHILD(n, i+1); /* tfpdef or COMMA */
Neal Norwitzc1505362006-12-28 06:47:50 +00001417 if (TYPE(ch) == COMMA) {
1418 int res = 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001419 i += 2; /* now follows keyword only arguments */
1420 res = handle_keywordonly_args(c, n, i,
1421 kwonlyargs, kwdefaults);
Amaury Forgeot d'Arc92dc80a2010-08-19 17:43:15 +00001422 if (res == -1) return NULL;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001423 i = res; /* res has new position to process */
1424 }
1425 else {
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001426 vararg = ast_for_arg(c, ch);
Benjamin Peterson30760062008-11-25 04:02:28 +00001427 if (!vararg)
1428 return NULL;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001429
Guido van Rossum4f72a782006-10-27 23:31:49 +00001430 i += 3;
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001431 if (i < NCH(n) && (TYPE(CHILD(n, i)) == tfpdef
1432 || TYPE(CHILD(n, i)) == vfpdef)) {
Guido van Rossum4f72a782006-10-27 23:31:49 +00001433 int res = 0;
1434 res = handle_keywordonly_args(c, n, i,
1435 kwonlyargs, kwdefaults);
Amaury Forgeot d'Arc92dc80a2010-08-19 17:43:15 +00001436 if (res == -1) return NULL;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001437 i = res; /* res has new position to process */
1438 }
1439 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440 break;
1441 case DOUBLESTAR:
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001442 ch = CHILD(n, i+1); /* tfpdef */
1443 assert(TYPE(ch) == tfpdef || TYPE(ch) == vfpdef);
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001444 kwarg = ast_for_arg(c, ch);
Amaury Forgeot d'Arc12844e62010-08-19 21:32:38 +00001445 if (!kwarg)
1446 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447 i += 3;
1448 break;
1449 default:
Neal Norwitz79792652005-11-14 04:25:03 +00001450 PyErr_Format(PyExc_SystemError,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001451 "unexpected node in varargslist: %d @ %d",
1452 TYPE(ch), i);
Amaury Forgeot d'Arc92dc80a2010-08-19 17:43:15 +00001453 return NULL;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001454 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001455 }
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001456 return arguments(posargs, vararg, kwonlyargs, kwdefaults, kwarg, posdefaults, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001457}
1458
1459static expr_ty
1460ast_for_dotted_name(struct compiling *c, const node *n)
1461{
Neal Norwitz84456bd2005-12-18 03:16:20 +00001462 expr_ty e;
1463 identifier id;
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001464 int lineno, col_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465 int i;
1466
1467 REQ(n, dotted_name);
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001468
1469 lineno = LINENO(n);
1470 col_offset = n->n_col_offset;
1471
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001472 id = NEW_IDENTIFIER(CHILD(n, 0));
1473 if (!id)
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001474 return NULL;
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001475 e = Name(id, Load, lineno, col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001476 if (!e)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001477 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001478
1479 for (i = 2; i < NCH(n); i+=2) {
1480 id = NEW_IDENTIFIER(CHILD(n, i));
Thomas Wouters89f507f2006-12-13 04:49:30 +00001481 if (!id)
1482 return NULL;
1483 e = Attribute(e, id, Load, lineno, col_offset, c->c_arena);
1484 if (!e)
1485 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001486 }
1487
1488 return e;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001489}
1490
1491static expr_ty
1492ast_for_decorator(struct compiling *c, const node *n)
1493{
1494 /* decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE */
1495 expr_ty d = NULL;
Neal Norwitz84456bd2005-12-18 03:16:20 +00001496 expr_ty name_expr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498 REQ(n, decorator);
Jeremy Hyltonc960f262006-01-27 15:18:39 +00001499 REQ(CHILD(n, 0), AT);
1500 REQ(RCHILD(n, -1), NEWLINE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001502 name_expr = ast_for_dotted_name(c, CHILD(n, 1));
1503 if (!name_expr)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001504 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001506 if (NCH(n) == 3) { /* No arguments */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001507 d = name_expr;
1508 name_expr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001509 }
1510 else if (NCH(n) == 5) { /* Call with no arguments */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001511 d = Call(name_expr, NULL, NULL, LINENO(n),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001512 n->n_col_offset, c->c_arena);
Thomas Wouters89f507f2006-12-13 04:49:30 +00001513 if (!d)
1514 return NULL;
1515 name_expr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001516 }
1517 else {
Serhiy Storchakaddbce132017-11-15 17:39:37 +02001518 d = ast_for_call(c, CHILD(n, 3), name_expr, true);
Thomas Wouters89f507f2006-12-13 04:49:30 +00001519 if (!d)
1520 return NULL;
1521 name_expr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001522 }
1523
1524 return d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001525}
1526
1527static asdl_seq*
1528ast_for_decorators(struct compiling *c, const node *n)
1529{
Neal Norwitz84456bd2005-12-18 03:16:20 +00001530 asdl_seq* decorator_seq;
Neal Norwitze76adcd2005-11-15 05:04:31 +00001531 expr_ty d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001532 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001534 REQ(n, decorators);
Antoine Pitroud01d396e2013-10-12 22:52:43 +02001535 decorator_seq = _Py_asdl_seq_new(NCH(n), c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001536 if (!decorator_seq)
1537 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001539 for (i = 0; i < NCH(n); i++) {
Jeremy Hyltona8293132006-02-28 17:58:27 +00001540 d = ast_for_decorator(c, CHILD(n, i));
Amaury Forgeot d'Arc92dc80a2010-08-19 17:43:15 +00001541 if (!d)
1542 return NULL;
1543 asdl_seq_SET(decorator_seq, i, d);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001544 }
1545 return decorator_seq;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001546}
1547
1548static stmt_ty
guoci90fc8982018-09-11 17:45:45 -04001549ast_for_funcdef_impl(struct compiling *c, const node *n0,
1550 asdl_seq *decorator_seq, bool is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001551{
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001552 /* funcdef: 'def' NAME parameters ['->' test] ':' suite */
guoci90fc8982018-09-11 17:45:45 -04001553 const node * const n = is_async ? CHILD(n0, 1) : n0;
Neal Norwitz84456bd2005-12-18 03:16:20 +00001554 identifier name;
1555 arguments_ty args;
1556 asdl_seq *body;
Neal Norwitzc1505362006-12-28 06:47:50 +00001557 expr_ty returns = NULL;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001558 int name_i = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001559
1560 REQ(n, funcdef);
1561
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001562 name = NEW_IDENTIFIER(CHILD(n, name_i));
1563 if (!name)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001564 return NULL;
Benjamin Petersonbd0df502012-09-02 15:04:51 -04001565 if (forbidden_name(c, name, CHILD(n, name_i), 0))
Benjamin Peterson70f52762009-06-28 23:32:44 +00001566 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001567 args = ast_for_arguments(c, CHILD(n, name_i + 1));
1568 if (!args)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001569 return NULL;
Neal Norwitzc1505362006-12-28 06:47:50 +00001570 if (TYPE(CHILD(n, name_i+2)) == RARROW) {
1571 returns = ast_for_expr(c, CHILD(n, name_i + 3));
1572 if (!returns)
Amaury Forgeot d'Arc92dc80a2010-08-19 17:43:15 +00001573 return NULL;
Neal Norwitzc1505362006-12-28 06:47:50 +00001574 name_i += 2;
1575 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001576 body = ast_for_suite(c, CHILD(n, name_i + 3));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001577 if (!body)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001578 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001579
Yury Selivanov75445082015-05-11 22:57:16 -04001580 if (is_async)
1581 return AsyncFunctionDef(name, args, body, decorator_seq, returns,
Benjamin Petersond13e59c2018-09-11 15:29:57 -07001582 LINENO(n0), n0->n_col_offset, c->c_arena);
Yury Selivanov75445082015-05-11 22:57:16 -04001583 else
1584 return FunctionDef(name, args, body, decorator_seq, returns,
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001585 LINENO(n), n->n_col_offset, c->c_arena);
Yury Selivanov75445082015-05-11 22:57:16 -04001586}
1587
1588static stmt_ty
1589ast_for_async_funcdef(struct compiling *c, const node *n, asdl_seq *decorator_seq)
1590{
Jelle Zijlstraac317702017-10-05 20:24:46 -07001591 /* async_funcdef: 'async' funcdef */
Yury Selivanov75445082015-05-11 22:57:16 -04001592 REQ(n, async_funcdef);
Jelle Zijlstraac317702017-10-05 20:24:46 -07001593 REQ(CHILD(n, 0), NAME);
1594 assert(strcmp(STR(CHILD(n, 0)), "async") == 0);
Yury Selivanov75445082015-05-11 22:57:16 -04001595 REQ(CHILD(n, 1), funcdef);
1596
guoci90fc8982018-09-11 17:45:45 -04001597 return ast_for_funcdef_impl(c, n, decorator_seq,
1598 true /* is_async */);
Yury Selivanov75445082015-05-11 22:57:16 -04001599}
1600
1601static stmt_ty
1602ast_for_funcdef(struct compiling *c, const node *n, asdl_seq *decorator_seq)
1603{
1604 /* funcdef: 'def' NAME parameters ['->' test] ':' suite */
1605 return ast_for_funcdef_impl(c, n, decorator_seq,
guoci90fc8982018-09-11 17:45:45 -04001606 false /* is_async */);
Yury Selivanov75445082015-05-11 22:57:16 -04001607}
1608
1609
1610static stmt_ty
1611ast_for_async_stmt(struct compiling *c, const node *n)
1612{
Jelle Zijlstraac317702017-10-05 20:24:46 -07001613 /* async_stmt: 'async' (funcdef | with_stmt | for_stmt) */
Yury Selivanov75445082015-05-11 22:57:16 -04001614 REQ(n, async_stmt);
Jelle Zijlstraac317702017-10-05 20:24:46 -07001615 REQ(CHILD(n, 0), NAME);
1616 assert(strcmp(STR(CHILD(n, 0)), "async") == 0);
Yury Selivanov75445082015-05-11 22:57:16 -04001617
1618 switch (TYPE(CHILD(n, 1))) {
1619 case funcdef:
guoci90fc8982018-09-11 17:45:45 -04001620 return ast_for_funcdef_impl(c, n, NULL,
1621 true /* is_async */);
Yury Selivanov75445082015-05-11 22:57:16 -04001622 case with_stmt:
guoci90fc8982018-09-11 17:45:45 -04001623 return ast_for_with_stmt(c, n,
1624 true /* is_async */);
Yury Selivanov75445082015-05-11 22:57:16 -04001625
1626 case for_stmt:
guoci90fc8982018-09-11 17:45:45 -04001627 return ast_for_for_stmt(c, n,
1628 true /* is_async */);
Yury Selivanov75445082015-05-11 22:57:16 -04001629
1630 default:
1631 PyErr_Format(PyExc_SystemError,
1632 "invalid async stament: %s",
1633 STR(CHILD(n, 1)));
1634 return NULL;
1635 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001636}
1637
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001638static stmt_ty
1639ast_for_decorated(struct compiling *c, const node *n)
1640{
Yury Selivanov75445082015-05-11 22:57:16 -04001641 /* decorated: decorators (classdef | funcdef | async_funcdef) */
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001642 stmt_ty thing = NULL;
1643 asdl_seq *decorator_seq = NULL;
1644
1645 REQ(n, decorated);
1646
1647 decorator_seq = ast_for_decorators(c, CHILD(n, 0));
1648 if (!decorator_seq)
1649 return NULL;
1650
1651 assert(TYPE(CHILD(n, 1)) == funcdef ||
Yury Selivanov75445082015-05-11 22:57:16 -04001652 TYPE(CHILD(n, 1)) == async_funcdef ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 TYPE(CHILD(n, 1)) == classdef);
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001654
1655 if (TYPE(CHILD(n, 1)) == funcdef) {
1656 thing = ast_for_funcdef(c, CHILD(n, 1), decorator_seq);
1657 } else if (TYPE(CHILD(n, 1)) == classdef) {
1658 thing = ast_for_classdef(c, CHILD(n, 1), decorator_seq);
Yury Selivanov75445082015-05-11 22:57:16 -04001659 } else if (TYPE(CHILD(n, 1)) == async_funcdef) {
1660 thing = ast_for_async_funcdef(c, CHILD(n, 1), decorator_seq);
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001661 }
1662 return thing;
1663}
1664
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001665static expr_ty
1666ast_for_lambdef(struct compiling *c, const node *n)
1667{
Nick Coghlan650f0d02007-04-15 12:05:43 +00001668 /* lambdef: 'lambda' [varargslist] ':' test
1669 lambdef_nocond: 'lambda' [varargslist] ':' test_nocond */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001670 arguments_ty args;
1671 expr_ty expression;
1672
1673 if (NCH(n) == 3) {
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001674 args = arguments(NULL, NULL, NULL, NULL, NULL, NULL, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001675 if (!args)
1676 return NULL;
1677 expression = ast_for_expr(c, CHILD(n, 2));
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001678 if (!expression)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001679 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001680 }
1681 else {
1682 args = ast_for_arguments(c, CHILD(n, 1));
1683 if (!args)
1684 return NULL;
1685 expression = ast_for_expr(c, CHILD(n, 3));
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001686 if (!expression)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001687 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001688 }
1689
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001690 return Lambda(args, expression, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001691}
1692
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001693static expr_ty
1694ast_for_ifexpr(struct compiling *c, const node *n)
1695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 /* test: or_test 'if' or_test 'else' test */
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001697 expr_ty expression, body, orelse;
1698
Thomas Woutersaa8b6c52006-02-27 16:46:22 +00001699 assert(NCH(n) == 5);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001700 body = ast_for_expr(c, CHILD(n, 0));
1701 if (!body)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001702 return NULL;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001703 expression = ast_for_expr(c, CHILD(n, 2));
1704 if (!expression)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001705 return NULL;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001706 orelse = ast_for_expr(c, CHILD(n, 4));
1707 if (!orelse)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001708 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001709 return IfExp(expression, body, orelse, LINENO(n), n->n_col_offset,
1710 c->c_arena);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001711}
1712
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001713/*
Nick Coghlan650f0d02007-04-15 12:05:43 +00001714 Count the number of 'for' loops in a comprehension.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001715
Nick Coghlan650f0d02007-04-15 12:05:43 +00001716 Helper for ast_for_comprehension().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001717*/
1718
1719static int
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001720count_comp_fors(struct compiling *c, const node *n)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001721{
Guido van Rossumd8faa362007-04-27 19:54:29 +00001722 int n_fors = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001723
Guido van Rossumd8faa362007-04-27 19:54:29 +00001724 count_comp_for:
1725 n_fors++;
Guido van Rossum992d4a32007-07-11 13:09:30 +00001726 REQ(n, comp_for);
Jelle Zijlstraac317702017-10-05 20:24:46 -07001727 if (NCH(n) == 2) {
1728 REQ(CHILD(n, 0), NAME);
1729 assert(strcmp(STR(CHILD(n, 0)), "async") == 0);
1730 n = CHILD(n, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001731 }
Jelle Zijlstraac317702017-10-05 20:24:46 -07001732 else if (NCH(n) == 1) {
1733 n = CHILD(n, 0);
1734 }
1735 else {
1736 goto error;
1737 }
1738 if (NCH(n) == (5)) {
1739 n = CHILD(n, 4);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001740 }
1741 else {
Guido van Rossumd8faa362007-04-27 19:54:29 +00001742 return n_fors;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001743 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001744 count_comp_iter:
Guido van Rossum992d4a32007-07-11 13:09:30 +00001745 REQ(n, comp_iter);
1746 n = CHILD(n, 0);
1747 if (TYPE(n) == comp_for)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001748 goto count_comp_for;
Guido van Rossum992d4a32007-07-11 13:09:30 +00001749 else if (TYPE(n) == comp_if) {
1750 if (NCH(n) == 3) {
1751 n = CHILD(n, 2);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001752 goto count_comp_iter;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001753 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001754 else
1755 return n_fors;
1756 }
Neal Norwitz84456bd2005-12-18 03:16:20 +00001757
Jelle Zijlstraac317702017-10-05 20:24:46 -07001758 error:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001759 /* Should never be reached */
1760 PyErr_SetString(PyExc_SystemError,
1761 "logic error in count_comp_fors");
1762 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001763}
1764
Nick Coghlan650f0d02007-04-15 12:05:43 +00001765/* Count the number of 'if' statements in a comprehension.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001766
Nick Coghlan650f0d02007-04-15 12:05:43 +00001767 Helper for ast_for_comprehension().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001768*/
1769
1770static int
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001771count_comp_ifs(struct compiling *c, const node *n)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001772{
Guido van Rossumd8faa362007-04-27 19:54:29 +00001773 int n_ifs = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001774
Guido van Rossumd8faa362007-04-27 19:54:29 +00001775 while (1) {
1776 REQ(n, comp_iter);
1777 if (TYPE(CHILD(n, 0)) == comp_for)
1778 return n_ifs;
1779 n = CHILD(n, 0);
1780 REQ(n, comp_if);
1781 n_ifs++;
1782 if (NCH(n) == 2)
1783 return n_ifs;
1784 n = CHILD(n, 2);
1785 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001786}
1787
Guido van Rossum992d4a32007-07-11 13:09:30 +00001788static asdl_seq *
1789ast_for_comprehension(struct compiling *c, const node *n)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001790{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001791 int i, n_fors;
Guido van Rossum992d4a32007-07-11 13:09:30 +00001792 asdl_seq *comps;
1793
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001794 n_fors = count_comp_fors(c, n);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001795 if (n_fors == -1)
1796 return NULL;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001797
Antoine Pitroud01d396e2013-10-12 22:52:43 +02001798 comps = _Py_asdl_seq_new(n_fors, c->c_arena);
Nick Coghlan650f0d02007-04-15 12:05:43 +00001799 if (!comps)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001800 return NULL;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001801
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001802 for (i = 0; i < n_fors; i++) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00001803 comprehension_ty comp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001804 asdl_seq *t;
Benjamin Peterson2e4b0e12009-09-11 22:36:20 +00001805 expr_ty expression, first;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001806 node *for_ch;
Jelle Zijlstraac317702017-10-05 20:24:46 -07001807 node *sync_n;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001808 int is_async = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809
Guido van Rossum992d4a32007-07-11 13:09:30 +00001810 REQ(n, comp_for);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811
Jelle Zijlstraac317702017-10-05 20:24:46 -07001812 if (NCH(n) == 2) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001813 is_async = 1;
Jelle Zijlstraac317702017-10-05 20:24:46 -07001814 REQ(CHILD(n, 0), NAME);
1815 assert(strcmp(STR(CHILD(n, 0)), "async") == 0);
1816 sync_n = CHILD(n, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001817 }
Jelle Zijlstraac317702017-10-05 20:24:46 -07001818 else {
1819 sync_n = CHILD(n, 0);
1820 }
1821 REQ(sync_n, sync_comp_for);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001822
Jelle Zijlstraac317702017-10-05 20:24:46 -07001823 for_ch = CHILD(sync_n, 1);
Thomas Wouters89f507f2006-12-13 04:49:30 +00001824 t = ast_for_exprlist(c, for_ch, Store);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001825 if (!t)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001826 return NULL;
Jelle Zijlstraac317702017-10-05 20:24:46 -07001827 expression = ast_for_expr(c, CHILD(sync_n, 3));
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001828 if (!expression)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001829 return NULL;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001830
Thomas Wouters89f507f2006-12-13 04:49:30 +00001831 /* Check the # of children rather than the length of t, since
1832 (x for x, in ...) has 1 element in t, but still requires a Tuple. */
Benjamin Peterson2e4b0e12009-09-11 22:36:20 +00001833 first = (expr_ty)asdl_seq_GET(t, 0);
Thomas Wouters89f507f2006-12-13 04:49:30 +00001834 if (NCH(for_ch) == 1)
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001835 comp = comprehension(first, expression, NULL,
1836 is_async, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001837 else
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001838 comp = comprehension(Tuple(t, Store, first->lineno,
1839 first->col_offset, c->c_arena),
1840 expression, NULL, is_async, c->c_arena);
Nick Coghlan650f0d02007-04-15 12:05:43 +00001841 if (!comp)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001842 return NULL;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001843
Jelle Zijlstraac317702017-10-05 20:24:46 -07001844 if (NCH(sync_n) == 5) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001845 int j, n_ifs;
1846 asdl_seq *ifs;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847
Jelle Zijlstraac317702017-10-05 20:24:46 -07001848 n = CHILD(sync_n, 4);
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001849 n_ifs = count_comp_ifs(c, n);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001850 if (n_ifs == -1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001851 return NULL;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001852
Antoine Pitroud01d396e2013-10-12 22:52:43 +02001853 ifs = _Py_asdl_seq_new(n_ifs, c->c_arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001854 if (!ifs)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001855 return NULL;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001856
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001857 for (j = 0; j < n_ifs; j++) {
Guido van Rossum992d4a32007-07-11 13:09:30 +00001858 REQ(n, comp_iter);
1859 n = CHILD(n, 0);
1860 REQ(n, comp_if);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861
Guido van Rossum992d4a32007-07-11 13:09:30 +00001862 expression = ast_for_expr(c, CHILD(n, 1));
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001863 if (!expression)
Neil Schemenauerc5dd10a2005-10-25 07:54:54 +00001864 return NULL;
Jeremy Hyltona8293132006-02-28 17:58:27 +00001865 asdl_seq_SET(ifs, j, expression);
Guido van Rossum992d4a32007-07-11 13:09:30 +00001866 if (NCH(n) == 3)
1867 n = CHILD(n, 2);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001868 }
Guido van Rossum992d4a32007-07-11 13:09:30 +00001869 /* on exit, must guarantee that n is a comp_for */
1870 if (TYPE(n) == comp_iter)
1871 n = CHILD(n, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00001872 comp->ifs = ifs;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001873 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00001874 asdl_seq_SET(comps, i, comp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001875 }
Guido van Rossum992d4a32007-07-11 13:09:30 +00001876 return comps;
1877}
1878
1879static expr_ty
1880ast_for_itercomp(struct compiling *c, const node *n, int type)
1881{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001882 /* testlist_comp: (test|star_expr)
1883 * ( comp_for | (',' (test|star_expr))* [','] ) */
Guido van Rossum992d4a32007-07-11 13:09:30 +00001884 expr_ty elt;
1885 asdl_seq *comps;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001886 node *ch;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887
Guido van Rossum992d4a32007-07-11 13:09:30 +00001888 assert(NCH(n) > 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001890 ch = CHILD(n, 0);
1891 elt = ast_for_expr(c, ch);
Guido van Rossum992d4a32007-07-11 13:09:30 +00001892 if (!elt)
1893 return NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001894 if (elt->kind == Starred_kind) {
1895 ast_error(c, ch, "iterable unpacking cannot be used in comprehension");
1896 return NULL;
1897 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898
Guido van Rossum992d4a32007-07-11 13:09:30 +00001899 comps = ast_for_comprehension(c, CHILD(n, 1));
1900 if (!comps)
1901 return NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00001902
1903 if (type == COMP_GENEXP)
1904 return GeneratorExp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena);
1905 else if (type == COMP_LISTCOMP)
1906 return ListComp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena);
1907 else if (type == COMP_SETCOMP)
1908 return SetComp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena);
1909 else
1910 /* Should never happen */
1911 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001912}
1913
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001914/* Fills in the key, value pair corresponding to the dict element. In case
1915 * of an unpacking, key is NULL. *i is advanced by the number of ast
1916 * elements. Iff successful, nonzero is returned.
1917 */
1918static int
1919ast_for_dictelement(struct compiling *c, const node *n, int *i,
1920 expr_ty *key, expr_ty *value)
1921{
1922 expr_ty expression;
1923 if (TYPE(CHILD(n, *i)) == DOUBLESTAR) {
1924 assert(NCH(n) - *i >= 2);
1925
1926 expression = ast_for_expr(c, CHILD(n, *i + 1));
1927 if (!expression)
1928 return 0;
1929 *key = NULL;
1930 *value = expression;
1931
1932 *i += 2;
1933 }
1934 else {
1935 assert(NCH(n) - *i >= 3);
1936
1937 expression = ast_for_expr(c, CHILD(n, *i));
1938 if (!expression)
1939 return 0;
1940 *key = expression;
1941
1942 REQ(CHILD(n, *i + 1), COLON);
1943
1944 expression = ast_for_expr(c, CHILD(n, *i + 2));
1945 if (!expression)
1946 return 0;
1947 *value = expression;
1948
1949 *i += 3;
1950 }
1951 return 1;
1952}
1953
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001954static expr_ty
Guido van Rossum992d4a32007-07-11 13:09:30 +00001955ast_for_dictcomp(struct compiling *c, const node *n)
1956{
1957 expr_ty key, value;
1958 asdl_seq *comps;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001959 int i = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001961 if (!ast_for_dictelement(c, n, &i, &key, &value))
Guido van Rossum992d4a32007-07-11 13:09:30 +00001962 return NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001963 assert(key);
1964 assert(NCH(n) - i >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001966 comps = ast_for_comprehension(c, CHILD(n, i));
Guido van Rossum992d4a32007-07-11 13:09:30 +00001967 if (!comps)
1968 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969
Guido van Rossum992d4a32007-07-11 13:09:30 +00001970 return DictComp(key, value, comps, LINENO(n), n->n_col_offset, c->c_arena);
1971}
1972
1973static expr_ty
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001974ast_for_dictdisplay(struct compiling *c, const node *n)
1975{
1976 int i;
1977 int j;
1978 int size;
1979 asdl_seq *keys, *values;
1980
1981 size = (NCH(n) + 1) / 3; /* +1 in case no trailing comma */
1982 keys = _Py_asdl_seq_new(size, c->c_arena);
1983 if (!keys)
1984 return NULL;
1985
1986 values = _Py_asdl_seq_new(size, c->c_arena);
1987 if (!values)
1988 return NULL;
1989
1990 j = 0;
1991 for (i = 0; i < NCH(n); i++) {
1992 expr_ty key, value;
1993
1994 if (!ast_for_dictelement(c, n, &i, &key, &value))
1995 return NULL;
1996 asdl_seq_SET(keys, j, key);
1997 asdl_seq_SET(values, j, value);
1998
1999 j++;
2000 }
2001 keys->size = j;
2002 values->size = j;
2003 return Dict(keys, values, LINENO(n), n->n_col_offset, c->c_arena);
2004}
2005
2006static expr_ty
Nick Coghlan650f0d02007-04-15 12:05:43 +00002007ast_for_genexp(struct compiling *c, const node *n)
2008{
2009 assert(TYPE(n) == (testlist_comp) || TYPE(n) == (argument));
Guido van Rossum992d4a32007-07-11 13:09:30 +00002010 return ast_for_itercomp(c, n, COMP_GENEXP);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002011}
2012
2013static expr_ty
2014ast_for_listcomp(struct compiling *c, const node *n)
2015{
2016 assert(TYPE(n) == (testlist_comp));
Guido van Rossum992d4a32007-07-11 13:09:30 +00002017 return ast_for_itercomp(c, n, COMP_LISTCOMP);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002018}
2019
2020static expr_ty
2021ast_for_setcomp(struct compiling *c, const node *n)
2022{
2023 assert(TYPE(n) == (dictorsetmaker));
Guido van Rossum992d4a32007-07-11 13:09:30 +00002024 return ast_for_itercomp(c, n, COMP_SETCOMP);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002025}
2026
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002027static expr_ty
2028ast_for_setdisplay(struct compiling *c, const node *n)
2029{
2030 int i;
2031 int size;
2032 asdl_seq *elts;
2033
2034 assert(TYPE(n) == (dictorsetmaker));
2035 size = (NCH(n) + 1) / 2; /* +1 in case no trailing comma */
2036 elts = _Py_asdl_seq_new(size, c->c_arena);
2037 if (!elts)
2038 return NULL;
2039 for (i = 0; i < NCH(n); i += 2) {
2040 expr_ty expression;
2041 expression = ast_for_expr(c, CHILD(n, i));
2042 if (!expression)
2043 return NULL;
2044 asdl_seq_SET(elts, i / 2, expression);
2045 }
2046 return Set(elts, LINENO(n), n->n_col_offset, c->c_arena);
2047}
Nick Coghlan650f0d02007-04-15 12:05:43 +00002048
2049static expr_ty
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002050ast_for_atom(struct compiling *c, const node *n)
2051{
Nick Coghlan650f0d02007-04-15 12:05:43 +00002052 /* atom: '(' [yield_expr|testlist_comp] ')' | '[' [testlist_comp] ']'
2053 | '{' [dictmaker|testlist_comp] '}' | NAME | NUMBER | STRING+
Guido van Rossume7ba4952007-06-06 23:52:48 +00002054 | '...' | 'None' | 'True' | 'False'
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002055 */
2056 node *ch = CHILD(n, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002058 switch (TYPE(ch)) {
Benjamin Peterson30760062008-11-25 04:02:28 +00002059 case NAME: {
Benjamin Peterson442f2092012-12-06 17:41:04 -05002060 PyObject *name;
2061 const char *s = STR(ch);
2062 size_t len = strlen(s);
2063 if (len >= 4 && len <= 5) {
2064 if (!strcmp(s, "None"))
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002065 return Constant(Py_None, LINENO(n), n->n_col_offset, c->c_arena);
Benjamin Peterson442f2092012-12-06 17:41:04 -05002066 if (!strcmp(s, "True"))
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002067 return Constant(Py_True, LINENO(n), n->n_col_offset, c->c_arena);
Benjamin Peterson442f2092012-12-06 17:41:04 -05002068 if (!strcmp(s, "False"))
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002069 return Constant(Py_False, LINENO(n), n->n_col_offset, c->c_arena);
Benjamin Peterson442f2092012-12-06 17:41:04 -05002070 }
2071 name = new_identifier(s, c);
Benjamin Peterson30760062008-11-25 04:02:28 +00002072 if (!name)
2073 return NULL;
Benjamin Peterson442f2092012-12-06 17:41:04 -05002074 /* All names start in Load context, but may later be changed. */
Benjamin Peterson30760062008-11-25 04:02:28 +00002075 return Name(name, Load, LINENO(n), n->n_col_offset, c->c_arena);
2076 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002077 case STRING: {
Eric V. Smith235a6f02015-09-19 14:51:32 -04002078 expr_ty str = parsestrplus(c, n);
Guido van Rossumb5a755e2007-07-18 18:15:48 +00002079 if (!str) {
Serhiy Storchaka5e61f142013-02-10 17:36:00 +02002080 const char *errtype = NULL;
2081 if (PyErr_ExceptionMatches(PyExc_UnicodeError))
2082 errtype = "unicode error";
2083 else if (PyErr_ExceptionMatches(PyExc_ValueError))
2084 errtype = "value error";
2085 if (errtype) {
2086 char buf[128];
Serhiy Storchaka144f77a2016-11-20 08:47:21 +02002087 const char *s = NULL;
Guido van Rossumb5a755e2007-07-18 18:15:48 +00002088 PyObject *type, *value, *tback, *errstr;
2089 PyErr_Fetch(&type, &value, &tback);
Benjamin Peterson6f7fad12008-11-21 22:58:57 +00002090 errstr = PyObject_Str(value);
Serhiy Storchaka144f77a2016-11-20 08:47:21 +02002091 if (errstr)
2092 s = PyUnicode_AsUTF8(errstr);
2093 if (s) {
Serhiy Storchaka5e61f142013-02-10 17:36:00 +02002094 PyOS_snprintf(buf, sizeof(buf), "(%s) %s", errtype, s);
Guido van Rossumb5a755e2007-07-18 18:15:48 +00002095 } else {
Victor Stinner00723e02015-09-03 12:57:11 +02002096 PyErr_Clear();
Serhiy Storchaka5e61f142013-02-10 17:36:00 +02002097 PyOS_snprintf(buf, sizeof(buf), "(%s) unknown error", errtype);
Guido van Rossumb5a755e2007-07-18 18:15:48 +00002098 }
Serhiy Storchaka144f77a2016-11-20 08:47:21 +02002099 Py_XDECREF(errstr);
Serhiy Storchaka801d9552013-02-10 17:42:01 +02002100 ast_error(c, n, buf);
Guido van Rossumb5a755e2007-07-18 18:15:48 +00002101 Py_DECREF(type);
Victor Stinner0fae8f92013-07-17 21:51:42 +02002102 Py_XDECREF(value);
Guido van Rossumb5a755e2007-07-18 18:15:48 +00002103 Py_XDECREF(tback);
2104 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00002105 return NULL;
Guido van Rossumb5a755e2007-07-18 18:15:48 +00002106 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04002107 return str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002108 }
2109 case NUMBER: {
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002110 PyObject *pynum = parsenumber(c, STR(ch));
Thomas Wouters89f507f2006-12-13 04:49:30 +00002111 if (!pynum)
2112 return NULL;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00002113
Victor Stinner43d81952013-07-17 00:57:58 +02002114 if (PyArena_AddPyObject(c->c_arena, pynum) < 0) {
2115 Py_DECREF(pynum);
2116 return NULL;
2117 }
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002118 return Constant(pynum, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002119 }
Georg Brandldde00282007-03-18 19:01:53 +00002120 case ELLIPSIS: /* Ellipsis */
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002121 return Constant(Py_Ellipsis, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002122 case LPAR: /* some parenthesized expressions */
Thomas Wouters89f507f2006-12-13 04:49:30 +00002123 ch = CHILD(n, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124
Thomas Wouters89f507f2006-12-13 04:49:30 +00002125 if (TYPE(ch) == RPAR)
2126 return Tuple(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127
Thomas Wouters89f507f2006-12-13 04:49:30 +00002128 if (TYPE(ch) == yield_expr)
2129 return ast_for_expr(c, ch);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 /* testlist_comp: test ( comp_for | (',' test)* [','] ) */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002132 if ((NCH(ch) > 1) && (TYPE(CHILD(ch, 1)) == comp_for))
Thomas Wouters89f507f2006-12-13 04:49:30 +00002133 return ast_for_genexp(c, ch);
Benjamin Peterson78565b22009-06-28 19:19:51 +00002134
Nick Coghlan650f0d02007-04-15 12:05:43 +00002135 return ast_for_testlist(c, ch);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002136 case LSQB: /* list (or list comprehension) */
Thomas Wouters89f507f2006-12-13 04:49:30 +00002137 ch = CHILD(n, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138
Thomas Wouters89f507f2006-12-13 04:49:30 +00002139 if (TYPE(ch) == RSQB)
2140 return List(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141
Nick Coghlan650f0d02007-04-15 12:05:43 +00002142 REQ(ch, testlist_comp);
Thomas Wouters89f507f2006-12-13 04:49:30 +00002143 if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) {
2144 asdl_seq *elts = seq_for_testlist(c, ch);
2145 if (!elts)
2146 return NULL;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00002147
Thomas Wouters89f507f2006-12-13 04:49:30 +00002148 return List(elts, Load, LINENO(n), n->n_col_offset, c->c_arena);
2149 }
2150 else
2151 return ast_for_listcomp(c, ch);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002152 case LBRACE: {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002153 /* dictorsetmaker: ( ((test ':' test | '**' test)
2154 * (comp_for | (',' (test ':' test | '**' test))* [','])) |
2155 * ((test | '*' test)
2156 * (comp_for | (',' (test | '*' test))* [','])) ) */
Benjamin Peterson58b53952015-09-25 22:44:43 -07002157 expr_ty res;
Neal Norwitzc1505362006-12-28 06:47:50 +00002158 ch = CHILD(n, 1);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002159 if (TYPE(ch) == RBRACE) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002160 /* It's an empty dict. */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002161 return Dict(NULL, NULL, LINENO(n), n->n_col_offset, c->c_arena);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002162 }
2163 else {
2164 int is_dict = (TYPE(CHILD(ch, 0)) == DOUBLESTAR);
2165 if (NCH(ch) == 1 ||
2166 (NCH(ch) > 1 &&
2167 TYPE(CHILD(ch, 1)) == COMMA)) {
2168 /* It's a set display. */
Benjamin Peterson58b53952015-09-25 22:44:43 -07002169 res = ast_for_setdisplay(c, ch);
Guido van Rossum86e58e22006-08-28 15:27:34 +00002170 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002171 else if (NCH(ch) > 1 &&
2172 TYPE(CHILD(ch, 1)) == comp_for) {
2173 /* It's a set comprehension. */
Benjamin Peterson58b53952015-09-25 22:44:43 -07002174 res = ast_for_setcomp(c, ch);
Guido van Rossum86e58e22006-08-28 15:27:34 +00002175 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002176 else if (NCH(ch) > 3 - is_dict &&
2177 TYPE(CHILD(ch, 3 - is_dict)) == comp_for) {
2178 /* It's a dictionary comprehension. */
2179 if (is_dict) {
2180 ast_error(c, n, "dict unpacking cannot be used in "
2181 "dict comprehension");
2182 return NULL;
2183 }
Benjamin Peterson58b53952015-09-25 22:44:43 -07002184 res = ast_for_dictcomp(c, ch);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002185 }
2186 else {
2187 /* It's a dictionary display. */
Benjamin Peterson58b53952015-09-25 22:44:43 -07002188 res = ast_for_dictdisplay(c, ch);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002189 }
Benjamin Peterson58b53952015-09-25 22:44:43 -07002190 if (res) {
2191 res->lineno = LINENO(n);
2192 res->col_offset = n->n_col_offset;
2193 }
2194 return res;
Guido van Rossum86e58e22006-08-28 15:27:34 +00002195 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002196 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002197 default:
Thomas Wouters89f507f2006-12-13 04:49:30 +00002198 PyErr_Format(PyExc_SystemError, "unhandled atom %d", TYPE(ch));
2199 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002200 }
2201}
2202
2203static slice_ty
2204ast_for_slice(struct compiling *c, const node *n)
2205{
2206 node *ch;
2207 expr_ty lower = NULL, upper = NULL, step = NULL;
2208
2209 REQ(n, subscript);
2210
2211 /*
Georg Brandl52318d62006-09-06 07:06:08 +00002212 subscript: test | [test] ':' [test] [sliceop]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002213 sliceop: ':' [test]
2214 */
2215 ch = CHILD(n, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002216 if (NCH(n) == 1 && TYPE(ch) == test) {
2217 /* 'step' variable hold no significance in terms of being used over
2218 other vars */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 step = ast_for_expr(c, ch);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002220 if (!step)
2221 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222
Thomas Wouters89f507f2006-12-13 04:49:30 +00002223 return Index(step, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002224 }
2225
2226 if (TYPE(ch) == test) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00002227 lower = ast_for_expr(c, ch);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002228 if (!lower)
2229 return NULL;
2230 }
2231
2232 /* If there's an upper bound it's in the second or third position. */
2233 if (TYPE(ch) == COLON) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00002234 if (NCH(n) > 1) {
2235 node *n2 = CHILD(n, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002236
Thomas Wouters89f507f2006-12-13 04:49:30 +00002237 if (TYPE(n2) == test) {
2238 upper = ast_for_expr(c, n2);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002239 if (!upper)
2240 return NULL;
2241 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00002242 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002243 } else if (NCH(n) > 2) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00002244 node *n2 = CHILD(n, 2);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002245
Thomas Wouters89f507f2006-12-13 04:49:30 +00002246 if (TYPE(n2) == test) {
2247 upper = ast_for_expr(c, n2);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002248 if (!upper)
2249 return NULL;
2250 }
2251 }
2252
2253 ch = CHILD(n, NCH(n) - 1);
2254 if (TYPE(ch) == sliceop) {
Benjamin Peterson78565b22009-06-28 19:19:51 +00002255 if (NCH(ch) != 1) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002256 ch = CHILD(ch, 1);
2257 if (TYPE(ch) == test) {
2258 step = ast_for_expr(c, ch);
2259 if (!step)
2260 return NULL;
2261 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002262 }
2263 }
2264
Neal Norwitzadb69fc2005-12-17 20:54:49 +00002265 return Slice(lower, upper, step, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002266}
2267
2268static expr_ty
2269ast_for_binop(struct compiling *c, const node *n)
2270{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002271 /* Must account for a sequence of expressions.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 How should A op B op C by represented?
Guido van Rossumd8faa362007-04-27 19:54:29 +00002273 BinOp(BinOp(A, op, B), op, C).
2274 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002275
Guido van Rossumd8faa362007-04-27 19:54:29 +00002276 int i, nops;
2277 expr_ty expr1, expr2, result;
2278 operator_ty newoperator;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002279
Guido van Rossumd8faa362007-04-27 19:54:29 +00002280 expr1 = ast_for_expr(c, CHILD(n, 0));
2281 if (!expr1)
2282 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002283
Guido van Rossumd8faa362007-04-27 19:54:29 +00002284 expr2 = ast_for_expr(c, CHILD(n, 2));
2285 if (!expr2)
2286 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002287
Guido van Rossumd8faa362007-04-27 19:54:29 +00002288 newoperator = get_operator(CHILD(n, 1));
2289 if (!newoperator)
2290 return NULL;
2291
2292 result = BinOp(expr1, newoperator, expr2, LINENO(n), n->n_col_offset,
2293 c->c_arena);
2294 if (!result)
2295 return NULL;
2296
2297 nops = (NCH(n) - 1) / 2;
2298 for (i = 1; i < nops; i++) {
2299 expr_ty tmp_result, tmp;
2300 const node* next_oper = CHILD(n, i * 2 + 1);
2301
2302 newoperator = get_operator(next_oper);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002303 if (!newoperator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002304 return NULL;
2305
Guido van Rossumd8faa362007-04-27 19:54:29 +00002306 tmp = ast_for_expr(c, CHILD(n, i * 2 + 2));
2307 if (!tmp)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002308 return NULL;
2309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 tmp_result = BinOp(result, newoperator, tmp,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002311 LINENO(next_oper), next_oper->n_col_offset,
2312 c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 if (!tmp_result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002314 return NULL;
2315 result = tmp_result;
2316 }
2317 return result;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002318}
2319
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002320static expr_ty
2321ast_for_trailer(struct compiling *c, const node *n, expr_ty left_expr)
2322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 /* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
Jeremy Hyltonc7d37262006-02-27 17:29:29 +00002324 subscriptlist: subscript (',' subscript)* [',']
2325 subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop]
2326 */
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002327 REQ(n, trailer);
2328 if (TYPE(CHILD(n, 0)) == LPAR) {
2329 if (NCH(n) == 2)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002330 return Call(left_expr, NULL, NULL, LINENO(n),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002331 n->n_col_offset, c->c_arena);
Benjamin Peterson7a66fc22015-02-02 10:51:20 -05002332 else
Serhiy Storchakaddbce132017-11-15 17:39:37 +02002333 return ast_for_call(c, CHILD(n, 1), left_expr, true);
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002334 }
Benjamin Peterson7a66fc22015-02-02 10:51:20 -05002335 else if (TYPE(CHILD(n, 0)) == DOT) {
Benjamin Peterson30760062008-11-25 04:02:28 +00002336 PyObject *attr_id = NEW_IDENTIFIER(CHILD(n, 1));
2337 if (!attr_id)
2338 return NULL;
2339 return Attribute(left_expr, attr_id, Load,
Benjamin Peterson7a66fc22015-02-02 10:51:20 -05002340 LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton9ebfbf02006-02-27 16:50:35 +00002341 }
2342 else {
2343 REQ(CHILD(n, 0), LSQB);
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002344 REQ(CHILD(n, 2), RSQB);
2345 n = CHILD(n, 1);
Jeremy Hyltonc7d37262006-02-27 17:29:29 +00002346 if (NCH(n) == 1) {
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002347 slice_ty slc = ast_for_slice(c, CHILD(n, 0));
2348 if (!slc)
2349 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002350 return Subscript(left_expr, slc, Load, LINENO(n), n->n_col_offset,
2351 c->c_arena);
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002352 }
2353 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 /* The grammar is ambiguous here. The ambiguity is resolved
Jeremy Hyltonc7d37262006-02-27 17:29:29 +00002355 by treating the sequence as a tuple literal if there are
2356 no slice features.
2357 */
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002358 int j;
2359 slice_ty slc;
Jeremy Hyltonc7d37262006-02-27 17:29:29 +00002360 expr_ty e;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00002361 int simple = 1;
Jeremy Hyltonc7d37262006-02-27 17:29:29 +00002362 asdl_seq *slices, *elts;
Antoine Pitroud01d396e2013-10-12 22:52:43 +02002363 slices = _Py_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002364 if (!slices)
2365 return NULL;
2366 for (j = 0; j < NCH(n); j += 2) {
2367 slc = ast_for_slice(c, CHILD(n, j));
Neal Norwitzadb69fc2005-12-17 20:54:49 +00002368 if (!slc)
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002369 return NULL;
Jeremy Hyltonc7d37262006-02-27 17:29:29 +00002370 if (slc->kind != Index_kind)
Neal Norwitz6baa4c42007-02-26 19:14:12 +00002371 simple = 0;
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002372 asdl_seq_SET(slices, j / 2, slc);
2373 }
Jeremy Hyltonc7d37262006-02-27 17:29:29 +00002374 if (!simple) {
2375 return Subscript(left_expr, ExtSlice(slices, c->c_arena),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00002376 Load, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hyltonc7d37262006-02-27 17:29:29 +00002377 }
2378 /* extract Index values and put them in a Tuple */
Antoine Pitroud01d396e2013-10-12 22:52:43 +02002379 elts = _Py_asdl_seq_new(asdl_seq_LEN(slices), c->c_arena);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00002380 if (!elts)
2381 return NULL;
Jeremy Hyltonc7d37262006-02-27 17:29:29 +00002382 for (j = 0; j < asdl_seq_LEN(slices); ++j) {
2383 slc = (slice_ty)asdl_seq_GET(slices, j);
2384 assert(slc->kind == Index_kind && slc->v.Index.value);
2385 asdl_seq_SET(elts, j, slc->v.Index.value);
2386 }
Martin v. Löwis49c5da12006-03-01 22:49:05 +00002387 e = Tuple(elts, Load, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hyltonc7d37262006-02-27 17:29:29 +00002388 if (!e)
2389 return NULL;
2390 return Subscript(left_expr, Index(e, c->c_arena),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00002391 Load, LINENO(n), n->n_col_offset, c->c_arena);
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002392 }
2393 }
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002394}
2395
2396static expr_ty
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002397ast_for_factor(struct compiling *c, const node *n)
2398{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002399 expr_ty expression;
2400
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002401 expression = ast_for_expr(c, CHILD(n, 1));
2402 if (!expression)
2403 return NULL;
2404
2405 switch (TYPE(CHILD(n, 0))) {
2406 case PLUS:
2407 return UnaryOp(UAdd, expression, LINENO(n), n->n_col_offset,
2408 c->c_arena);
2409 case MINUS:
2410 return UnaryOp(USub, expression, LINENO(n), n->n_col_offset,
2411 c->c_arena);
2412 case TILDE:
2413 return UnaryOp(Invert, expression, LINENO(n),
2414 n->n_col_offset, c->c_arena);
2415 }
2416 PyErr_Format(PyExc_SystemError, "unhandled factor: %d",
2417 TYPE(CHILD(n, 0)));
2418 return NULL;
2419}
2420
2421static expr_ty
Yury Selivanov75445082015-05-11 22:57:16 -04002422ast_for_atom_expr(struct compiling *c, const node *n)
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002423{
Yury Selivanov75445082015-05-11 22:57:16 -04002424 int i, nch, start = 0;
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002425 expr_ty e, tmp;
Yury Selivanov75445082015-05-11 22:57:16 -04002426
2427 REQ(n, atom_expr);
2428 nch = NCH(n);
2429
Jelle Zijlstraac317702017-10-05 20:24:46 -07002430 if (TYPE(CHILD(n, 0)) == NAME && strcmp(STR(CHILD(n, 0)), "await") == 0) {
Yury Selivanov75445082015-05-11 22:57:16 -04002431 start = 1;
2432 assert(nch > 1);
2433 }
2434
2435 e = ast_for_atom(c, CHILD(n, start));
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002436 if (!e)
2437 return NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002438 if (nch == 1)
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002439 return e;
Yury Selivanov75445082015-05-11 22:57:16 -04002440 if (start && nch == 2) {
2441 return Await(e, LINENO(n), n->n_col_offset, c->c_arena);
2442 }
2443
2444 for (i = start + 1; i < nch; i++) {
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002445 node *ch = CHILD(n, i);
2446 if (TYPE(ch) != trailer)
2447 break;
2448 tmp = ast_for_trailer(c, ch, e);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00002449 if (!tmp)
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002450 return NULL;
Benjamin Peterson7a66fc22015-02-02 10:51:20 -05002451 tmp->lineno = e->lineno;
2452 tmp->col_offset = e->col_offset;
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002453 e = tmp;
2454 }
Yury Selivanov75445082015-05-11 22:57:16 -04002455
2456 if (start) {
Jelle Zijlstraac317702017-10-05 20:24:46 -07002457 /* there was an 'await' */
Yury Selivanov75445082015-05-11 22:57:16 -04002458 return Await(e, LINENO(n), n->n_col_offset, c->c_arena);
2459 }
2460 else {
2461 return e;
2462 }
2463}
2464
2465static expr_ty
2466ast_for_power(struct compiling *c, const node *n)
2467{
2468 /* power: atom trailer* ('**' factor)*
2469 */
2470 expr_ty e;
2471 REQ(n, power);
2472 e = ast_for_atom_expr(c, CHILD(n, 0));
2473 if (!e)
2474 return NULL;
2475 if (NCH(n) == 1)
2476 return e;
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002477 if (TYPE(CHILD(n, NCH(n) - 1)) == factor) {
2478 expr_ty f = ast_for_expr(c, CHILD(n, NCH(n) - 1));
Neal Norwitzadb69fc2005-12-17 20:54:49 +00002479 if (!f)
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002480 return NULL;
Benjamin Peterson7a66fc22015-02-02 10:51:20 -05002481 e = BinOp(e, Pow, f, LINENO(n), n->n_col_offset, c->c_arena);
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002482 }
2483 return e;
2484}
2485
Guido van Rossum0368b722007-05-11 16:50:42 +00002486static expr_ty
2487ast_for_starred(struct compiling *c, const node *n)
2488{
2489 expr_ty tmp;
2490 REQ(n, star_expr);
2491
2492 tmp = ast_for_expr(c, CHILD(n, 1));
2493 if (!tmp)
2494 return NULL;
2495
2496 /* The Load context is changed later. */
2497 return Starred(tmp, Load, LINENO(n), n->n_col_offset, c->c_arena);
2498}
2499
2500
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002501/* Do not name a variable 'expr'! Will cause a compile error.
2502*/
2503
2504static expr_ty
2505ast_for_expr(struct compiling *c, const node *n)
2506{
2507 /* handle the full range of simple expressions
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002508 test: or_test ['if' or_test 'else' test] | lambdef
Nick Coghlan650f0d02007-04-15 12:05:43 +00002509 test_nocond: or_test | lambdef_nocond
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 or_test: and_test ('or' and_test)*
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002511 and_test: not_test ('and' not_test)*
2512 not_test: 'not' not_test | comparison
2513 comparison: expr (comp_op expr)*
2514 expr: xor_expr ('|' xor_expr)*
2515 xor_expr: and_expr ('^' and_expr)*
2516 and_expr: shift_expr ('&' shift_expr)*
2517 shift_expr: arith_expr (('<<'|'>>') arith_expr)*
2518 arith_expr: term (('+'|'-') term)*
Benjamin Petersond51374e2014-04-09 23:55:56 -04002519 term: factor (('*'|'@'|'/'|'%'|'//') factor)*
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002520 factor: ('+'|'-'|'~') factor | power
Yury Selivanov75445082015-05-11 22:57:16 -04002521 power: atom_expr ['**' factor]
Jelle Zijlstraac317702017-10-05 20:24:46 -07002522 atom_expr: ['await'] atom trailer*
Yury Selivanov75445082015-05-11 22:57:16 -04002523 yield_expr: 'yield' [yield_arg]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002524 */
2525
2526 asdl_seq *seq;
2527 int i;
2528
2529 loop:
2530 switch (TYPE(n)) {
2531 case test:
Nick Coghlan650f0d02007-04-15 12:05:43 +00002532 case test_nocond:
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002533 if (TYPE(CHILD(n, 0)) == lambdef ||
Nick Coghlan650f0d02007-04-15 12:05:43 +00002534 TYPE(CHILD(n, 0)) == lambdef_nocond)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002535 return ast_for_lambdef(c, CHILD(n, 0));
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002536 else if (NCH(n) > 1)
2537 return ast_for_ifexpr(c, n);
Thomas Wouters89f507f2006-12-13 04:49:30 +00002538 /* Fallthrough */
2539 case or_test:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002540 case and_test:
2541 if (NCH(n) == 1) {
2542 n = CHILD(n, 0);
2543 goto loop;
2544 }
Antoine Pitroud01d396e2013-10-12 22:52:43 +02002545 seq = _Py_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002546 if (!seq)
2547 return NULL;
2548 for (i = 0; i < NCH(n); i += 2) {
2549 expr_ty e = ast_for_expr(c, CHILD(n, i));
2550 if (!e)
2551 return NULL;
2552 asdl_seq_SET(seq, i / 2, e);
2553 }
2554 if (!strcmp(STR(CHILD(n, 1)), "and"))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002555 return BoolOp(And, seq, LINENO(n), n->n_col_offset,
2556 c->c_arena);
Neal Norwitz84456bd2005-12-18 03:16:20 +00002557 assert(!strcmp(STR(CHILD(n, 1)), "or"));
Martin v. Löwis49c5da12006-03-01 22:49:05 +00002558 return BoolOp(Or, seq, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002559 case not_test:
2560 if (NCH(n) == 1) {
2561 n = CHILD(n, 0);
2562 goto loop;
2563 }
2564 else {
2565 expr_ty expression = ast_for_expr(c, CHILD(n, 1));
2566 if (!expression)
2567 return NULL;
2568
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002569 return UnaryOp(Not, expression, LINENO(n), n->n_col_offset,
2570 c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002571 }
2572 case comparison:
2573 if (NCH(n) == 1) {
2574 n = CHILD(n, 0);
2575 goto loop;
2576 }
2577 else {
2578 expr_ty expression;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002579 asdl_int_seq *ops;
Thomas Wouters89f507f2006-12-13 04:49:30 +00002580 asdl_seq *cmps;
Antoine Pitroud01d396e2013-10-12 22:52:43 +02002581 ops = _Py_asdl_int_seq_new(NCH(n) / 2, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582 if (!ops)
2583 return NULL;
Antoine Pitroud01d396e2013-10-12 22:52:43 +02002584 cmps = _Py_asdl_seq_new(NCH(n) / 2, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002585 if (!cmps) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002586 return NULL;
2587 }
2588 for (i = 1; i < NCH(n); i += 2) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002589 cmpop_ty newoperator;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002590
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002591 newoperator = ast_for_comp_op(c, CHILD(n, i));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002592 if (!newoperator) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002593 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00002594 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002595
2596 expression = ast_for_expr(c, CHILD(n, i + 1));
Neal Norwitze76adcd2005-11-15 05:04:31 +00002597 if (!expression) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002598 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00002599 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002601 asdl_seq_SET(ops, i / 2, newoperator);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002602 asdl_seq_SET(cmps, i / 2, expression);
2603 }
2604 expression = ast_for_expr(c, CHILD(n, 0));
Neal Norwitze76adcd2005-11-15 05:04:31 +00002605 if (!expression) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002606 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00002607 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002609 return Compare(expression, ops, cmps, LINENO(n),
2610 n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002611 }
2612 break;
2613
Guido van Rossum0368b722007-05-11 16:50:42 +00002614 case star_expr:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 return ast_for_starred(c, n);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002616 /* The next five cases all handle BinOps. The main body of code
2617 is the same in each case, but the switch turned inside out to
2618 reuse the code for each type of operator.
2619 */
2620 case expr:
2621 case xor_expr:
2622 case and_expr:
2623 case shift_expr:
2624 case arith_expr:
2625 case term:
2626 if (NCH(n) == 1) {
2627 n = CHILD(n, 0);
2628 goto loop;
2629 }
2630 return ast_for_binop(c, n);
2631 case yield_expr: {
Nick Coghlan1f7ce622012-01-13 21:43:40 +10002632 node *an = NULL;
2633 node *en = NULL;
2634 int is_from = 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00002635 expr_ty exp = NULL;
Nick Coghlan1f7ce622012-01-13 21:43:40 +10002636 if (NCH(n) > 1)
2637 an = CHILD(n, 1); /* yield_arg */
2638 if (an) {
2639 en = CHILD(an, NCH(an) - 1);
2640 if (NCH(an) == 2) {
2641 is_from = 1;
2642 exp = ast_for_expr(c, en);
2643 }
2644 else
2645 exp = ast_for_testlist(c, en);
Thomas Wouters89f507f2006-12-13 04:49:30 +00002646 if (!exp)
2647 return NULL;
2648 }
Benjamin Peterson527c6222012-01-14 08:58:23 -05002649 if (is_from)
2650 return YieldFrom(exp, LINENO(n), n->n_col_offset, c->c_arena);
2651 return Yield(exp, LINENO(n), n->n_col_offset, c->c_arena);
Thomas Wouters89f507f2006-12-13 04:49:30 +00002652 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002653 case factor:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002654 if (NCH(n) == 1) {
2655 n = CHILD(n, 0);
2656 goto loop;
2657 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00002658 return ast_for_factor(c, n);
Neil Schemenauer982e8d62005-10-25 09:16:05 +00002659 case power:
2660 return ast_for_power(c, n);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002661 default:
Neal Norwitz79792652005-11-14 04:25:03 +00002662 PyErr_Format(PyExc_SystemError, "unhandled expr: %d", TYPE(n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002663 return NULL;
2664 }
Neal Norwitz84456bd2005-12-18 03:16:20 +00002665 /* should never get here unless if error is set */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002666 return NULL;
2667}
2668
2669static expr_ty
Serhiy Storchakaddbce132017-11-15 17:39:37 +02002670ast_for_call(struct compiling *c, const node *n, expr_ty func, bool allowgen)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002671{
2672 /*
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002673 arglist: argument (',' argument)* [',']
2674 argument: ( test [comp_for] | '*' test | test '=' test | '**' test )
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002675 */
2676
Serhiy Storchaka9165f772017-11-15 08:49:40 +02002677 int i, nargs, nkeywords;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002678 int ndoublestars;
Neal Norwitz84456bd2005-12-18 03:16:20 +00002679 asdl_seq *args;
2680 asdl_seq *keywords;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002681
2682 REQ(n, arglist);
2683
2684 nargs = 0;
2685 nkeywords = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002686 for (i = 0; i < NCH(n); i++) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00002687 node *ch = CHILD(n, i);
2688 if (TYPE(ch) == argument) {
2689 if (NCH(ch) == 1)
2690 nargs++;
Serhiy Storchaka9165f772017-11-15 08:49:40 +02002691 else if (TYPE(CHILD(ch, 1)) == comp_for) {
2692 nargs++;
Serhiy Storchakaddbce132017-11-15 17:39:37 +02002693 if (!allowgen) {
2694 ast_error(c, ch, "invalid syntax");
2695 return NULL;
2696 }
Serhiy Storchaka9165f772017-11-15 08:49:40 +02002697 if (NCH(n) > 1) {
2698 ast_error(c, ch, "Generator expression must be parenthesized");
2699 return NULL;
2700 }
2701 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002702 else if (TYPE(CHILD(ch, 0)) == STAR)
2703 nargs++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002704 else
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002705 /* TYPE(CHILD(ch, 0)) == DOUBLESTAR or keyword argument */
Thomas Wouters89f507f2006-12-13 04:49:30 +00002706 nkeywords++;
2707 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002708 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709
Serhiy Storchaka9165f772017-11-15 08:49:40 +02002710 args = _Py_asdl_seq_new(nargs, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711 if (!args)
Neal Norwitzadb69fc2005-12-17 20:54:49 +00002712 return NULL;
Antoine Pitroud01d396e2013-10-12 22:52:43 +02002713 keywords = _Py_asdl_seq_new(nkeywords, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002714 if (!keywords)
Neal Norwitzadb69fc2005-12-17 20:54:49 +00002715 return NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002716
2717 nargs = 0; /* positional arguments + iterable argument unpackings */
2718 nkeywords = 0; /* keyword arguments + keyword argument unpackings */
2719 ndoublestars = 0; /* just keyword argument unpackings */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002720 for (i = 0; i < NCH(n); i++) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00002721 node *ch = CHILD(n, i);
2722 if (TYPE(ch) == argument) {
2723 expr_ty e;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002724 node *chch = CHILD(ch, 0);
Thomas Wouters89f507f2006-12-13 04:49:30 +00002725 if (NCH(ch) == 1) {
Yury Selivanov14acf5f2015-08-05 17:54:10 -04002726 /* a positional argument */
2727 if (nkeywords) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002728 if (ndoublestars) {
2729 ast_error(c, chch,
Yury Selivanov14acf5f2015-08-05 17:54:10 -04002730 "positional argument follows "
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002731 "keyword argument unpacking");
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002732 }
Yury Selivanov14acf5f2015-08-05 17:54:10 -04002733 else {
2734 ast_error(c, chch,
2735 "positional argument follows "
2736 "keyword argument");
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002737 }
Yury Selivanov14acf5f2015-08-05 17:54:10 -04002738 return NULL;
Benjamin Peterson2d735bc2008-08-19 20:57:10 +00002739 }
Yury Selivanov14acf5f2015-08-05 17:54:10 -04002740 e = ast_for_expr(c, chch);
2741 if (!e)
2742 return NULL;
2743 asdl_seq_SET(args, nargs++, e);
2744 }
2745 else if (TYPE(chch) == STAR) {
2746 /* an iterable argument unpacking */
2747 expr_ty starred;
2748 if (ndoublestars) {
2749 ast_error(c, chch,
2750 "iterable argument unpacking follows "
2751 "keyword argument unpacking");
2752 return NULL;
2753 }
2754 e = ast_for_expr(c, CHILD(ch, 1));
2755 if (!e)
2756 return NULL;
2757 starred = Starred(e, Load, LINENO(chch),
2758 chch->n_col_offset,
2759 c->c_arena);
2760 if (!starred)
2761 return NULL;
2762 asdl_seq_SET(args, nargs++, starred);
2763
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002764 }
2765 else if (TYPE(chch) == DOUBLESTAR) {
2766 /* a keyword argument unpacking */
2767 keyword_ty kw;
2768 i++;
2769 e = ast_for_expr(c, CHILD(ch, 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002770 if (!e)
Neal Norwitzadb69fc2005-12-17 20:54:49 +00002771 return NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002772 kw = keyword(NULL, e, c->c_arena);
2773 asdl_seq_SET(keywords, nkeywords++, kw);
2774 ndoublestars++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002776 else if (TYPE(CHILD(ch, 1)) == comp_for) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002777 /* the lone generator expression */
Thomas Wouters89f507f2006-12-13 04:49:30 +00002778 e = ast_for_genexp(c, ch);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002779 if (!e)
Neal Norwitzadb69fc2005-12-17 20:54:49 +00002780 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00002781 asdl_seq_SET(args, nargs++, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002782 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00002783 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002784 /* a keyword argument */
Thomas Wouters89f507f2006-12-13 04:49:30 +00002785 keyword_ty kw;
Benjamin Peterson07a1f942008-07-01 20:03:27 +00002786 identifier key, tmp;
2787 int k;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002788
Benjamin Petersonc9a71dd2018-09-12 17:14:39 -07002789 // To remain LL(1), the grammar accepts any test (basically, any
2790 // expression) in the keyword slot of a call site. So, we need
2791 // to manually enforce that the keyword is a NAME here.
2792 static const int name_tree[] = {
2793 test,
2794 or_test,
2795 and_test,
2796 not_test,
2797 comparison,
2798 expr,
2799 xor_expr,
2800 and_expr,
2801 shift_expr,
2802 arith_expr,
2803 term,
2804 factor,
2805 power,
2806 atom_expr,
2807 atom,
2808 0,
2809 };
2810 node *expr_node = chch;
2811 for (int i = 0; name_tree[i]; i++) {
2812 if (TYPE(expr_node) != name_tree[i])
2813 break;
2814 if (NCH(expr_node) != 1)
2815 break;
2816 expr_node = CHILD(expr_node, 0);
2817 }
2818 if (TYPE(expr_node) == lambdef) {
2819 // f(lambda x: x[0] = 3) ends up getting parsed with LHS
2820 // test = lambda x: x[0], and RHS test = 3. Issue #132313
2821 // points out that complaining about a keyword then is very
2822 // confusing.
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002823 ast_error(c, chch,
2824 "lambda cannot contain assignment");
Benjamin Petersonc64ae922012-01-16 18:02:21 -05002825 return NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002826 }
Benjamin Petersonc9a71dd2018-09-12 17:14:39 -07002827 else if (TYPE(expr_node) != NAME) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002828 ast_error(c, chch,
Benjamin Petersonc9a71dd2018-09-12 17:14:39 -07002829 "keyword can't be an expression");
Benjamin Petersonc64ae922012-01-16 18:02:21 -05002830 return NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002831 }
Benjamin Petersonc9a71dd2018-09-12 17:14:39 -07002832 key = new_identifier(STR(expr_node), c);
2833 if (key == NULL) {
Benjamin Petersonc64ae922012-01-16 18:02:21 -05002834 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 }
Benjamin Petersonc9a71dd2018-09-12 17:14:39 -07002836 if (forbidden_name(c, key, chch, 1)) {
2837 return NULL;
2838 }
Benjamin Peterson07a1f942008-07-01 20:03:27 +00002839 for (k = 0; k < nkeywords; k++) {
2840 tmp = ((keyword_ty)asdl_seq_GET(keywords, k))->arg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002841 if (tmp && !PyUnicode_Compare(tmp, key)) {
2842 ast_error(c, chch,
2843 "keyword argument repeated");
Benjamin Peterson07a1f942008-07-01 20:03:27 +00002844 return NULL;
2845 }
2846 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00002847 e = ast_for_expr(c, CHILD(ch, 2));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002848 if (!e)
Neal Norwitzadb69fc2005-12-17 20:54:49 +00002849 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00002850 kw = keyword(key, e, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002851 if (!kw)
Neal Norwitzadb69fc2005-12-17 20:54:49 +00002852 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00002853 asdl_seq_SET(keywords, nkeywords++, kw);
2854 }
2855 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002856 }
2857
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002858 return Call(func, args, keywords, func->lineno, func->col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002859}
2860
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002861static expr_ty
Neil Schemenauerc5dd10a2005-10-25 07:54:54 +00002862ast_for_testlist(struct compiling *c, const node* n)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002863{
Nick Coghlan650f0d02007-04-15 12:05:43 +00002864 /* testlist_comp: test (comp_for | (',' test)* [',']) */
Neil Schemenauerc5dd10a2005-10-25 07:54:54 +00002865 /* testlist: test (',' test)* [','] */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002866 assert(NCH(n) > 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002867 if (TYPE(n) == testlist_comp) {
Neil Schemenauerc5dd10a2005-10-25 07:54:54 +00002868 if (NCH(n) > 1)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002869 assert(TYPE(CHILD(n, 1)) != comp_for);
Neil Schemenauerc5dd10a2005-10-25 07:54:54 +00002870 }
2871 else {
2872 assert(TYPE(n) == testlist ||
Benjamin Peterson4905e802009-09-27 02:43:28 +00002873 TYPE(n) == testlist_star_expr);
Neil Schemenauerc5dd10a2005-10-25 07:54:54 +00002874 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002875 if (NCH(n) == 1)
Thomas Wouters89f507f2006-12-13 04:49:30 +00002876 return ast_for_expr(c, CHILD(n, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002877 else {
2878 asdl_seq *tmp = seq_for_testlist(c, n);
2879 if (!tmp)
2880 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00002881 return Tuple(tmp, Load, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882 }
Neil Schemenauerc5dd10a2005-10-25 07:54:54 +00002883}
2884
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002885static stmt_ty
2886ast_for_expr_stmt(struct compiling *c, const node *n)
2887{
2888 REQ(n, expr_stmt);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002889 /* expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) |
2890 ('=' (yield_expr|testlist_star_expr))*)
2891 annassign: ':' test ['=' test]
Benjamin Peterson4905e802009-09-27 02:43:28 +00002892 testlist_star_expr: (test|star_expr) (',' test|star_expr)* [',']
Benjamin Petersond51374e2014-04-09 23:55:56 -04002893 augassign: '+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^='
Thomas Wouters89f507f2006-12-13 04:49:30 +00002894 | '<<=' | '>>=' | '**=' | '//='
Martin Panter69332c12016-08-04 13:07:31 +00002895 test: ... here starts the operator precedence dance
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002896 */
2897
2898 if (NCH(n) == 1) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00002899 expr_ty e = ast_for_testlist(c, CHILD(n, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002900 if (!e)
2901 return NULL;
2902
Thomas Wouters89f507f2006-12-13 04:49:30 +00002903 return Expr(e, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002904 }
2905 else if (TYPE(CHILD(n, 1)) == augassign) {
2906 expr_ty expr1, expr2;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002907 operator_ty newoperator;
Thomas Wouters89f507f2006-12-13 04:49:30 +00002908 node *ch = CHILD(n, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002909
Thomas Wouters89f507f2006-12-13 04:49:30 +00002910 expr1 = ast_for_testlist(c, ch);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002911 if (!expr1)
2912 return NULL;
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002913 if(!set_context(c, expr1, Store, ch))
2914 return NULL;
Benjamin Petersonbd27aef2009-10-03 20:27:13 +00002915 /* set_context checks that most expressions are not the left side.
2916 Augmented assignments can only have a name, a subscript, or an
2917 attribute on the left, though, so we have to explicitly check for
2918 those. */
2919 switch (expr1->kind) {
2920 case Name_kind:
2921 case Attribute_kind:
2922 case Subscript_kind:
2923 break;
2924 default:
Benjamin Petersonbd0df502012-09-02 15:04:51 -04002925 ast_error(c, ch, "illegal expression for augmented assignment");
Benjamin Petersonbd27aef2009-10-03 20:27:13 +00002926 return NULL;
2927 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002928
Thomas Wouters89f507f2006-12-13 04:49:30 +00002929 ch = CHILD(n, 2);
2930 if (TYPE(ch) == testlist)
2931 expr2 = ast_for_testlist(c, ch);
2932 else
2933 expr2 = ast_for_expr(c, ch);
Neal Norwitz84456bd2005-12-18 03:16:20 +00002934 if (!expr2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002935 return NULL;
2936
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002937 newoperator = ast_for_augassign(c, CHILD(n, 1));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002938 if (!newoperator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939 return NULL;
2940
Thomas Wouters89f507f2006-12-13 04:49:30 +00002941 return AugAssign(expr1, newoperator, expr2, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002943 else if (TYPE(CHILD(n, 1)) == annassign) {
2944 expr_ty expr1, expr2, expr3;
2945 node *ch = CHILD(n, 0);
2946 node *deep, *ann = CHILD(n, 1);
2947 int simple = 1;
2948
2949 /* we keep track of parens to qualify (x) as expression not name */
2950 deep = ch;
2951 while (NCH(deep) == 1) {
2952 deep = CHILD(deep, 0);
2953 }
2954 if (NCH(deep) > 0 && TYPE(CHILD(deep, 0)) == LPAR) {
2955 simple = 0;
2956 }
2957 expr1 = ast_for_testlist(c, ch);
2958 if (!expr1) {
2959 return NULL;
2960 }
2961 switch (expr1->kind) {
2962 case Name_kind:
2963 if (forbidden_name(c, expr1->v.Name.id, n, 0)) {
2964 return NULL;
2965 }
2966 expr1->v.Name.ctx = Store;
2967 break;
2968 case Attribute_kind:
2969 if (forbidden_name(c, expr1->v.Attribute.attr, n, 1)) {
2970 return NULL;
2971 }
2972 expr1->v.Attribute.ctx = Store;
2973 break;
2974 case Subscript_kind:
2975 expr1->v.Subscript.ctx = Store;
2976 break;
2977 case List_kind:
2978 ast_error(c, ch,
2979 "only single target (not list) can be annotated");
2980 return NULL;
2981 case Tuple_kind:
2982 ast_error(c, ch,
2983 "only single target (not tuple) can be annotated");
2984 return NULL;
2985 default:
2986 ast_error(c, ch,
2987 "illegal target for annotation");
2988 return NULL;
2989 }
2990
2991 if (expr1->kind != Name_kind) {
2992 simple = 0;
2993 }
2994 ch = CHILD(ann, 1);
2995 expr2 = ast_for_expr(c, ch);
2996 if (!expr2) {
2997 return NULL;
2998 }
2999 if (NCH(ann) == 2) {
3000 return AnnAssign(expr1, expr2, NULL, simple,
3001 LINENO(n), n->n_col_offset, c->c_arena);
3002 }
3003 else {
3004 ch = CHILD(ann, 3);
3005 expr3 = ast_for_expr(c, ch);
3006 if (!expr3) {
3007 return NULL;
3008 }
3009 return AnnAssign(expr1, expr2, expr3, simple,
3010 LINENO(n), n->n_col_offset, c->c_arena);
3011 }
3012 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003013 else {
Thomas Wouters89f507f2006-12-13 04:49:30 +00003014 int i;
3015 asdl_seq *targets;
3016 node *value;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003017 expr_ty expression;
3018
Thomas Wouters89f507f2006-12-13 04:49:30 +00003019 /* a normal assignment */
3020 REQ(CHILD(n, 1), EQUAL);
Antoine Pitroud01d396e2013-10-12 22:52:43 +02003021 targets = _Py_asdl_seq_new(NCH(n) / 2, c->c_arena);
Thomas Wouters89f507f2006-12-13 04:49:30 +00003022 if (!targets)
3023 return NULL;
3024 for (i = 0; i < NCH(n) - 2; i += 2) {
3025 expr_ty e;
3026 node *ch = CHILD(n, i);
3027 if (TYPE(ch) == yield_expr) {
Benjamin Petersonbd0df502012-09-02 15:04:51 -04003028 ast_error(c, ch, "assignment to yield expression not possible");
Thomas Wouters89f507f2006-12-13 04:49:30 +00003029 return NULL;
3030 }
3031 e = ast_for_testlist(c, ch);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 if (!e)
Thomas Wouters89f507f2006-12-13 04:49:30 +00003033 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003034
Amaury Forgeot d'Arc92dc80a2010-08-19 17:43:15 +00003035 /* set context to assign */
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003036 if (!set_context(c, e, Store, CHILD(n, i)))
Thomas Wouters89f507f2006-12-13 04:49:30 +00003037 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003038
Thomas Wouters89f507f2006-12-13 04:49:30 +00003039 asdl_seq_SET(targets, i / 2, e);
3040 }
3041 value = CHILD(n, NCH(n) - 1);
Benjamin Peterson4905e802009-09-27 02:43:28 +00003042 if (TYPE(value) == testlist_star_expr)
Thomas Wouters89f507f2006-12-13 04:49:30 +00003043 expression = ast_for_testlist(c, value);
3044 else
3045 expression = ast_for_expr(c, value);
3046 if (!expression)
3047 return NULL;
3048 return Assign(targets, expression, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003049 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003050}
3051
Benjamin Peterson78565b22009-06-28 19:19:51 +00003052
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003053static asdl_seq *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003054ast_for_exprlist(struct compiling *c, const node *n, expr_context_ty context)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003055{
3056 asdl_seq *seq;
3057 int i;
3058 expr_ty e;
3059
3060 REQ(n, exprlist);
3061
Antoine Pitroud01d396e2013-10-12 22:52:43 +02003062 seq = _Py_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003063 if (!seq)
Thomas Wouters89f507f2006-12-13 04:49:30 +00003064 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003065 for (i = 0; i < NCH(n); i += 2) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00003066 e = ast_for_expr(c, CHILD(n, i));
3067 if (!e)
3068 return NULL;
3069 asdl_seq_SET(seq, i / 2, e);
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003070 if (context && !set_context(c, e, context, CHILD(n, i)))
Thomas Wouters89f507f2006-12-13 04:49:30 +00003071 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003072 }
3073 return seq;
3074}
3075
3076static stmt_ty
3077ast_for_del_stmt(struct compiling *c, const node *n)
3078{
3079 asdl_seq *expr_list;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003081 /* del_stmt: 'del' exprlist */
3082 REQ(n, del_stmt);
3083
3084 expr_list = ast_for_exprlist(c, CHILD(n, 1), Del);
3085 if (!expr_list)
3086 return NULL;
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003087 return Delete(expr_list, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003088}
3089
3090static stmt_ty
3091ast_for_flow_stmt(struct compiling *c, const node *n)
3092{
3093 /*
3094 flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
3095 | yield_stmt
3096 break_stmt: 'break'
3097 continue_stmt: 'continue'
3098 return_stmt: 'return' [testlist]
3099 yield_stmt: yield_expr
Nick Coghlan1f7ce622012-01-13 21:43:40 +10003100 yield_expr: 'yield' testlist | 'yield' 'from' test
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003101 raise_stmt: 'raise' [test [',' test [',' test]]]
3102 */
3103 node *ch;
3104
3105 REQ(n, flow_stmt);
3106 ch = CHILD(n, 0);
3107 switch (TYPE(ch)) {
3108 case break_stmt:
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003109 return Break(LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003110 case continue_stmt:
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003111 return Continue(LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003112 case yield_stmt: { /* will reduce to yield_expr */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003113 expr_ty exp = ast_for_expr(c, CHILD(ch, 0));
3114 if (!exp)
3115 return NULL;
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003116 return Expr(exp, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003117 }
3118 case return_stmt:
3119 if (NCH(ch) == 1)
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003120 return Return(NULL, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003121 else {
Neil Schemenauerc5dd10a2005-10-25 07:54:54 +00003122 expr_ty expression = ast_for_testlist(c, CHILD(ch, 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003123 if (!expression)
3124 return NULL;
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003125 return Return(expression, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003126 }
3127 case raise_stmt:
3128 if (NCH(ch) == 1)
Collin Winter828f04a2007-08-31 00:04:24 +00003129 return Raise(NULL, NULL, LINENO(n), n->n_col_offset, c->c_arena);
3130 else if (NCH(ch) >= 2) {
3131 expr_ty cause = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003132 expr_ty expression = ast_for_expr(c, CHILD(ch, 1));
3133 if (!expression)
3134 return NULL;
Collin Winter828f04a2007-08-31 00:04:24 +00003135 if (NCH(ch) == 4) {
3136 cause = ast_for_expr(c, CHILD(ch, 3));
3137 if (!cause)
3138 return NULL;
3139 }
3140 return Raise(expression, cause, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003141 }
Stefan Krahf432a322017-08-21 13:09:59 +02003142 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003143 default:
Neal Norwitz79792652005-11-14 04:25:03 +00003144 PyErr_Format(PyExc_SystemError,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003145 "unexpected flow_stmt: %d", TYPE(ch));
3146 return NULL;
3147 }
3148}
3149
3150static alias_ty
Benjamin Peterson78565b22009-06-28 19:19:51 +00003151alias_for_import_name(struct compiling *c, const node *n, int store)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003152{
3153 /*
Thomas Wouters8ae12952006-02-28 22:42:15 +00003154 import_as_name: NAME ['as' NAME]
3155 dotted_as_name: dotted_name ['as' NAME]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003156 dotted_name: NAME ('.' NAME)*
3157 */
Benjamin Peterson78565b22009-06-28 19:19:51 +00003158 identifier str, name;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00003159
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003160 loop:
3161 switch (TYPE(n)) {
Benjamin Petersonf63d6152011-06-20 21:40:19 -05003162 case import_as_name: {
Benjamin Peterson78565b22009-06-28 19:19:51 +00003163 node *name_node = CHILD(n, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003164 str = NULL;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003165 name = NEW_IDENTIFIER(name_node);
Benjamin Peterson30760062008-11-25 04:02:28 +00003166 if (!name)
3167 return NULL;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003168 if (NCH(n) == 3) {
3169 node *str_node = CHILD(n, 2);
3170 str = NEW_IDENTIFIER(str_node);
3171 if (!str)
3172 return NULL;
Benjamin Petersonbd0df502012-09-02 15:04:51 -04003173 if (store && forbidden_name(c, str, str_node, 0))
Benjamin Peterson78565b22009-06-28 19:19:51 +00003174 return NULL;
3175 }
3176 else {
Benjamin Petersonbd0df502012-09-02 15:04:51 -04003177 if (forbidden_name(c, name, name_node, 0))
Benjamin Peterson78565b22009-06-28 19:19:51 +00003178 return NULL;
3179 }
Benjamin Peterson30760062008-11-25 04:02:28 +00003180 return alias(name, str, c->c_arena);
Benjamin Peterson78565b22009-06-28 19:19:51 +00003181 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003182 case dotted_as_name:
3183 if (NCH(n) == 1) {
3184 n = CHILD(n, 0);
3185 goto loop;
3186 }
3187 else {
Benjamin Peterson78565b22009-06-28 19:19:51 +00003188 node *asname_node = CHILD(n, 2);
3189 alias_ty a = alias_for_import_name(c, CHILD(n, 0), 0);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003190 if (!a)
3191 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003192 assert(!a->asname);
Benjamin Peterson78565b22009-06-28 19:19:51 +00003193 a->asname = NEW_IDENTIFIER(asname_node);
Benjamin Peterson30760062008-11-25 04:02:28 +00003194 if (!a->asname)
3195 return NULL;
Benjamin Petersonbd0df502012-09-02 15:04:51 -04003196 if (forbidden_name(c, a->asname, asname_node, 0))
Benjamin Peterson78565b22009-06-28 19:19:51 +00003197 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003198 return a;
3199 }
3200 break;
3201 case dotted_name:
Benjamin Peterson30760062008-11-25 04:02:28 +00003202 if (NCH(n) == 1) {
Benjamin Peterson78565b22009-06-28 19:19:51 +00003203 node *name_node = CHILD(n, 0);
3204 name = NEW_IDENTIFIER(name_node);
Benjamin Peterson30760062008-11-25 04:02:28 +00003205 if (!name)
3206 return NULL;
Benjamin Petersonbd0df502012-09-02 15:04:51 -04003207 if (store && forbidden_name(c, name, name_node, 0))
Benjamin Peterson78565b22009-06-28 19:19:51 +00003208 return NULL;
Benjamin Peterson30760062008-11-25 04:02:28 +00003209 return alias(name, NULL, c->c_arena);
3210 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003211 else {
3212 /* Create a string of the form "a.b.c" */
Tim Peterse93e64f2006-01-08 02:28:41 +00003213 int i;
Tim Peters5db42c42006-01-08 02:25:34 +00003214 size_t len;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003215 char *s;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 PyObject *uni;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003217
3218 len = 0;
3219 for (i = 0; i < NCH(n); i += 2)
3220 /* length of string plus one for the dot */
3221 len += strlen(STR(CHILD(n, i))) + 1;
3222 len--; /* the last name doesn't have a dot */
Christian Heimes72b710a2008-05-26 13:28:38 +00003223 str = PyBytes_FromStringAndSize(NULL, len);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003224 if (!str)
3225 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00003226 s = PyBytes_AS_STRING(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003227 if (!s)
3228 return NULL;
3229 for (i = 0; i < NCH(n); i += 2) {
3230 char *sch = STR(CHILD(n, i));
3231 strcpy(s, STR(CHILD(n, i)));
3232 s += strlen(sch);
3233 *s++ = '.';
3234 }
3235 --s;
3236 *s = '\0';
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str),
3238 PyBytes_GET_SIZE(str),
3239 NULL);
3240 Py_DECREF(str);
3241 if (!uni)
3242 return NULL;
3243 str = uni;
Martin v. Löwis5b222132007-06-10 09:51:05 +00003244 PyUnicode_InternInPlace(&str);
Victor Stinner43d81952013-07-17 00:57:58 +02003245 if (PyArena_AddPyObject(c->c_arena, str) < 0) {
3246 Py_DECREF(str);
3247 return NULL;
3248 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00003249 return alias(str, NULL, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003250 }
3251 break;
3252 case STAR:
Martin v. Löwis5b222132007-06-10 09:51:05 +00003253 str = PyUnicode_InternFromString("*");
Alexey Izbyshev28853a22018-08-22 07:55:16 +03003254 if (!str)
3255 return NULL;
Victor Stinner43d81952013-07-17 00:57:58 +02003256 if (PyArena_AddPyObject(c->c_arena, str) < 0) {
3257 Py_DECREF(str);
3258 return NULL;
3259 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00003260 return alias(str, NULL, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003261 default:
Neal Norwitz79792652005-11-14 04:25:03 +00003262 PyErr_Format(PyExc_SystemError,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263 "unexpected import name: %d", TYPE(n));
3264 return NULL;
3265 }
Neal Norwitz84456bd2005-12-18 03:16:20 +00003266
3267 PyErr_SetString(PyExc_SystemError, "unhandled import name condition");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003268 return NULL;
3269}
3270
3271static stmt_ty
3272ast_for_import_stmt(struct compiling *c, const node *n)
3273{
3274 /*
3275 import_stmt: import_name | import_from
3276 import_name: 'import' dotted_as_names
Georg Brandle66c8c72007-03-19 18:56:50 +00003277 import_from: 'from' (('.' | '...')* dotted_name | ('.' | '...')+)
3278 'import' ('*' | '(' import_as_names ')' | import_as_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003279 */
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003280 int lineno;
3281 int col_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003282 int i;
3283 asdl_seq *aliases;
3284
3285 REQ(n, import_stmt);
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003286 lineno = LINENO(n);
3287 col_offset = n->n_col_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003288 n = CHILD(n, 0);
Thomas Wouters8622e932006-02-27 17:14:45 +00003289 if (TYPE(n) == import_name) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003290 n = CHILD(n, 1);
Thomas Wouters89f507f2006-12-13 04:49:30 +00003291 REQ(n, dotted_as_names);
Antoine Pitroud01d396e2013-10-12 22:52:43 +02003292 aliases = _Py_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
Thomas Wouters89f507f2006-12-13 04:49:30 +00003293 if (!aliases)
3294 return NULL;
3295 for (i = 0; i < NCH(n); i += 2) {
Benjamin Peterson78565b22009-06-28 19:19:51 +00003296 alias_ty import_alias = alias_for_import_name(c, CHILD(n, i), 1);
Neal Norwitz84456bd2005-12-18 03:16:20 +00003297 if (!import_alias)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003298 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003299 asdl_seq_SET(aliases, i / 2, import_alias);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003300 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00003301 return Import(aliases, lineno, col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003302 }
Thomas Wouters8622e932006-02-27 17:14:45 +00003303 else if (TYPE(n) == import_from) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003304 int n_children;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003305 int idx, ndots = 0;
3306 alias_ty mod = NULL;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003307 identifier modname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003309 /* Count the number of dots (for relative imports) and check for the
3310 optional module name */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003311 for (idx = 1; idx < NCH(n); idx++) {
3312 if (TYPE(CHILD(n, idx)) == dotted_name) {
Benjamin Peterson78565b22009-06-28 19:19:51 +00003313 mod = alias_for_import_name(c, CHILD(n, idx), 0);
3314 if (!mod)
3315 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003316 idx++;
3317 break;
Georg Brandle66c8c72007-03-19 18:56:50 +00003318 } else if (TYPE(CHILD(n, idx)) == ELLIPSIS) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 /* three consecutive dots are tokenized as one ELLIPSIS */
Georg Brandle66c8c72007-03-19 18:56:50 +00003320 ndots += 3;
3321 continue;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003322 } else if (TYPE(CHILD(n, idx)) != DOT) {
3323 break;
3324 }
3325 ndots++;
3326 }
3327 idx++; /* skip over the 'import' keyword */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003328 switch (TYPE(CHILD(n, idx))) {
Thomas Wouters106203c2006-02-27 17:05:19 +00003329 case STAR:
3330 /* from ... import * */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003331 n = CHILD(n, idx);
3332 n_children = 1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003333 break;
3334 case LPAR:
3335 /* from ... import (x, y, z) */
3336 n = CHILD(n, idx + 1);
3337 n_children = NCH(n);
3338 break;
3339 case import_as_names:
3340 /* from ... import x, y, z */
3341 n = CHILD(n, idx);
3342 n_children = NCH(n);
Thomas Wouters106203c2006-02-27 17:05:19 +00003343 if (n_children % 2 == 0) {
Benjamin Petersonbd0df502012-09-02 15:04:51 -04003344 ast_error(c, n, "trailing comma not allowed without"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003345 " surrounding parentheses");
3346 return NULL;
3347 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00003348 break;
3349 default:
Benjamin Petersonbd0df502012-09-02 15:04:51 -04003350 ast_error(c, n, "Unexpected node-type in from-import");
Thomas Wouters89f507f2006-12-13 04:49:30 +00003351 return NULL;
3352 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003353
Antoine Pitroud01d396e2013-10-12 22:52:43 +02003354 aliases = _Py_asdl_seq_new((n_children + 1) / 2, c->c_arena);
Thomas Wouters89f507f2006-12-13 04:49:30 +00003355 if (!aliases)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003356 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003357
3358 /* handle "from ... import *" special b/c there's no children */
Thomas Wouters106203c2006-02-27 17:05:19 +00003359 if (TYPE(n) == STAR) {
Benjamin Peterson78565b22009-06-28 19:19:51 +00003360 alias_ty import_alias = alias_for_import_name(c, n, 1);
Neal Norwitz84456bd2005-12-18 03:16:20 +00003361 if (!import_alias)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003362 return NULL;
Georg Brandl5c60ea32016-01-18 07:53:59 +01003363 asdl_seq_SET(aliases, 0, import_alias);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003364 }
Jeremy Hyltona8293132006-02-28 17:58:27 +00003365 else {
Thomas Wouters89f507f2006-12-13 04:49:30 +00003366 for (i = 0; i < NCH(n); i += 2) {
Benjamin Peterson78565b22009-06-28 19:19:51 +00003367 alias_ty import_alias = alias_for_import_name(c, CHILD(n, i), 1);
Jeremy Hyltona8293132006-02-28 17:58:27 +00003368 if (!import_alias)
3369 return NULL;
Georg Brandl5c60ea32016-01-18 07:53:59 +01003370 asdl_seq_SET(aliases, i / 2, import_alias);
Jeremy Hyltona8293132006-02-28 17:58:27 +00003371 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003372 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003373 if (mod != NULL)
3374 modname = mod->name;
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003375 return ImportFrom(modname, aliases, ndots, lineno, col_offset,
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003376 c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003377 }
Neal Norwitz79792652005-11-14 04:25:03 +00003378 PyErr_Format(PyExc_SystemError,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003379 "unknown import statement: starts with command '%s'",
3380 STR(CHILD(n, 0)));
3381 return NULL;
3382}
3383
3384static stmt_ty
3385ast_for_global_stmt(struct compiling *c, const node *n)
3386{
3387 /* global_stmt: 'global' NAME (',' NAME)* */
3388 identifier name;
3389 asdl_seq *s;
3390 int i;
3391
3392 REQ(n, global_stmt);
Antoine Pitroud01d396e2013-10-12 22:52:43 +02003393 s = _Py_asdl_seq_new(NCH(n) / 2, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003394 if (!s)
Thomas Wouters89f507f2006-12-13 04:49:30 +00003395 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003396 for (i = 1; i < NCH(n); i += 2) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00003397 name = NEW_IDENTIFIER(CHILD(n, i));
3398 if (!name)
3399 return NULL;
3400 asdl_seq_SET(s, i / 2, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003401 }
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003402 return Global(s, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003403}
3404
3405static stmt_ty
Jeremy Hylton81e95022007-02-27 06:50:52 +00003406ast_for_nonlocal_stmt(struct compiling *c, const node *n)
3407{
3408 /* nonlocal_stmt: 'nonlocal' NAME (',' NAME)* */
3409 identifier name;
3410 asdl_seq *s;
3411 int i;
3412
3413 REQ(n, nonlocal_stmt);
Antoine Pitroud01d396e2013-10-12 22:52:43 +02003414 s = _Py_asdl_seq_new(NCH(n) / 2, c->c_arena);
Jeremy Hylton81e95022007-02-27 06:50:52 +00003415 if (!s)
3416 return NULL;
3417 for (i = 1; i < NCH(n); i += 2) {
3418 name = NEW_IDENTIFIER(CHILD(n, i));
3419 if (!name)
3420 return NULL;
3421 asdl_seq_SET(s, i / 2, name);
3422 }
3423 return Nonlocal(s, LINENO(n), n->n_col_offset, c->c_arena);
3424}
3425
3426static stmt_ty
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003427ast_for_assert_stmt(struct compiling *c, const node *n)
3428{
3429 /* assert_stmt: 'assert' test [',' test] */
3430 REQ(n, assert_stmt);
3431 if (NCH(n) == 2) {
3432 expr_ty expression = ast_for_expr(c, CHILD(n, 1));
3433 if (!expression)
3434 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003435 return Assert(expression, NULL, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003436 }
3437 else if (NCH(n) == 4) {
3438 expr_ty expr1, expr2;
3439
3440 expr1 = ast_for_expr(c, CHILD(n, 1));
3441 if (!expr1)
3442 return NULL;
3443 expr2 = ast_for_expr(c, CHILD(n, 3));
3444 if (!expr2)
3445 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446
Thomas Wouters89f507f2006-12-13 04:49:30 +00003447 return Assert(expr1, expr2, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003448 }
Neal Norwitz79792652005-11-14 04:25:03 +00003449 PyErr_Format(PyExc_SystemError,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003450 "improper number of parts to 'assert' statement: %d",
3451 NCH(n));
3452 return NULL;
3453}
3454
3455static asdl_seq *
3456ast_for_suite(struct compiling *c, const node *n)
3457{
3458 /* suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT */
Neal Norwitz84456bd2005-12-18 03:16:20 +00003459 asdl_seq *seq;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003460 stmt_ty s;
3461 int i, total, num, end, pos = 0;
3462 node *ch;
3463
3464 REQ(n, suite);
3465
3466 total = num_stmts(n);
Antoine Pitroud01d396e2013-10-12 22:52:43 +02003467 seq = _Py_asdl_seq_new(total, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003468 if (!seq)
Thomas Wouters89f507f2006-12-13 04:49:30 +00003469 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003470 if (TYPE(CHILD(n, 0)) == simple_stmt) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00003471 n = CHILD(n, 0);
3472 /* simple_stmt always ends with a NEWLINE,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003473 and may have a trailing SEMI
Thomas Wouters89f507f2006-12-13 04:49:30 +00003474 */
3475 end = NCH(n) - 1;
3476 if (TYPE(CHILD(n, end - 1)) == SEMI)
3477 end--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003478 /* loop by 2 to skip semi-colons */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003479 for (i = 0; i < end; i += 2) {
3480 ch = CHILD(n, i);
3481 s = ast_for_stmt(c, ch);
3482 if (!s)
3483 return NULL;
3484 asdl_seq_SET(seq, pos++, s);
3485 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003486 }
3487 else {
Thomas Wouters89f507f2006-12-13 04:49:30 +00003488 for (i = 2; i < (NCH(n) - 1); i++) {
3489 ch = CHILD(n, i);
3490 REQ(ch, stmt);
3491 num = num_stmts(ch);
3492 if (num == 1) {
3493 /* small_stmt or compound_stmt with only one child */
3494 s = ast_for_stmt(c, ch);
3495 if (!s)
3496 return NULL;
3497 asdl_seq_SET(seq, pos++, s);
3498 }
3499 else {
3500 int j;
3501 ch = CHILD(ch, 0);
3502 REQ(ch, simple_stmt);
3503 for (j = 0; j < NCH(ch); j += 2) {
3504 /* statement terminates with a semi-colon ';' */
3505 if (NCH(CHILD(ch, j)) == 0) {
3506 assert((j + 1) == NCH(ch));
3507 break;
3508 }
3509 s = ast_for_stmt(c, CHILD(ch, j));
3510 if (!s)
3511 return NULL;
3512 asdl_seq_SET(seq, pos++, s);
3513 }
3514 }
3515 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003516 }
3517 assert(pos == seq->size);
3518 return seq;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003519}
3520
3521static stmt_ty
3522ast_for_if_stmt(struct compiling *c, const node *n)
3523{
3524 /* if_stmt: 'if' test ':' suite ('elif' test ':' suite)*
3525 ['else' ':' suite]
3526 */
3527 char *s;
3528
3529 REQ(n, if_stmt);
3530
3531 if (NCH(n) == 4) {
3532 expr_ty expression;
3533 asdl_seq *suite_seq;
3534
3535 expression = ast_for_expr(c, CHILD(n, 1));
3536 if (!expression)
3537 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 suite_seq = ast_for_suite(c, CHILD(n, 3));
Neal Norwitz84456bd2005-12-18 03:16:20 +00003539 if (!suite_seq)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003540 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541
Guido van Rossumd8faa362007-04-27 19:54:29 +00003542 return If(expression, suite_seq, NULL, LINENO(n), n->n_col_offset,
3543 c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003544 }
Neal Norwitz84456bd2005-12-18 03:16:20 +00003545
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546 s = STR(CHILD(n, 4));
3547 /* s[2], the third character in the string, will be
3548 's' for el_s_e, or
3549 'i' for el_i_f
3550 */
3551 if (s[2] == 's') {
3552 expr_ty expression;
3553 asdl_seq *seq1, *seq2;
3554
3555 expression = ast_for_expr(c, CHILD(n, 1));
3556 if (!expression)
3557 return NULL;
3558 seq1 = ast_for_suite(c, CHILD(n, 3));
Neal Norwitz84456bd2005-12-18 03:16:20 +00003559 if (!seq1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003560 return NULL;
3561 seq2 = ast_for_suite(c, CHILD(n, 6));
Neal Norwitz84456bd2005-12-18 03:16:20 +00003562 if (!seq2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563 return NULL;
3564
Guido van Rossumd8faa362007-04-27 19:54:29 +00003565 return If(expression, seq1, seq2, LINENO(n), n->n_col_offset,
3566 c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003567 }
3568 else if (s[2] == 'i') {
Thomas Wouters89f507f2006-12-13 04:49:30 +00003569 int i, n_elif, has_else = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003570 expr_ty expression;
3571 asdl_seq *suite_seq;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003572 asdl_seq *orelse = NULL;
3573 n_elif = NCH(n) - 4;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003574 /* must reference the child n_elif+1 since 'else' token is third,
3575 not fourth, child from the end. */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003576 if (TYPE(CHILD(n, (n_elif + 1))) == NAME
3577 && STR(CHILD(n, (n_elif + 1)))[2] == 's') {
3578 has_else = 1;
3579 n_elif -= 3;
3580 }
3581 n_elif /= 4;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003582
Thomas Wouters89f507f2006-12-13 04:49:30 +00003583 if (has_else) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003584 asdl_seq *suite_seq2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003585
Antoine Pitroud01d396e2013-10-12 22:52:43 +02003586 orelse = _Py_asdl_seq_new(1, c->c_arena);
Thomas Wouters89f507f2006-12-13 04:49:30 +00003587 if (!orelse)
3588 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003589 expression = ast_for_expr(c, CHILD(n, NCH(n) - 6));
Neal Norwitz84456bd2005-12-18 03:16:20 +00003590 if (!expression)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003591 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003592 suite_seq = ast_for_suite(c, CHILD(n, NCH(n) - 4));
3593 if (!suite_seq)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003594 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003595 suite_seq2 = ast_for_suite(c, CHILD(n, NCH(n) - 1));
3596 if (!suite_seq2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003597 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 asdl_seq_SET(orelse, 0,
3600 If(expression, suite_seq, suite_seq2,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003601 LINENO(CHILD(n, NCH(n) - 6)),
3602 CHILD(n, NCH(n) - 6)->n_col_offset,
3603 c->c_arena));
Thomas Wouters89f507f2006-12-13 04:49:30 +00003604 /* the just-created orelse handled the last elif */
3605 n_elif--;
3606 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003607
Thomas Wouters89f507f2006-12-13 04:49:30 +00003608 for (i = 0; i < n_elif; i++) {
3609 int off = 5 + (n_elif - i - 1) * 4;
Antoine Pitroud01d396e2013-10-12 22:52:43 +02003610 asdl_seq *newobj = _Py_asdl_seq_new(1, c->c_arena);
Thomas Wouters89f507f2006-12-13 04:49:30 +00003611 if (!newobj)
3612 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613 expression = ast_for_expr(c, CHILD(n, off));
Neal Norwitz84456bd2005-12-18 03:16:20 +00003614 if (!expression)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003615 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003616 suite_seq = ast_for_suite(c, CHILD(n, off + 2));
Neal Norwitz84456bd2005-12-18 03:16:20 +00003617 if (!suite_seq)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003618 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003619
Thomas Wouters89f507f2006-12-13 04:49:30 +00003620 asdl_seq_SET(newobj, 0,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621 If(expression, suite_seq, orelse,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003622 LINENO(CHILD(n, off)),
3623 CHILD(n, off)->n_col_offset, c->c_arena));
Thomas Wouters89f507f2006-12-13 04:49:30 +00003624 orelse = newobj;
3625 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00003626 expression = ast_for_expr(c, CHILD(n, 1));
3627 if (!expression)
3628 return NULL;
3629 suite_seq = ast_for_suite(c, CHILD(n, 3));
3630 if (!suite_seq)
3631 return NULL;
3632 return If(expression, suite_seq, orelse,
3633 LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003634 }
Neal Norwitz84456bd2005-12-18 03:16:20 +00003635
3636 PyErr_Format(PyExc_SystemError,
3637 "unexpected token in 'if' statement: %s", s);
3638 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003639}
3640
3641static stmt_ty
3642ast_for_while_stmt(struct compiling *c, const node *n)
3643{
3644 /* while_stmt: 'while' test ':' suite ['else' ':' suite] */
3645 REQ(n, while_stmt);
3646
3647 if (NCH(n) == 4) {
3648 expr_ty expression;
3649 asdl_seq *suite_seq;
3650
3651 expression = ast_for_expr(c, CHILD(n, 1));
3652 if (!expression)
3653 return NULL;
3654 suite_seq = ast_for_suite(c, CHILD(n, 3));
Neal Norwitz84456bd2005-12-18 03:16:20 +00003655 if (!suite_seq)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003656 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003657 return While(expression, suite_seq, NULL, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003658 }
3659 else if (NCH(n) == 7) {
3660 expr_ty expression;
3661 asdl_seq *seq1, *seq2;
3662
3663 expression = ast_for_expr(c, CHILD(n, 1));
3664 if (!expression)
3665 return NULL;
3666 seq1 = ast_for_suite(c, CHILD(n, 3));
Neal Norwitz84456bd2005-12-18 03:16:20 +00003667 if (!seq1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003668 return NULL;
3669 seq2 = ast_for_suite(c, CHILD(n, 6));
Neal Norwitz84456bd2005-12-18 03:16:20 +00003670 if (!seq2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003671 return NULL;
3672
Thomas Wouters89f507f2006-12-13 04:49:30 +00003673 return While(expression, seq1, seq2, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003674 }
Neal Norwitz84456bd2005-12-18 03:16:20 +00003675
3676 PyErr_Format(PyExc_SystemError,
3677 "wrong number of tokens for 'while' statement: %d",
3678 NCH(n));
3679 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003680}
3681
3682static stmt_ty
guoci90fc8982018-09-11 17:45:45 -04003683ast_for_for_stmt(struct compiling *c, const node *n0, bool is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003684{
guoci90fc8982018-09-11 17:45:45 -04003685 const node * const n = is_async ? CHILD(n0, 1) : n0;
Neal Norwitz84456bd2005-12-18 03:16:20 +00003686 asdl_seq *_target, *seq = NULL, *suite_seq;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003687 expr_ty expression;
Benjamin Peterson2e4b0e12009-09-11 22:36:20 +00003688 expr_ty target, first;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003689 const node *node_target;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003690 /* for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] */
3691 REQ(n, for_stmt);
3692
3693 if (NCH(n) == 9) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00003694 seq = ast_for_suite(c, CHILD(n, 8));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003695 if (!seq)
3696 return NULL;
3697 }
3698
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003699 node_target = CHILD(n, 1);
3700 _target = ast_for_exprlist(c, node_target, Store);
Neal Norwitz84456bd2005-12-18 03:16:20 +00003701 if (!_target)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003702 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003703 /* Check the # of children rather than the length of _target, since
3704 for x, in ... has 1 element in _target, but still requires a Tuple. */
Benjamin Peterson2e4b0e12009-09-11 22:36:20 +00003705 first = (expr_ty)asdl_seq_GET(_target, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003706 if (NCH(node_target) == 1)
Benjamin Peterson2e4b0e12009-09-11 22:36:20 +00003707 target = first;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003708 else
Benjamin Peterson2e4b0e12009-09-11 22:36:20 +00003709 target = Tuple(_target, Store, first->lineno, first->col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003710
Neil Schemenauerc5dd10a2005-10-25 07:54:54 +00003711 expression = ast_for_testlist(c, CHILD(n, 3));
Neal Norwitz84456bd2005-12-18 03:16:20 +00003712 if (!expression)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003713 return NULL;
3714 suite_seq = ast_for_suite(c, CHILD(n, 5));
Neal Norwitz84456bd2005-12-18 03:16:20 +00003715 if (!suite_seq)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003716 return NULL;
3717
Yury Selivanov75445082015-05-11 22:57:16 -04003718 if (is_async)
3719 return AsyncFor(target, expression, suite_seq, seq,
Benjamin Petersond13e59c2018-09-11 15:29:57 -07003720 LINENO(n0), n0->n_col_offset,
Yury Selivanov75445082015-05-11 22:57:16 -04003721 c->c_arena);
3722 else
3723 return For(target, expression, suite_seq, seq,
3724 LINENO(n), n->n_col_offset,
3725 c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003726}
3727
3728static excepthandler_ty
3729ast_for_except_clause(struct compiling *c, const node *exc, node *body)
3730{
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003731 /* except_clause: 'except' [test ['as' test]] */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003732 REQ(exc, except_clause);
3733 REQ(body, suite);
3734
3735 if (NCH(exc) == 1) {
3736 asdl_seq *suite_seq = ast_for_suite(c, body);
3737 if (!suite_seq)
3738 return NULL;
3739
Neal Norwitzad74aa82008-03-31 05:14:30 +00003740 return ExceptHandler(NULL, NULL, suite_seq, LINENO(exc),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003741 exc->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003742 }
3743 else if (NCH(exc) == 2) {
3744 expr_ty expression;
3745 asdl_seq *suite_seq;
3746
3747 expression = ast_for_expr(c, CHILD(exc, 1));
3748 if (!expression)
3749 return NULL;
3750 suite_seq = ast_for_suite(c, body);
Neal Norwitz84456bd2005-12-18 03:16:20 +00003751 if (!suite_seq)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003752 return NULL;
3753
Neal Norwitzad74aa82008-03-31 05:14:30 +00003754 return ExceptHandler(expression, NULL, suite_seq, LINENO(exc),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003755 exc->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003756 }
3757 else if (NCH(exc) == 4) {
3758 asdl_seq *suite_seq;
3759 expr_ty expression;
Guido van Rossum16be03e2007-01-10 18:51:35 +00003760 identifier e = NEW_IDENTIFIER(CHILD(exc, 3));
Thomas Wouters89f507f2006-12-13 04:49:30 +00003761 if (!e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003762 return NULL;
Benjamin Petersonbd0df502012-09-02 15:04:51 -04003763 if (forbidden_name(c, e, CHILD(exc, 3), 0))
Benjamin Peterson70f52762009-06-28 23:32:44 +00003764 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003765 expression = ast_for_expr(c, CHILD(exc, 1));
Neal Norwitz84456bd2005-12-18 03:16:20 +00003766 if (!expression)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003767 return NULL;
3768 suite_seq = ast_for_suite(c, body);
Neal Norwitz84456bd2005-12-18 03:16:20 +00003769 if (!suite_seq)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003770 return NULL;
3771
Neal Norwitzad74aa82008-03-31 05:14:30 +00003772 return ExceptHandler(expression, e, suite_seq, LINENO(exc),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003773 exc->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003774 }
Neal Norwitz84456bd2005-12-18 03:16:20 +00003775
3776 PyErr_Format(PyExc_SystemError,
3777 "wrong number of children for 'except' clause: %d",
3778 NCH(exc));
3779 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003780}
3781
3782static stmt_ty
3783ast_for_try_stmt(struct compiling *c, const node *n)
3784{
Neal Norwitzf599f422005-12-17 21:33:47 +00003785 const int nch = NCH(n);
3786 int n_except = (nch - 3)/3;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003787 asdl_seq *body, *handlers = NULL, *orelse = NULL, *finally = NULL;
Neal Norwitzf599f422005-12-17 21:33:47 +00003788
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003789 REQ(n, try_stmt);
3790
Neal Norwitzf599f422005-12-17 21:33:47 +00003791 body = ast_for_suite(c, CHILD(n, 2));
3792 if (body == NULL)
3793 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003794
Neal Norwitzf599f422005-12-17 21:33:47 +00003795 if (TYPE(CHILD(n, nch - 3)) == NAME) {
3796 if (strcmp(STR(CHILD(n, nch - 3)), "finally") == 0) {
3797 if (nch >= 9 && TYPE(CHILD(n, nch - 6)) == NAME) {
3798 /* we can assume it's an "else",
3799 because nch >= 9 for try-else-finally and
3800 it would otherwise have a type of except_clause */
3801 orelse = ast_for_suite(c, CHILD(n, nch - 4));
3802 if (orelse == NULL)
3803 return NULL;
3804 n_except--;
3805 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003806
Neal Norwitzf599f422005-12-17 21:33:47 +00003807 finally = ast_for_suite(c, CHILD(n, nch - 1));
3808 if (finally == NULL)
3809 return NULL;
3810 n_except--;
3811 }
3812 else {
3813 /* we can assume it's an "else",
3814 otherwise it would have a type of except_clause */
3815 orelse = ast_for_suite(c, CHILD(n, nch - 1));
3816 if (orelse == NULL)
3817 return NULL;
3818 n_except--;
3819 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003820 }
Neal Norwitzf599f422005-12-17 21:33:47 +00003821 else if (TYPE(CHILD(n, nch - 3)) != except_clause) {
Benjamin Petersonbd0df502012-09-02 15:04:51 -04003822 ast_error(c, n, "malformed 'try' statement");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003823 return NULL;
3824 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825
Neal Norwitzf599f422005-12-17 21:33:47 +00003826 if (n_except > 0) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00003827 int i;
Neal Norwitzf599f422005-12-17 21:33:47 +00003828 /* process except statements to create a try ... except */
Antoine Pitroud01d396e2013-10-12 22:52:43 +02003829 handlers = _Py_asdl_seq_new(n_except, c->c_arena);
Neal Norwitzf599f422005-12-17 21:33:47 +00003830 if (handlers == NULL)
3831 return NULL;
3832
3833 for (i = 0; i < n_except; i++) {
3834 excepthandler_ty e = ast_for_except_clause(c, CHILD(n, 3 + i * 3),
3835 CHILD(n, 5 + i * 3));
3836 if (!e)
3837 return NULL;
3838 asdl_seq_SET(handlers, i, e);
3839 }
Neal Norwitzf599f422005-12-17 21:33:47 +00003840 }
3841
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003842 assert(finally != NULL || asdl_seq_LEN(handlers));
3843 return Try(body, handlers, orelse, finally, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003844}
3845
Georg Brandl0c315622009-05-25 21:10:36 +00003846/* with_item: test ['as' expr] */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003847static withitem_ty
3848ast_for_with_item(struct compiling *c, const node *n)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003849{
3850 expr_ty context_expr, optional_vars = NULL;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003851
Georg Brandl0c315622009-05-25 21:10:36 +00003852 REQ(n, with_item);
3853 context_expr = ast_for_expr(c, CHILD(n, 0));
Amaury Forgeot d'Arc92dc80a2010-08-19 17:43:15 +00003854 if (!context_expr)
3855 return NULL;
Georg Brandl0c315622009-05-25 21:10:36 +00003856 if (NCH(n) == 3) {
3857 optional_vars = ast_for_expr(c, CHILD(n, 2));
Guido van Rossumc2e20742006-02-27 22:32:47 +00003858
3859 if (!optional_vars) {
3860 return NULL;
3861 }
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003862 if (!set_context(c, optional_vars, Store, n)) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00003863 return NULL;
3864 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003865 }
3866
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003867 return withitem(context_expr, optional_vars, c->c_arena);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003868}
3869
Georg Brandl0c315622009-05-25 21:10:36 +00003870/* with_stmt: 'with' with_item (',' with_item)* ':' suite */
3871static stmt_ty
guoci90fc8982018-09-11 17:45:45 -04003872ast_for_with_stmt(struct compiling *c, const node *n0, bool is_async)
Georg Brandl0c315622009-05-25 21:10:36 +00003873{
guoci90fc8982018-09-11 17:45:45 -04003874 const node * const n = is_async ? CHILD(n0, 1) : n0;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003875 int i, n_items;
3876 asdl_seq *items, *body;
Georg Brandl0c315622009-05-25 21:10:36 +00003877
3878 REQ(n, with_stmt);
3879
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003880 n_items = (NCH(n) - 2) / 2;
Antoine Pitroud01d396e2013-10-12 22:52:43 +02003881 items = _Py_asdl_seq_new(n_items, c->c_arena);
Stefan Krah28a2ad52012-08-20 16:07:38 +02003882 if (!items)
3883 return NULL;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003884 for (i = 1; i < NCH(n) - 2; i += 2) {
3885 withitem_ty item = ast_for_with_item(c, CHILD(n, i));
3886 if (!item)
Georg Brandl0c315622009-05-25 21:10:36 +00003887 return NULL;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003888 asdl_seq_SET(items, (i - 1) / 2, item);
Georg Brandl0c315622009-05-25 21:10:36 +00003889 }
3890
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003891 body = ast_for_suite(c, CHILD(n, NCH(n) - 1));
3892 if (!body)
3893 return NULL;
3894
Yury Selivanov75445082015-05-11 22:57:16 -04003895 if (is_async)
Benjamin Petersond13e59c2018-09-11 15:29:57 -07003896 return AsyncWith(items, body, LINENO(n0), n0->n_col_offset, c->c_arena);
Yury Selivanov75445082015-05-11 22:57:16 -04003897 else
3898 return With(items, body, LINENO(n), n->n_col_offset, c->c_arena);
Georg Brandl0c315622009-05-25 21:10:36 +00003899}
3900
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003901static stmt_ty
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003902ast_for_classdef(struct compiling *c, const node *n, asdl_seq *decorator_seq)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003903{
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003904 /* classdef: 'class' NAME ['(' arglist ')'] ':' suite */
Benjamin Peterson30760062008-11-25 04:02:28 +00003905 PyObject *classname;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003906 asdl_seq *s;
Benjamin Petersond951e7b2008-11-25 22:19:53 +00003907 expr_ty call;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003908
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003909 REQ(n, classdef);
3910
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003911 if (NCH(n) == 4) { /* class NAME ':' suite */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03003912 s = ast_for_suite(c, CHILD(n, 3));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003913 if (!s)
3914 return NULL;
Benjamin Peterson30760062008-11-25 04:02:28 +00003915 classname = NEW_IDENTIFIER(CHILD(n, 1));
3916 if (!classname)
3917 return NULL;
Benjamin Petersonbd0df502012-09-02 15:04:51 -04003918 if (forbidden_name(c, classname, CHILD(n, 3), 0))
Benjamin Peterson70f52762009-06-28 23:32:44 +00003919 return NULL;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03003920 return ClassDef(classname, NULL, NULL, s, decorator_seq,
INADA Naokicb41b272017-02-23 00:31:59 +09003921 LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003922 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003923
3924 if (TYPE(CHILD(n, 3)) == RPAR) { /* class NAME '(' ')' ':' suite */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03003925 s = ast_for_suite(c, CHILD(n, 5));
Thomas Wouters89f507f2006-12-13 04:49:30 +00003926 if (!s)
Benjamin Peterson30760062008-11-25 04:02:28 +00003927 return NULL;
3928 classname = NEW_IDENTIFIER(CHILD(n, 1));
3929 if (!classname)
3930 return NULL;
Benjamin Petersonbd0df502012-09-02 15:04:51 -04003931 if (forbidden_name(c, classname, CHILD(n, 3), 0))
Benjamin Peterson70f52762009-06-28 23:32:44 +00003932 return NULL;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03003933 return ClassDef(classname, NULL, NULL, s, decorator_seq,
INADA Naokicb41b272017-02-23 00:31:59 +09003934 LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003935 }
3936
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003937 /* class NAME '(' arglist ')' ':' suite */
3938 /* build up a fake Call node so we can extract its pieces */
Benjamin Petersond951e7b2008-11-25 22:19:53 +00003939 {
3940 PyObject *dummy_name;
3941 expr_ty dummy;
3942 dummy_name = NEW_IDENTIFIER(CHILD(n, 1));
3943 if (!dummy_name)
3944 return NULL;
3945 dummy = Name(dummy_name, Load, LINENO(n), n->n_col_offset, c->c_arena);
Serhiy Storchakaddbce132017-11-15 17:39:37 +02003946 call = ast_for_call(c, CHILD(n, 3), dummy, false);
Benjamin Petersond951e7b2008-11-25 22:19:53 +00003947 if (!call)
3948 return NULL;
3949 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03003950 s = ast_for_suite(c, CHILD(n, 6));
Neal Norwitz84456bd2005-12-18 03:16:20 +00003951 if (!s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003952 return NULL;
Benjamin Peterson30760062008-11-25 04:02:28 +00003953 classname = NEW_IDENTIFIER(CHILD(n, 1));
3954 if (!classname)
3955 return NULL;
Benjamin Petersonbd0df502012-09-02 15:04:51 -04003956 if (forbidden_name(c, classname, CHILD(n, 1), 0))
Benjamin Peterson70f52762009-06-28 23:32:44 +00003957 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003958
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003959 return ClassDef(classname, call->v.Call.args, call->v.Call.keywords, s,
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03003960 decorator_seq, LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003961}
3962
3963static stmt_ty
3964ast_for_stmt(struct compiling *c, const node *n)
3965{
3966 if (TYPE(n) == stmt) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00003967 assert(NCH(n) == 1);
3968 n = CHILD(n, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003969 }
3970 if (TYPE(n) == simple_stmt) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00003971 assert(num_stmts(n) == 1);
3972 n = CHILD(n, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003973 }
3974 if (TYPE(n) == small_stmt) {
Neal Norwitzc1505362006-12-28 06:47:50 +00003975 n = CHILD(n, 0);
Jeremy Hylton81e95022007-02-27 06:50:52 +00003976 /* small_stmt: expr_stmt | del_stmt | pass_stmt | flow_stmt
3977 | import_stmt | global_stmt | nonlocal_stmt | assert_stmt
Thomas Wouters89f507f2006-12-13 04:49:30 +00003978 */
3979 switch (TYPE(n)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003980 case expr_stmt:
3981 return ast_for_expr_stmt(c, n);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003982 case del_stmt:
3983 return ast_for_del_stmt(c, n);
3984 case pass_stmt:
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003985 return Pass(LINENO(n), n->n_col_offset, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003986 case flow_stmt:
3987 return ast_for_flow_stmt(c, n);
3988 case import_stmt:
3989 return ast_for_import_stmt(c, n);
3990 case global_stmt:
3991 return ast_for_global_stmt(c, n);
Jeremy Hylton81e95022007-02-27 06:50:52 +00003992 case nonlocal_stmt:
3993 return ast_for_nonlocal_stmt(c, n);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003994 case assert_stmt:
3995 return ast_for_assert_stmt(c, n);
3996 default:
Neal Norwitz79792652005-11-14 04:25:03 +00003997 PyErr_Format(PyExc_SystemError,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003998 "unhandled small_stmt: TYPE=%d NCH=%d\n",
3999 TYPE(n), NCH(n));
4000 return NULL;
4001 }
4002 }
4003 else {
4004 /* compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt
Yury Selivanov75445082015-05-11 22:57:16 -04004005 | funcdef | classdef | decorated | async_stmt
Thomas Wouters89f507f2006-12-13 04:49:30 +00004006 */
4007 node *ch = CHILD(n, 0);
4008 REQ(n, compound_stmt);
4009 switch (TYPE(ch)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004010 case if_stmt:
4011 return ast_for_if_stmt(c, ch);
4012 case while_stmt:
4013 return ast_for_while_stmt(c, ch);
4014 case for_stmt:
Yury Selivanov75445082015-05-11 22:57:16 -04004015 return ast_for_for_stmt(c, ch, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004016 case try_stmt:
4017 return ast_for_try_stmt(c, ch);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004018 case with_stmt:
Yury Selivanov75445082015-05-11 22:57:16 -04004019 return ast_for_with_stmt(c, ch, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004020 case funcdef:
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004021 return ast_for_funcdef(c, ch, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004022 case classdef:
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004023 return ast_for_classdef(c, ch, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004024 case decorated:
4025 return ast_for_decorated(c, ch);
Yury Selivanov75445082015-05-11 22:57:16 -04004026 case async_stmt:
4027 return ast_for_async_stmt(c, ch);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004028 default:
Neal Norwitz79792652005-11-14 04:25:03 +00004029 PyErr_Format(PyExc_SystemError,
Jelle Zijlstra898ff922018-05-13 17:04:53 -04004030 "unhandled compound_stmt: TYPE=%d NCH=%d\n",
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004031 TYPE(n), NCH(n));
4032 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004033 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004034 }
4035}
4036
4037static PyObject *
Brett Cannona721aba2016-09-09 14:57:09 -07004038parsenumber_raw(struct compiling *c, const char *s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004039{
Guido van Rossumd8faa362007-04-27 19:54:29 +00004040 const char *end;
4041 long x;
4042 double dx;
Christian Heimes81ee3ef2008-05-04 22:42:01 +00004043 Py_complex compl;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004044 int imflag;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004045
Mark Dickinsond3c827b2008-12-05 18:10:46 +00004046 assert(s != NULL);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004047 errno = 0;
4048 end = s + strlen(s) - 1;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004049 imflag = *end == 'j' || *end == 'J';
Guido van Rossumd8faa362007-04-27 19:54:29 +00004050 if (s[0] == '0') {
Serhiy Storchakac6792272013-10-19 21:03:34 +03004051 x = (long) PyOS_strtoul(s, (char **)&end, 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004052 if (x < 0 && errno == 0) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03004053 return PyLong_FromString(s, (char **)0, 0);
Thomas Wouters89f507f2006-12-13 04:49:30 +00004054 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00004055 }
4056 else
Serhiy Storchakac6792272013-10-19 21:03:34 +03004057 x = PyOS_strtol(s, (char **)&end, 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004058 if (*end == '\0') {
4059 if (errno != 0)
Serhiy Storchakac6792272013-10-19 21:03:34 +03004060 return PyLong_FromString(s, (char **)0, 0);
Christian Heimes217cfd12007-12-02 14:31:20 +00004061 return PyLong_FromLong(x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004062 }
4063 /* XXX Huge floats may silently fail */
Guido van Rossumd8faa362007-04-27 19:54:29 +00004064 if (imflag) {
Christian Heimes81ee3ef2008-05-04 22:42:01 +00004065 compl.real = 0.;
Mark Dickinson725bfd82009-05-03 20:33:40 +00004066 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
4067 if (compl.imag == -1.0 && PyErr_Occurred())
4068 return NULL;
4069 return PyComplex_FromCComplex(compl);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004070 }
4071 else
Guido van Rossumd8faa362007-04-27 19:54:29 +00004072 {
Mark Dickinson725bfd82009-05-03 20:33:40 +00004073 dx = PyOS_string_to_double(s, NULL, NULL);
4074 if (dx == -1.0 && PyErr_Occurred())
4075 return NULL;
4076 return PyFloat_FromDouble(dx);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004077 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004078}
4079
4080static PyObject *
Brett Cannona721aba2016-09-09 14:57:09 -07004081parsenumber(struct compiling *c, const char *s)
4082{
4083 char *dup, *end;
4084 PyObject *res = NULL;
4085
4086 assert(s != NULL);
4087
4088 if (strchr(s, '_') == NULL) {
4089 return parsenumber_raw(c, s);
4090 }
4091 /* Create a duplicate without underscores. */
4092 dup = PyMem_Malloc(strlen(s) + 1);
4093 end = dup;
4094 for (; *s; s++) {
4095 if (*s != '_') {
4096 *end++ = *s;
4097 }
4098 }
4099 *end = '\0';
4100 res = parsenumber_raw(c, dup);
4101 PyMem_Free(dup);
4102 return res;
4103}
4104
4105static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004106decode_utf8(struct compiling *c, const char **sPtr, const char *end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004107{
Serhiy Storchakac6792272013-10-19 21:03:34 +03004108 const char *s, *t;
4109 t = s = *sPtr;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004110 /* while (s < end && *s != '\\') s++; */ /* inefficient for u".." */
4111 while (s < end && (*s & 0x80)) s++;
4112 *sPtr = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004113 return PyUnicode_DecodeUTF8(t, s - t, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004114}
4115
Eric V. Smith56466482016-10-31 14:46:26 -04004116static int
4117warn_invalid_escape_sequence(struct compiling *c, const node *n,
Serhiy Storchaka56cb4652017-10-20 17:08:15 +03004118 unsigned char first_invalid_escape_char)
Eric V. Smith56466482016-10-31 14:46:26 -04004119{
4120 PyObject *msg = PyUnicode_FromFormat("invalid escape sequence \\%c",
4121 first_invalid_escape_char);
4122 if (msg == NULL) {
4123 return -1;
4124 }
Serhiy Storchaka65439122018-10-19 17:42:06 +03004125 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
Eric V. Smith56466482016-10-31 14:46:26 -04004126 c->c_filename, LINENO(n),
Serhiy Storchakaa5618622017-12-01 08:40:23 +02004127 NULL, NULL) < 0)
Eric V. Smith56466482016-10-31 14:46:26 -04004128 {
Serhiy Storchaka65439122018-10-19 17:42:06 +03004129 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchakaa5618622017-12-01 08:40:23 +02004130 const char *s;
Victor Stinnerf9cca362016-11-15 09:12:10 +01004131
Serhiy Storchaka65439122018-10-19 17:42:06 +03004132 /* Replace the SyntaxWarning exception with a SyntaxError
Serhiy Storchakaa5618622017-12-01 08:40:23 +02004133 to get a more accurate error report */
4134 PyErr_Clear();
Victor Stinnerf9cca362016-11-15 09:12:10 +01004135
Serhiy Storchakaa5618622017-12-01 08:40:23 +02004136 s = PyUnicode_AsUTF8(msg);
4137 if (s != NULL) {
4138 ast_error(c, n, s);
4139 }
Eric V. Smith56466482016-10-31 14:46:26 -04004140 }
4141 Py_DECREF(msg);
4142 return -1;
4143 }
4144 Py_DECREF(msg);
4145 return 0;
4146}
4147
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004148static PyObject *
Eric V. Smith56466482016-10-31 14:46:26 -04004149decode_unicode_with_escapes(struct compiling *c, const node *n, const char *s,
4150 size_t len)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004151{
Guido van Rossumd8faa362007-04-27 19:54:29 +00004152 PyObject *v, *u;
4153 char *buf;
4154 char *p;
4155 const char *end;
Guido van Rossum29fd7122007-11-12 01:13:56 +00004156
Benjamin Peterson202803a2016-02-25 22:34:45 -08004157 /* check for integer overflow */
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07004158 if (len > SIZE_MAX / 6)
Benjamin Peterson202803a2016-02-25 22:34:45 -08004159 return NULL;
4160 /* "Ă€" (2 bytes) may become "\U000000E4" (10 bytes), or 1:5
4161 "\Ă€" (3 bytes) may become "\u005c\U000000E4" (16 bytes), or ~1:6 */
4162 u = PyBytes_FromStringAndSize((char *)NULL, len * 6);
4163 if (u == NULL)
4164 return NULL;
4165 p = buf = PyBytes_AsString(u);
4166 end = s + len;
4167 while (s < end) {
4168 if (*s == '\\') {
4169 *p++ = *s++;
Serhiy Storchaka0cd7a3f2017-05-25 13:33:55 +03004170 if (s >= end || *s & 0x80) {
Benjamin Peterson202803a2016-02-25 22:34:45 -08004171 strcpy(p, "u005c");
4172 p += 5;
Serhiy Storchaka0cd7a3f2017-05-25 13:33:55 +03004173 if (s >= end)
4174 break;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004175 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00004176 }
Benjamin Peterson202803a2016-02-25 22:34:45 -08004177 if (*s & 0x80) { /* XXX inefficient */
4178 PyObject *w;
4179 int kind;
4180 void *data;
4181 Py_ssize_t len, i;
4182 w = decode_utf8(c, &s, end);
4183 if (w == NULL) {
4184 Py_DECREF(u);
4185 return NULL;
4186 }
4187 kind = PyUnicode_KIND(w);
4188 data = PyUnicode_DATA(w);
4189 len = PyUnicode_GET_LENGTH(w);
4190 for (i = 0; i < len; i++) {
4191 Py_UCS4 chr = PyUnicode_READ(kind, data, i);
4192 sprintf(p, "\\U%08x", chr);
4193 p += 10;
4194 }
4195 /* Should be impossible to overflow */
Serhiy Storchakafff9a312017-03-21 08:53:25 +02004196 assert(p - buf <= PyBytes_GET_SIZE(u));
Benjamin Peterson202803a2016-02-25 22:34:45 -08004197 Py_DECREF(w);
4198 } else {
4199 *p++ = *s++;
4200 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00004201 }
Benjamin Peterson202803a2016-02-25 22:34:45 -08004202 len = p - buf;
4203 s = buf;
4204
Eric V. Smith56466482016-10-31 14:46:26 -04004205 const char *first_invalid_escape;
4206 v = _PyUnicode_DecodeUnicodeEscape(s, len, NULL, &first_invalid_escape);
4207
4208 if (v != NULL && first_invalid_escape != NULL) {
4209 if (warn_invalid_escape_sequence(c, n, *first_invalid_escape) < 0) {
4210 /* We have not decref u before because first_invalid_escape points
4211 inside u. */
4212 Py_XDECREF(u);
4213 Py_DECREF(v);
4214 return NULL;
4215 }
4216 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00004217 Py_XDECREF(u);
4218 return v;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004219}
4220
Eric V. Smith56466482016-10-31 14:46:26 -04004221static PyObject *
4222decode_bytes_with_escapes(struct compiling *c, const node *n, const char *s,
4223 size_t len)
4224{
4225 const char *first_invalid_escape;
4226 PyObject *result = _PyBytes_DecodeEscape(s, len, NULL, 0, NULL,
4227 &first_invalid_escape);
4228 if (result == NULL)
4229 return NULL;
4230
4231 if (first_invalid_escape != NULL) {
4232 if (warn_invalid_escape_sequence(c, n, *first_invalid_escape) < 0) {
4233 Py_DECREF(result);
4234 return NULL;
4235 }
4236 }
4237 return result;
4238}
4239
Ɓukasz Langae7c566c2017-09-06 17:27:58 -07004240/* Shift locations for the given node and all its children by adding `lineno`
4241 and `col_offset` to existing locations. */
4242static void fstring_shift_node_locations(node *n, int lineno, int col_offset)
4243{
4244 n->n_col_offset = n->n_col_offset + col_offset;
4245 for (int i = 0; i < NCH(n); ++i) {
4246 if (n->n_lineno && n->n_lineno < CHILD(n, i)->n_lineno) {
4247 /* Shifting column offsets unnecessary if there's been newlines. */
4248 col_offset = 0;
4249 }
4250 fstring_shift_node_locations(CHILD(n, i), lineno, col_offset);
4251 }
4252 n->n_lineno = n->n_lineno + lineno;
4253}
4254
4255/* Fix locations for the given node and its children.
4256
4257 `parent` is the enclosing node.
4258 `n` is the node which locations are going to be fixed relative to parent.
luzpaza5293b42017-11-05 07:37:50 -06004259 `expr_str` is the child node's string representation, including braces.
Ɓukasz Langae7c566c2017-09-06 17:27:58 -07004260*/
4261static void
4262fstring_fix_node_location(const node *parent, node *n, char *expr_str)
4263{
4264 char *substr = NULL;
4265 char *start;
4266 int lines = LINENO(parent) - 1;
4267 int cols = parent->n_col_offset;
4268 /* Find the full fstring to fix location information in `n`. */
4269 while (parent && parent->n_type != STRING)
4270 parent = parent->n_child;
4271 if (parent && parent->n_str) {
4272 substr = strstr(parent->n_str, expr_str);
4273 if (substr) {
4274 start = substr;
4275 while (start > parent->n_str) {
4276 if (start[0] == '\n')
4277 break;
4278 start--;
4279 }
Victor Stinnerfb7e7992018-04-30 23:51:02 +02004280 cols += (int)(substr - start);
Ɓukasz Langae7c566c2017-09-06 17:27:58 -07004281 /* Fix lineno in mulitline strings. */
4282 while ((substr = strchr(substr + 1, '\n')))
4283 lines--;
4284 }
4285 }
4286 fstring_shift_node_locations(n, lines, cols);
4287}
4288
Eric V. Smith451d0e32016-09-09 21:56:20 -04004289/* Compile this expression in to an expr_ty. Add parens around the
4290 expression, in order to allow leading spaces in the expression. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004291static expr_ty
Eric V. Smith451d0e32016-09-09 21:56:20 -04004292fstring_compile_expr(const char *expr_start, const char *expr_end,
4293 struct compiling *c, const node *n)
Eric V. Smith1e5fcc32015-09-24 08:52:04 -04004294
Eric V. Smith235a6f02015-09-19 14:51:32 -04004295{
4296 PyCompilerFlags cf;
Ɓukasz Langae7c566c2017-09-06 17:27:58 -07004297 node *mod_n;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004298 mod_ty mod;
Eric V. Smith451d0e32016-09-09 21:56:20 -04004299 char *str;
Eric V. Smith451d0e32016-09-09 21:56:20 -04004300 Py_ssize_t len;
Serhiy Storchaka2e9cd582017-06-08 23:43:54 +03004301 const char *s;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004302
Eric V. Smith1d44c412015-09-23 07:49:00 -04004303 assert(expr_end >= expr_start);
Eric V. Smith451d0e32016-09-09 21:56:20 -04004304 assert(*(expr_start-1) == '{');
4305 assert(*expr_end == '}' || *expr_end == '!' || *expr_end == ':');
Eric V. Smith1d44c412015-09-23 07:49:00 -04004306
Ɓukasz Langae7c566c2017-09-06 17:27:58 -07004307 /* If the substring is all whitespace, it's an error. We need to catch this
4308 here, and not when we call PyParser_SimpleParseStringFlagsFilename,
4309 because turning the expression '' in to '()' would go from being invalid
4310 to valid. */
Serhiy Storchaka2e9cd582017-06-08 23:43:54 +03004311 for (s = expr_start; s != expr_end; s++) {
4312 char c = *s;
4313 /* The Python parser ignores only the following whitespace
4314 characters (\r already is converted to \n). */
4315 if (!(c == ' ' || c == '\t' || c == '\n' || c == '\f')) {
Eric V. Smith235a6f02015-09-19 14:51:32 -04004316 break;
4317 }
4318 }
Serhiy Storchaka2e9cd582017-06-08 23:43:54 +03004319 if (s == expr_end) {
Eric V. Smith1e5fcc32015-09-24 08:52:04 -04004320 ast_error(c, n, "f-string: empty expression not allowed");
Eric V. Smith451d0e32016-09-09 21:56:20 -04004321 return NULL;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004322 }
4323
Eric V. Smith451d0e32016-09-09 21:56:20 -04004324 len = expr_end - expr_start;
4325 /* Allocate 3 extra bytes: open paren, close paren, null byte. */
4326 str = PyMem_RawMalloc(len + 3);
4327 if (str == NULL)
4328 return NULL;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004329
Eric V. Smith451d0e32016-09-09 21:56:20 -04004330 str[0] = '(';
4331 memcpy(str+1, expr_start, len);
4332 str[len+1] = ')';
4333 str[len+2] = 0;
Eric V. Smith1d44c412015-09-23 07:49:00 -04004334
4335 cf.cf_flags = PyCF_ONLY_AST;
Ɓukasz Langae7c566c2017-09-06 17:27:58 -07004336 mod_n = PyParser_SimpleParseStringFlagsFilename(str, "<fstring>",
4337 Py_eval_input, 0);
4338 if (!mod_n) {
4339 PyMem_RawFree(str);
4340 return NULL;
4341 }
4342 /* Reuse str to find the correct column offset. */
4343 str[0] = '{';
4344 str[len+1] = '}';
4345 fstring_fix_node_location(n, mod_n, str);
4346 mod = PyAST_FromNode(mod_n, &cf, "<fstring>", c->c_arena);
Eric V. Smith451d0e32016-09-09 21:56:20 -04004347 PyMem_RawFree(str);
Ɓukasz Langae7c566c2017-09-06 17:27:58 -07004348 PyNode_Free(mod_n);
Eric V. Smith235a6f02015-09-19 14:51:32 -04004349 if (!mod)
Eric V. Smith451d0e32016-09-09 21:56:20 -04004350 return NULL;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004351 return mod->v.Expression.body;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004352}
4353
4354/* Return -1 on error.
4355
4356 Return 0 if we reached the end of the literal.
4357
4358 Return 1 if we haven't reached the end of the literal, but we want
4359 the caller to process the literal up to this point. Used for
4360 doubled braces.
4361*/
4362static int
Eric V. Smith451d0e32016-09-09 21:56:20 -04004363fstring_find_literal(const char **str, const char *end, int raw,
4364 PyObject **literal, int recurse_lvl,
4365 struct compiling *c, const node *n)
Eric V. Smith235a6f02015-09-19 14:51:32 -04004366{
Eric V. Smith451d0e32016-09-09 21:56:20 -04004367 /* Get any literal string. It ends when we hit an un-doubled left
4368 brace (which isn't part of a unicode name escape such as
4369 "\N{EULER CONSTANT}"), or the end of the string. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004370
Serhiy Storchaka0cd7a3f2017-05-25 13:33:55 +03004371 const char *s = *str;
4372 const char *literal_start = s;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004373 int result = 0;
4374
Eric V. Smith235a6f02015-09-19 14:51:32 -04004375 assert(*literal == NULL);
Serhiy Storchaka0cd7a3f2017-05-25 13:33:55 +03004376 while (s < end) {
4377 char ch = *s++;
4378 if (!raw && ch == '\\' && s < end) {
4379 ch = *s++;
4380 if (ch == 'N') {
4381 if (s < end && *s++ == '{') {
4382 while (s < end && *s++ != '}') {
4383 }
4384 continue;
4385 }
4386 break;
4387 }
4388 if (ch == '{' && warn_invalid_escape_sequence(c, n, ch) < 0) {
4389 return -1;
4390 }
4391 }
4392 if (ch == '{' || ch == '}') {
Eric V. Smith235a6f02015-09-19 14:51:32 -04004393 /* Check for doubled braces, but only at the top level. If
4394 we checked at every level, then f'{0:{3}}' would fail
4395 with the two closing braces. */
4396 if (recurse_lvl == 0) {
Serhiy Storchaka0cd7a3f2017-05-25 13:33:55 +03004397 if (s < end && *s == ch) {
Eric V. Smith235a6f02015-09-19 14:51:32 -04004398 /* We're going to tell the caller that the literal ends
4399 here, but that they should continue scanning. But also
4400 skip over the second brace when we resume scanning. */
Serhiy Storchaka0cd7a3f2017-05-25 13:33:55 +03004401 *str = s + 1;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004402 result = 1;
4403 goto done;
4404 }
4405
4406 /* Where a single '{' is the start of a new expression, a
4407 single '}' is not allowed. */
4408 if (ch == '}') {
Serhiy Storchaka0cd7a3f2017-05-25 13:33:55 +03004409 *str = s - 1;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004410 ast_error(c, n, "f-string: single '}' is not allowed");
4411 return -1;
4412 }
4413 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004414 /* We're either at a '{', which means we're starting another
4415 expression; or a '}', which means we're at the end of this
4416 f-string (for a nested format_spec). */
Serhiy Storchaka0cd7a3f2017-05-25 13:33:55 +03004417 s--;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004418 break;
4419 }
4420 }
Serhiy Storchaka0cd7a3f2017-05-25 13:33:55 +03004421 *str = s;
4422 assert(s <= end);
4423 assert(s == end || *s == '{' || *s == '}');
Eric V. Smith235a6f02015-09-19 14:51:32 -04004424done:
Serhiy Storchaka0cd7a3f2017-05-25 13:33:55 +03004425 if (literal_start != s) {
Eric V. Smith451d0e32016-09-09 21:56:20 -04004426 if (raw)
4427 *literal = PyUnicode_DecodeUTF8Stateful(literal_start,
Serhiy Storchaka0cd7a3f2017-05-25 13:33:55 +03004428 s - literal_start,
Eric V. Smith451d0e32016-09-09 21:56:20 -04004429 NULL, NULL);
4430 else
Eric V. Smith56466482016-10-31 14:46:26 -04004431 *literal = decode_unicode_with_escapes(c, n, literal_start,
Serhiy Storchaka0cd7a3f2017-05-25 13:33:55 +03004432 s - literal_start);
Eric V. Smith235a6f02015-09-19 14:51:32 -04004433 if (!*literal)
4434 return -1;
4435 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004436 return result;
4437}
4438
4439/* Forward declaration because parsing is recursive. */
4440static expr_ty
Eric V. Smith451d0e32016-09-09 21:56:20 -04004441fstring_parse(const char **str, const char *end, int raw, int recurse_lvl,
Eric V. Smith235a6f02015-09-19 14:51:32 -04004442 struct compiling *c, const node *n);
4443
Eric V. Smith451d0e32016-09-09 21:56:20 -04004444/* Parse the f-string at *str, ending at end. We know *str starts an
Eric V. Smith235a6f02015-09-19 14:51:32 -04004445 expression (so it must be a '{'). Returns the FormattedValue node,
4446 which includes the expression, conversion character, and
4447 format_spec expression.
4448
4449 Note that I don't do a perfect job here: I don't make sure that a
4450 closing brace doesn't match an opening paren, for example. It
4451 doesn't need to error on all invalid expressions, just correctly
4452 find the end of all valid ones. Any errors inside the expression
4453 will be caught when we parse it later. */
4454static int
Eric V. Smith451d0e32016-09-09 21:56:20 -04004455fstring_find_expr(const char **str, const char *end, int raw, int recurse_lvl,
Eric V. Smith235a6f02015-09-19 14:51:32 -04004456 expr_ty *expression, struct compiling *c, const node *n)
4457{
4458 /* Return -1 on error, else 0. */
4459
Eric V. Smith451d0e32016-09-09 21:56:20 -04004460 const char *expr_start;
4461 const char *expr_end;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004462 expr_ty simple_expression;
4463 expr_ty format_spec = NULL; /* Optional format specifier. */
Benjamin Peterson4ba5c882016-09-09 19:31:12 -07004464 int conversion = -1; /* The conversion char. -1 if not specified. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004465
4466 /* 0 if we're not in a string, else the quote char we're trying to
4467 match (single or double quote). */
Eric V. Smith451d0e32016-09-09 21:56:20 -04004468 char quote_char = 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004469
4470 /* If we're inside a string, 1=normal, 3=triple-quoted. */
4471 int string_type = 0;
4472
4473 /* Keep track of nesting level for braces/parens/brackets in
4474 expressions. */
4475 Py_ssize_t nested_depth = 0;
4476
4477 /* Can only nest one level deep. */
4478 if (recurse_lvl >= 2) {
4479 ast_error(c, n, "f-string: expressions nested too deeply");
4480 return -1;
4481 }
4482
4483 /* The first char must be a left brace, or we wouldn't have gotten
4484 here. Skip over it. */
Eric V. Smith451d0e32016-09-09 21:56:20 -04004485 assert(**str == '{');
4486 *str += 1;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004487
Eric V. Smith451d0e32016-09-09 21:56:20 -04004488 expr_start = *str;
4489 for (; *str < end; (*str)++) {
4490 char ch;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004491
4492 /* Loop invariants. */
4493 assert(nested_depth >= 0);
Eric V. Smith451d0e32016-09-09 21:56:20 -04004494 assert(*str >= expr_start && *str < end);
Eric V. Smith235a6f02015-09-19 14:51:32 -04004495 if (quote_char)
4496 assert(string_type == 1 || string_type == 3);
4497 else
4498 assert(string_type == 0);
4499
Eric V. Smith451d0e32016-09-09 21:56:20 -04004500 ch = **str;
4501 /* Nowhere inside an expression is a backslash allowed. */
4502 if (ch == '\\') {
4503 /* Error: can't include a backslash character, inside
4504 parens or strings or not. */
4505 ast_error(c, n, "f-string expression part "
4506 "cannot include a backslash");
4507 return -1;
4508 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004509 if (quote_char) {
4510 /* We're inside a string. See if we're at the end. */
4511 /* This code needs to implement the same non-error logic
4512 as tok_get from tokenizer.c, at the letter_quote
4513 label. To actually share that code would be a
4514 nightmare. But, it's unlikely to change and is small,
4515 so duplicate it here. Note we don't need to catch all
4516 of the errors, since they'll be caught when parsing the
4517 expression. We just need to match the non-error
4518 cases. Thus we can ignore \n in single-quoted strings,
4519 for example. Or non-terminated strings. */
4520 if (ch == quote_char) {
4521 /* Does this match the string_type (single or triple
4522 quoted)? */
4523 if (string_type == 3) {
Eric V. Smith451d0e32016-09-09 21:56:20 -04004524 if (*str+2 < end && *(*str+1) == ch && *(*str+2) == ch) {
Eric V. Smith235a6f02015-09-19 14:51:32 -04004525 /* We're at the end of a triple quoted string. */
Eric V. Smith451d0e32016-09-09 21:56:20 -04004526 *str += 2;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004527 string_type = 0;
4528 quote_char = 0;
4529 continue;
4530 }
4531 } else {
4532 /* We're at the end of a normal string. */
4533 quote_char = 0;
4534 string_type = 0;
4535 continue;
4536 }
4537 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004538 } else if (ch == '\'' || ch == '"') {
4539 /* Is this a triple quoted string? */
Eric V. Smith451d0e32016-09-09 21:56:20 -04004540 if (*str+2 < end && *(*str+1) == ch && *(*str+2) == ch) {
Eric V. Smith235a6f02015-09-19 14:51:32 -04004541 string_type = 3;
Eric V. Smith451d0e32016-09-09 21:56:20 -04004542 *str += 2;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004543 } else {
4544 /* Start of a normal string. */
4545 string_type = 1;
4546 }
4547 /* Start looking for the end of the string. */
4548 quote_char = ch;
4549 } else if (ch == '[' || ch == '{' || ch == '(') {
4550 nested_depth++;
4551 } else if (nested_depth != 0 &&
4552 (ch == ']' || ch == '}' || ch == ')')) {
4553 nested_depth--;
4554 } else if (ch == '#') {
4555 /* Error: can't include a comment character, inside parens
4556 or not. */
Eric V. Smith09835dc2016-09-11 18:58:20 -04004557 ast_error(c, n, "f-string expression part cannot include '#'");
Eric V. Smith235a6f02015-09-19 14:51:32 -04004558 return -1;
4559 } else if (nested_depth == 0 &&
4560 (ch == '!' || ch == ':' || ch == '}')) {
4561 /* First, test for the special case of "!=". Since '=' is
4562 not an allowed conversion character, nothing is lost in
4563 this test. */
Eric V. Smith451d0e32016-09-09 21:56:20 -04004564 if (ch == '!' && *str+1 < end && *(*str+1) == '=') {
Eric V. Smith235a6f02015-09-19 14:51:32 -04004565 /* This isn't a conversion character, just continue. */
4566 continue;
Eric V. Smith451d0e32016-09-09 21:56:20 -04004567 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004568 /* Normal way out of this loop. */
4569 break;
4570 } else {
4571 /* Just consume this char and loop around. */
4572 }
4573 }
Eric V. Smith451d0e32016-09-09 21:56:20 -04004574 expr_end = *str;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004575 /* If we leave this loop in a string or with mismatched parens, we
4576 don't care. We'll get a syntax error when compiling the
4577 expression. But, we can produce a better error message, so
4578 let's just do that.*/
4579 if (quote_char) {
4580 ast_error(c, n, "f-string: unterminated string");
4581 return -1;
4582 }
4583 if (nested_depth) {
4584 ast_error(c, n, "f-string: mismatched '(', '{', or '['");
4585 return -1;
4586 }
4587
Eric V. Smith451d0e32016-09-09 21:56:20 -04004588 if (*str >= end)
Eric V. Smith235a6f02015-09-19 14:51:32 -04004589 goto unexpected_end_of_string;
Eric V. Smith1d44c412015-09-23 07:49:00 -04004590
4591 /* Compile the expression as soon as possible, so we show errors
4592 related to the expression before errors related to the
4593 conversion or format_spec. */
Eric V. Smith451d0e32016-09-09 21:56:20 -04004594 simple_expression = fstring_compile_expr(expr_start, expr_end, c, n);
Eric V. Smith1d44c412015-09-23 07:49:00 -04004595 if (!simple_expression)
4596 return -1;
4597
4598 /* Check for a conversion char, if present. */
Eric V. Smith451d0e32016-09-09 21:56:20 -04004599 if (**str == '!') {
4600 *str += 1;
4601 if (*str >= end)
Eric V. Smith235a6f02015-09-19 14:51:32 -04004602 goto unexpected_end_of_string;
4603
Eric V. Smith451d0e32016-09-09 21:56:20 -04004604 conversion = **str;
4605 *str += 1;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004606
4607 /* Validate the conversion. */
4608 if (!(conversion == 's' || conversion == 'r'
4609 || conversion == 'a')) {
4610 ast_error(c, n, "f-string: invalid conversion character: "
4611 "expected 's', 'r', or 'a'");
4612 return -1;
4613 }
4614 }
4615
4616 /* Check for the format spec, if present. */
Eric V. Smith451d0e32016-09-09 21:56:20 -04004617 if (*str >= end)
Eric V. Smith235a6f02015-09-19 14:51:32 -04004618 goto unexpected_end_of_string;
Eric V. Smith451d0e32016-09-09 21:56:20 -04004619 if (**str == ':') {
4620 *str += 1;
4621 if (*str >= end)
Eric V. Smith235a6f02015-09-19 14:51:32 -04004622 goto unexpected_end_of_string;
4623
4624 /* Parse the format spec. */
Eric V. Smith451d0e32016-09-09 21:56:20 -04004625 format_spec = fstring_parse(str, end, raw, recurse_lvl+1, c, n);
Eric V. Smith235a6f02015-09-19 14:51:32 -04004626 if (!format_spec)
4627 return -1;
4628 }
4629
Eric V. Smith451d0e32016-09-09 21:56:20 -04004630 if (*str >= end || **str != '}')
Eric V. Smith235a6f02015-09-19 14:51:32 -04004631 goto unexpected_end_of_string;
4632
4633 /* We're at a right brace. Consume it. */
Eric V. Smith451d0e32016-09-09 21:56:20 -04004634 assert(*str < end);
4635 assert(**str == '}');
4636 *str += 1;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004637
Eric V. Smith451d0e32016-09-09 21:56:20 -04004638 /* And now create the FormattedValue node that represents this
4639 entire expression with the conversion and format spec. */
Benjamin Peterson4ba5c882016-09-09 19:31:12 -07004640 *expression = FormattedValue(simple_expression, conversion,
Eric V. Smith235a6f02015-09-19 14:51:32 -04004641 format_spec, LINENO(n), n->n_col_offset,
4642 c->c_arena);
4643 if (!*expression)
4644 return -1;
4645
4646 return 0;
4647
4648unexpected_end_of_string:
4649 ast_error(c, n, "f-string: expecting '}'");
4650 return -1;
4651}
4652
4653/* Return -1 on error.
4654
4655 Return 0 if we have a literal (possible zero length) and an
4656 expression (zero length if at the end of the string.
4657
4658 Return 1 if we have a literal, but no expression, and we want the
4659 caller to call us again. This is used to deal with doubled
4660 braces.
4661
4662 When called multiple times on the string 'a{{b{0}c', this function
4663 will return:
4664
4665 1. the literal 'a{' with no expression, and a return value
4666 of 1. Despite the fact that there's no expression, the return
4667 value of 1 means we're not finished yet.
4668
4669 2. the literal 'b' and the expression '0', with a return value of
4670 0. The fact that there's an expression means we're not finished.
4671
4672 3. literal 'c' with no expression and a return value of 0. The
4673 combination of the return value of 0 with no expression means
4674 we're finished.
4675*/
4676static int
Eric V. Smith451d0e32016-09-09 21:56:20 -04004677fstring_find_literal_and_expr(const char **str, const char *end, int raw,
4678 int recurse_lvl, PyObject **literal,
4679 expr_ty *expression,
Eric V. Smith235a6f02015-09-19 14:51:32 -04004680 struct compiling *c, const node *n)
4681{
4682 int result;
4683
4684 assert(*literal == NULL && *expression == NULL);
4685
4686 /* Get any literal string. */
Eric V. Smith451d0e32016-09-09 21:56:20 -04004687 result = fstring_find_literal(str, end, raw, literal, recurse_lvl, c, n);
Eric V. Smith235a6f02015-09-19 14:51:32 -04004688 if (result < 0)
4689 goto error;
4690
4691 assert(result == 0 || result == 1);
4692
4693 if (result == 1)
4694 /* We have a literal, but don't look at the expression. */
4695 return 1;
4696
Eric V. Smith451d0e32016-09-09 21:56:20 -04004697 if (*str >= end || **str == '}')
Eric V. Smith235a6f02015-09-19 14:51:32 -04004698 /* We're at the end of the string or the end of a nested
4699 f-string: no expression. The top-level error case where we
4700 expect to be at the end of the string but we're at a '}' is
4701 handled later. */
4702 return 0;
4703
4704 /* We must now be the start of an expression, on a '{'. */
Eric V. Smith451d0e32016-09-09 21:56:20 -04004705 assert(**str == '{');
Eric V. Smith235a6f02015-09-19 14:51:32 -04004706
Eric V. Smith451d0e32016-09-09 21:56:20 -04004707 if (fstring_find_expr(str, end, raw, recurse_lvl, expression, c, n) < 0)
Eric V. Smith235a6f02015-09-19 14:51:32 -04004708 goto error;
4709
4710 return 0;
4711
4712error:
Serhiy Storchaka726fc132015-12-27 15:44:33 +02004713 Py_CLEAR(*literal);
Eric V. Smith235a6f02015-09-19 14:51:32 -04004714 return -1;
4715}
4716
4717#define EXPRLIST_N_CACHED 64
4718
4719typedef struct {
4720 /* Incrementally build an array of expr_ty, so be used in an
4721 asdl_seq. Cache some small but reasonably sized number of
4722 expr_ty's, and then after that start dynamically allocating,
4723 doubling the number allocated each time. Note that the f-string
4724 f'{0}a{1}' contains 3 expr_ty's: 2 FormattedValue's, and one
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004725 Constant for the literal 'a'. So you add expr_ty's about twice as
Eric V. Smith235a6f02015-09-19 14:51:32 -04004726 fast as you add exressions in an f-string. */
4727
4728 Py_ssize_t allocated; /* Number we've allocated. */
4729 Py_ssize_t size; /* Number we've used. */
4730 expr_ty *p; /* Pointer to the memory we're actually
4731 using. Will point to 'data' until we
4732 start dynamically allocating. */
4733 expr_ty data[EXPRLIST_N_CACHED];
4734} ExprList;
4735
4736#ifdef NDEBUG
4737#define ExprList_check_invariants(l)
4738#else
4739static void
4740ExprList_check_invariants(ExprList *l)
4741{
4742 /* Check our invariants. Make sure this object is "live", and
4743 hasn't been deallocated. */
4744 assert(l->size >= 0);
4745 assert(l->p != NULL);
4746 if (l->size <= EXPRLIST_N_CACHED)
4747 assert(l->data == l->p);
4748}
4749#endif
4750
4751static void
4752ExprList_Init(ExprList *l)
4753{
4754 l->allocated = EXPRLIST_N_CACHED;
4755 l->size = 0;
4756
4757 /* Until we start allocating dynamically, p points to data. */
4758 l->p = l->data;
4759
4760 ExprList_check_invariants(l);
4761}
4762
4763static int
4764ExprList_Append(ExprList *l, expr_ty exp)
4765{
4766 ExprList_check_invariants(l);
4767 if (l->size >= l->allocated) {
4768 /* We need to alloc (or realloc) the memory. */
4769 Py_ssize_t new_size = l->allocated * 2;
4770
4771 /* See if we've ever allocated anything dynamically. */
4772 if (l->p == l->data) {
4773 Py_ssize_t i;
4774 /* We're still using the cached data. Switch to
4775 alloc-ing. */
4776 l->p = PyMem_RawMalloc(sizeof(expr_ty) * new_size);
4777 if (!l->p)
4778 return -1;
4779 /* Copy the cached data into the new buffer. */
4780 for (i = 0; i < l->size; i++)
4781 l->p[i] = l->data[i];
4782 } else {
4783 /* Just realloc. */
4784 expr_ty *tmp = PyMem_RawRealloc(l->p, sizeof(expr_ty) * new_size);
4785 if (!tmp) {
4786 PyMem_RawFree(l->p);
4787 l->p = NULL;
4788 return -1;
4789 }
4790 l->p = tmp;
4791 }
4792
4793 l->allocated = new_size;
4794 assert(l->allocated == 2 * l->size);
4795 }
4796
4797 l->p[l->size++] = exp;
4798
4799 ExprList_check_invariants(l);
4800 return 0;
4801}
4802
4803static void
4804ExprList_Dealloc(ExprList *l)
4805{
4806 ExprList_check_invariants(l);
4807
4808 /* If there's been an error, or we've never dynamically allocated,
4809 do nothing. */
4810 if (!l->p || l->p == l->data) {
4811 /* Do nothing. */
4812 } else {
4813 /* We have dynamically allocated. Free the memory. */
4814 PyMem_RawFree(l->p);
4815 }
4816 l->p = NULL;
4817 l->size = -1;
4818}
4819
4820static asdl_seq *
4821ExprList_Finish(ExprList *l, PyArena *arena)
4822{
4823 asdl_seq *seq;
4824
4825 ExprList_check_invariants(l);
4826
4827 /* Allocate the asdl_seq and copy the expressions in to it. */
4828 seq = _Py_asdl_seq_new(l->size, arena);
4829 if (seq) {
4830 Py_ssize_t i;
4831 for (i = 0; i < l->size; i++)
4832 asdl_seq_SET(seq, i, l->p[i]);
4833 }
4834 ExprList_Dealloc(l);
4835 return seq;
4836}
4837
4838/* The FstringParser is designed to add a mix of strings and
4839 f-strings, and concat them together as needed. Ultimately, it
4840 generates an expr_ty. */
4841typedef struct {
4842 PyObject *last_str;
4843 ExprList expr_list;
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004844 int fmode;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004845} FstringParser;
4846
4847#ifdef NDEBUG
4848#define FstringParser_check_invariants(state)
4849#else
4850static void
4851FstringParser_check_invariants(FstringParser *state)
4852{
4853 if (state->last_str)
4854 assert(PyUnicode_CheckExact(state->last_str));
4855 ExprList_check_invariants(&state->expr_list);
4856}
4857#endif
4858
4859static void
4860FstringParser_Init(FstringParser *state)
4861{
4862 state->last_str = NULL;
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004863 state->fmode = 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004864 ExprList_Init(&state->expr_list);
4865 FstringParser_check_invariants(state);
4866}
4867
4868static void
4869FstringParser_Dealloc(FstringParser *state)
4870{
4871 FstringParser_check_invariants(state);
4872
4873 Py_XDECREF(state->last_str);
4874 ExprList_Dealloc(&state->expr_list);
4875}
4876
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004877/* Make a Constant node, but decref the PyUnicode object being added. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004878static expr_ty
4879make_str_node_and_del(PyObject **str, struct compiling *c, const node* n)
4880{
4881 PyObject *s = *str;
4882 *str = NULL;
4883 assert(PyUnicode_CheckExact(s));
4884 if (PyArena_AddPyObject(c->c_arena, s) < 0) {
4885 Py_DECREF(s);
4886 return NULL;
4887 }
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004888 return Constant(s, LINENO(n), n->n_col_offset, c->c_arena);
Eric V. Smith235a6f02015-09-19 14:51:32 -04004889}
4890
4891/* Add a non-f-string (that is, a regular literal string). str is
4892 decref'd. */
4893static int
4894FstringParser_ConcatAndDel(FstringParser *state, PyObject *str)
4895{
4896 FstringParser_check_invariants(state);
4897
4898 assert(PyUnicode_CheckExact(str));
4899
4900 if (PyUnicode_GET_LENGTH(str) == 0) {
4901 Py_DECREF(str);
4902 return 0;
4903 }
4904
4905 if (!state->last_str) {
4906 /* We didn't have a string before, so just remember this one. */
4907 state->last_str = str;
4908 } else {
4909 /* Concatenate this with the previous string. */
Serhiy Storchaka726fc132015-12-27 15:44:33 +02004910 PyUnicode_AppendAndDel(&state->last_str, str);
4911 if (!state->last_str)
Eric V. Smith235a6f02015-09-19 14:51:32 -04004912 return -1;
4913 }
4914 FstringParser_check_invariants(state);
4915 return 0;
4916}
4917
Eric V. Smith451d0e32016-09-09 21:56:20 -04004918/* Parse an f-string. The f-string is in *str to end, with no
4919 'f' or quotes. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004920static int
Eric V. Smith451d0e32016-09-09 21:56:20 -04004921FstringParser_ConcatFstring(FstringParser *state, const char **str,
4922 const char *end, int raw, int recurse_lvl,
Eric V. Smith235a6f02015-09-19 14:51:32 -04004923 struct compiling *c, const node *n)
4924{
4925 FstringParser_check_invariants(state);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004926 state->fmode = 1;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004927
4928 /* Parse the f-string. */
4929 while (1) {
4930 PyObject *literal = NULL;
4931 expr_ty expression = NULL;
4932
4933 /* If there's a zero length literal in front of the
4934 expression, literal will be NULL. If we're at the end of
4935 the f-string, expression will be NULL (unless result == 1,
4936 see below). */
Eric V. Smith451d0e32016-09-09 21:56:20 -04004937 int result = fstring_find_literal_and_expr(str, end, raw, recurse_lvl,
Eric V. Smith235a6f02015-09-19 14:51:32 -04004938 &literal, &expression,
4939 c, n);
4940 if (result < 0)
4941 return -1;
4942
4943 /* Add the literal, if any. */
4944 if (!literal) {
4945 /* Do nothing. Just leave last_str alone (and possibly
4946 NULL). */
4947 } else if (!state->last_str) {
ericvsmith11e97f22017-06-16 06:19:32 -04004948 /* Note that the literal can be zero length, if the
4949 input string is "\\\n" or "\\\r", among others. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004950 state->last_str = literal;
4951 literal = NULL;
4952 } else {
4953 /* We have a literal, concatenate it. */
4954 assert(PyUnicode_GET_LENGTH(literal) != 0);
4955 if (FstringParser_ConcatAndDel(state, literal) < 0)
4956 return -1;
4957 literal = NULL;
4958 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004959
4960 /* We've dealt with the literal now. It can't be leaked on further
4961 errors. */
4962 assert(literal == NULL);
4963
4964 /* See if we should just loop around to get the next literal
4965 and expression, while ignoring the expression this
4966 time. This is used for un-doubling braces, as an
4967 optimization. */
4968 if (result == 1)
4969 continue;
4970
4971 if (!expression)
4972 /* We're done with this f-string. */
4973 break;
4974
4975 /* We know we have an expression. Convert any existing string
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004976 to a Constant node. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004977 if (!state->last_str) {
4978 /* Do nothing. No previous literal. */
4979 } else {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004980 /* Convert the existing last_str literal to a Constant node. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004981 expr_ty str = make_str_node_and_del(&state->last_str, c, n);
4982 if (!str || ExprList_Append(&state->expr_list, str) < 0)
4983 return -1;
4984 }
4985
4986 if (ExprList_Append(&state->expr_list, expression) < 0)
4987 return -1;
4988 }
4989
Eric V. Smith235a6f02015-09-19 14:51:32 -04004990 /* If recurse_lvl is zero, then we must be at the end of the
4991 string. Otherwise, we must be at a right brace. */
4992
Eric V. Smith451d0e32016-09-09 21:56:20 -04004993 if (recurse_lvl == 0 && *str < end-1) {
Eric V. Smith235a6f02015-09-19 14:51:32 -04004994 ast_error(c, n, "f-string: unexpected end of string");
4995 return -1;
4996 }
Eric V. Smith451d0e32016-09-09 21:56:20 -04004997 if (recurse_lvl != 0 && **str != '}') {
Eric V. Smith235a6f02015-09-19 14:51:32 -04004998 ast_error(c, n, "f-string: expecting '}'");
4999 return -1;
5000 }
5001
5002 FstringParser_check_invariants(state);
5003 return 0;
5004}
5005
5006/* Convert the partial state reflected in last_str and expr_list to an
Serhiy Storchaka3f228112018-09-27 17:42:37 +03005007 expr_ty. The expr_ty can be a Constant, or a JoinedStr. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04005008static expr_ty
5009FstringParser_Finish(FstringParser *state, struct compiling *c,
5010 const node *n)
5011{
5012 asdl_seq *seq;
5013
5014 FstringParser_check_invariants(state);
5015
5016 /* If we're just a constant string with no expressions, return
5017 that. */
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02005018 if (!state->fmode) {
5019 assert(!state->expr_list.size);
Eric V. Smith235a6f02015-09-19 14:51:32 -04005020 if (!state->last_str) {
5021 /* Create a zero length string. */
5022 state->last_str = PyUnicode_FromStringAndSize(NULL, 0);
5023 if (!state->last_str)
5024 goto error;
5025 }
5026 return make_str_node_and_del(&state->last_str, c, n);
5027 }
5028
Serhiy Storchaka3f228112018-09-27 17:42:37 +03005029 /* Create a Constant node out of last_str, if needed. It will be the
Eric V. Smith235a6f02015-09-19 14:51:32 -04005030 last node in our expression list. */
5031 if (state->last_str) {
5032 expr_ty str = make_str_node_and_del(&state->last_str, c, n);
5033 if (!str || ExprList_Append(&state->expr_list, str) < 0)
5034 goto error;
5035 }
5036 /* This has already been freed. */
5037 assert(state->last_str == NULL);
5038
5039 seq = ExprList_Finish(&state->expr_list, c->c_arena);
5040 if (!seq)
5041 goto error;
5042
Eric V. Smith235a6f02015-09-19 14:51:32 -04005043 return JoinedStr(seq, LINENO(n), n->n_col_offset, c->c_arena);
5044
5045error:
5046 FstringParser_Dealloc(state);
5047 return NULL;
5048}
5049
Eric V. Smith451d0e32016-09-09 21:56:20 -04005050/* Given an f-string (with no 'f' or quotes) that's in *str and ends
5051 at end, parse it into an expr_ty. Return NULL on error. Adjust
5052 str to point past the parsed portion. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04005053static expr_ty
Eric V. Smith451d0e32016-09-09 21:56:20 -04005054fstring_parse(const char **str, const char *end, int raw, int recurse_lvl,
Eric V. Smith235a6f02015-09-19 14:51:32 -04005055 struct compiling *c, const node *n)
5056{
5057 FstringParser state;
5058
5059 FstringParser_Init(&state);
Eric V. Smith451d0e32016-09-09 21:56:20 -04005060 if (FstringParser_ConcatFstring(&state, str, end, raw, recurse_lvl,
Eric V. Smith235a6f02015-09-19 14:51:32 -04005061 c, n) < 0) {
5062 FstringParser_Dealloc(&state);
5063 return NULL;
5064 }
5065
5066 return FstringParser_Finish(&state, c, n);
5067}
5068
5069/* n is a Python string literal, including the bracketing quote
5070 characters, and r, b, u, &/or f prefixes (if any), and embedded
Eric V. Smith451d0e32016-09-09 21:56:20 -04005071 escape sequences (if any). parsestr parses it, and sets *result to
Eric V. Smith235a6f02015-09-19 14:51:32 -04005072 decoded Python string object. If the string is an f-string, set
Eric V. Smith451d0e32016-09-09 21:56:20 -04005073 *fstr and *fstrlen to the unparsed string object. Return 0 if no
5074 errors occurred.
Eric V. Smith235a6f02015-09-19 14:51:32 -04005075*/
Eric V. Smith451d0e32016-09-09 21:56:20 -04005076static int
5077parsestr(struct compiling *c, const node *n, int *bytesmode, int *rawmode,
5078 PyObject **result, const char **fstr, Py_ssize_t *fstrlen)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005079{
Guido van Rossumd8faa362007-04-27 19:54:29 +00005080 size_t len;
5081 const char *s = STR(n);
5082 int quote = Py_CHARMASK(*s);
Eric V. Smith451d0e32016-09-09 21:56:20 -04005083 int fmode = 0;
5084 *bytesmode = 0;
5085 *rawmode = 0;
5086 *result = NULL;
5087 *fstr = NULL;
Antoine Pitrou4de74572013-02-09 23:11:27 +01005088 if (Py_ISALPHA(quote)) {
Eric V. Smith451d0e32016-09-09 21:56:20 -04005089 while (!*bytesmode || !*rawmode) {
Antoine Pitrou3a5d4cb2012-01-12 22:46:19 +01005090 if (quote == 'b' || quote == 'B') {
5091 quote = *++s;
5092 *bytesmode = 1;
5093 }
Armin Ronacher6ecf77b2012-03-04 12:04:06 +00005094 else if (quote == 'u' || quote == 'U') {
5095 quote = *++s;
5096 }
Antoine Pitrou3a5d4cb2012-01-12 22:46:19 +01005097 else if (quote == 'r' || quote == 'R') {
5098 quote = *++s;
Eric V. Smith451d0e32016-09-09 21:56:20 -04005099 *rawmode = 1;
Antoine Pitrou3a5d4cb2012-01-12 22:46:19 +01005100 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04005101 else if (quote == 'f' || quote == 'F') {
5102 quote = *++s;
Eric V. Smith451d0e32016-09-09 21:56:20 -04005103 fmode = 1;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005104 }
Antoine Pitrou3a5d4cb2012-01-12 22:46:19 +01005105 else {
5106 break;
5107 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005108 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00005109 }
Eric V. Smith451d0e32016-09-09 21:56:20 -04005110 if (fmode && *bytesmode) {
Eric V. Smith235a6f02015-09-19 14:51:32 -04005111 PyErr_BadInternalCall();
Eric V. Smith451d0e32016-09-09 21:56:20 -04005112 return -1;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005113 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00005114 if (quote != '\'' && quote != '\"') {
5115 PyErr_BadInternalCall();
Eric V. Smith451d0e32016-09-09 21:56:20 -04005116 return -1;
Guido van Rossumd8faa362007-04-27 19:54:29 +00005117 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04005118 /* Skip the leading quote char. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005119 s++;
5120 len = strlen(s);
5121 if (len > INT_MAX) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005122 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005123 "string to parse is too long");
Eric V. Smith451d0e32016-09-09 21:56:20 -04005124 return -1;
Guido van Rossumd8faa362007-04-27 19:54:29 +00005125 }
5126 if (s[--len] != quote) {
Eric V. Smith235a6f02015-09-19 14:51:32 -04005127 /* Last quote char must match the first. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005128 PyErr_BadInternalCall();
Eric V. Smith451d0e32016-09-09 21:56:20 -04005129 return -1;
Guido van Rossumd8faa362007-04-27 19:54:29 +00005130 }
5131 if (len >= 4 && s[0] == quote && s[1] == quote) {
Eric V. Smith235a6f02015-09-19 14:51:32 -04005132 /* A triple quoted string. We've already skipped one quote at
5133 the start and one at the end of the string. Now skip the
5134 two at the start. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005135 s += 2;
5136 len -= 2;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005137 /* And check that the last two match. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005138 if (s[--len] != quote || s[--len] != quote) {
5139 PyErr_BadInternalCall();
Eric V. Smith451d0e32016-09-09 21:56:20 -04005140 return -1;
Thomas Wouters00e41de2007-02-23 19:56:57 +00005141 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00005142 }
Eric V. Smith6a4efce2016-09-03 09:18:34 -04005143
Eric V. Smith451d0e32016-09-09 21:56:20 -04005144 if (fmode) {
5145 /* Just return the bytes. The caller will parse the resulting
5146 string. */
5147 *fstr = s;
5148 *fstrlen = len;
5149 return 0;
Eric V. Smith6a4efce2016-09-03 09:18:34 -04005150 }
5151
Eric V. Smith451d0e32016-09-09 21:56:20 -04005152 /* Not an f-string. */
Benjamin Peterson768921c2016-02-25 23:13:53 -08005153 /* Avoid invoking escape decoding routines if possible. */
Eric V. Smith451d0e32016-09-09 21:56:20 -04005154 *rawmode = *rawmode || strchr(s, '\\') == NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00005155 if (*bytesmode) {
Benjamin Peterson768921c2016-02-25 23:13:53 -08005156 /* Disallow non-ASCII characters. */
Benjamin Petersonbd0df502012-09-02 15:04:51 -04005157 const char *ch;
5158 for (ch = s; *ch; ch++) {
5159 if (Py_CHARMASK(*ch) >= 0x80) {
5160 ast_error(c, n, "bytes can only contain ASCII "
Guido van Rossumd8faa362007-04-27 19:54:29 +00005161 "literal characters.");
Eric V. Smith451d0e32016-09-09 21:56:20 -04005162 return -1;
Guido van Rossumd8faa362007-04-27 19:54:29 +00005163 }
Thomas Wouters00e41de2007-02-23 19:56:57 +00005164 }
Eric V. Smith451d0e32016-09-09 21:56:20 -04005165 if (*rawmode)
5166 *result = PyBytes_FromStringAndSize(s, len);
Benjamin Peterson768921c2016-02-25 23:13:53 -08005167 else
Eric V. Smith56466482016-10-31 14:46:26 -04005168 *result = decode_bytes_with_escapes(c, n, s, len);
Benjamin Peterson768921c2016-02-25 23:13:53 -08005169 } else {
Eric V. Smith451d0e32016-09-09 21:56:20 -04005170 if (*rawmode)
5171 *result = PyUnicode_DecodeUTF8Stateful(s, len, NULL, NULL);
Benjamin Peterson768921c2016-02-25 23:13:53 -08005172 else
Eric V. Smith56466482016-10-31 14:46:26 -04005173 *result = decode_unicode_with_escapes(c, n, s, len);
Guido van Rossumd8faa362007-04-27 19:54:29 +00005174 }
Eric V. Smith451d0e32016-09-09 21:56:20 -04005175 return *result == NULL ? -1 : 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005176}
5177
Eric V. Smith235a6f02015-09-19 14:51:32 -04005178/* Accepts a STRING+ atom, and produces an expr_ty node. Run through
5179 each STRING atom, and process it as needed. For bytes, just
Serhiy Storchaka3f228112018-09-27 17:42:37 +03005180 concatenate them together, and the result will be a Constant node. For
Eric V. Smith235a6f02015-09-19 14:51:32 -04005181 normal strings and f-strings, concatenate them together. The result
Serhiy Storchaka3f228112018-09-27 17:42:37 +03005182 will be a Constant node if there were no f-strings; a FormattedValue
Eric V. Smith235a6f02015-09-19 14:51:32 -04005183 node if there's just an f-string (with no leading or trailing
5184 literals), or a JoinedStr node if there are multiple f-strings or
5185 any literals involved. */
5186static expr_ty
5187parsestrplus(struct compiling *c, const node *n)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005188{
Eric V. Smith235a6f02015-09-19 14:51:32 -04005189 int bytesmode = 0;
5190 PyObject *bytes_str = NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00005191 int i;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005192
5193 FstringParser state;
5194 FstringParser_Init(&state);
5195
5196 for (i = 0; i < NCH(n); i++) {
Eric V. Smith451d0e32016-09-09 21:56:20 -04005197 int this_bytesmode;
5198 int this_rawmode;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005199 PyObject *s;
Eric V. Smith451d0e32016-09-09 21:56:20 -04005200 const char *fstr;
5201 Py_ssize_t fstrlen = -1; /* Silence a compiler warning. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04005202
5203 REQ(CHILD(n, i), STRING);
Eric V. Smith451d0e32016-09-09 21:56:20 -04005204 if (parsestr(c, CHILD(n, i), &this_bytesmode, &this_rawmode, &s,
5205 &fstr, &fstrlen) != 0)
Eric V. Smith235a6f02015-09-19 14:51:32 -04005206 goto error;
5207
5208 /* Check that we're not mixing bytes with unicode. */
5209 if (i != 0 && bytesmode != this_bytesmode) {
5210 ast_error(c, n, "cannot mix bytes and nonbytes literals");
Eric V. Smith9b88fdf2016-11-07 17:54:01 -05005211 /* s is NULL if the current string part is an f-string. */
5212 Py_XDECREF(s);
Eric V. Smith235a6f02015-09-19 14:51:32 -04005213 goto error;
5214 }
5215 bytesmode = this_bytesmode;
5216
Eric V. Smith451d0e32016-09-09 21:56:20 -04005217 if (fstr != NULL) {
5218 int result;
5219 assert(s == NULL && !bytesmode);
5220 /* This is an f-string. Parse and concatenate it. */
5221 result = FstringParser_ConcatFstring(&state, &fstr, fstr+fstrlen,
5222 this_rawmode, 0, c, n);
Eric V. Smith235a6f02015-09-19 14:51:32 -04005223 if (result < 0)
5224 goto error;
5225 } else {
Eric V. Smith9b88fdf2016-11-07 17:54:01 -05005226 /* A string or byte string. */
5227 assert(s != NULL && fstr == NULL);
5228
Eric V. Smith451d0e32016-09-09 21:56:20 -04005229 assert(bytesmode ? PyBytes_CheckExact(s) :
5230 PyUnicode_CheckExact(s));
5231
Eric V. Smith451d0e32016-09-09 21:56:20 -04005232 if (bytesmode) {
5233 /* For bytes, concat as we go. */
5234 if (i == 0) {
5235 /* First time, just remember this value. */
5236 bytes_str = s;
5237 } else {
5238 PyBytes_ConcatAndDel(&bytes_str, s);
5239 if (!bytes_str)
5240 goto error;
5241 }
5242 } else {
Eric V. Smith451d0e32016-09-09 21:56:20 -04005243 /* This is a regular string. Concatenate it. */
5244 if (FstringParser_ConcatAndDel(&state, s) < 0)
5245 goto error;
5246 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005247 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00005248 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04005249 if (bytesmode) {
5250 /* Just return the bytes object and we're done. */
5251 if (PyArena_AddPyObject(c->c_arena, bytes_str) < 0)
5252 goto error;
Serhiy Storchaka3f228112018-09-27 17:42:37 +03005253 return Constant(bytes_str, LINENO(n), n->n_col_offset, c->c_arena);
Eric V. Smith235a6f02015-09-19 14:51:32 -04005254 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005255
Eric V. Smith235a6f02015-09-19 14:51:32 -04005256 /* We're not a bytes string, bytes_str should never have been set. */
5257 assert(bytes_str == NULL);
5258
5259 return FstringParser_Finish(&state, c, n);
5260
5261error:
5262 Py_XDECREF(bytes_str);
5263 FstringParser_Dealloc(&state);
Guido van Rossumd8faa362007-04-27 19:54:29 +00005264 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005265}
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03005266
5267PyObject *
5268_PyAST_GetDocString(asdl_seq *body)
5269{
5270 if (!asdl_seq_LEN(body)) {
5271 return NULL;
5272 }
5273 stmt_ty st = (stmt_ty)asdl_seq_GET(body, 0);
5274 if (st->kind != Expr_kind) {
5275 return NULL;
5276 }
5277 expr_ty e = st->v.Expr.value;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03005278 if (e->kind == Constant_kind && PyUnicode_CheckExact(e->v.Constant.value)) {
5279 return e->v.Constant.value;
5280 }
5281 return NULL;
5282}