Debian Codegraph @

cpython27/Modules/parsermodule.c

raw symbols SCIP
1 /* parsermodule.c
2 *
3 * Copyright 1995-1996 by Fred L. Drake, Jr. and Virginia Polytechnic
4 * Institute and State University, Blacksburg, Virginia, USA.
5 * Portions copyright 1991-1995 by Stichting Mathematisch Centrum,
6 * Amsterdam, The Netherlands. Copying is permitted under the terms
7 * associated with the main Python distribution, with the additional
8 * restriction that this additional notice be included and maintained
9 * on all distributed copies.
10 *
11 * This module serves to replace the original parser module written
12 * by Guido. The functionality is not matched precisely, but the
13 * original may be implemented on top of this. This is desirable
14 * since the source of the text to be parsed is now divorced from
15 * this interface.
16 *
17 * Unlike the prior interface, the ability to give a parse tree
18 * produced by Python code as a tuple to the compiler is enabled by
19 * this module. See the documentation for more details.
20 *
21 * I've added some annotations that help with the lint code-checking
22 * program, but they're not complete by a long shot. The real errors
23 * that lint detects are gone, but there are still warnings with
24 * Py_[X]DECREF() and Py_[X]INCREF() macros. The lint annotations
25 * look like "NOTE(...)".
26 */
27
28 #include "Python.h" /* general Python API */
29 #include "Python-ast.h" /* mod_ty */
30 #include "graminit.h" /* symbols defined in the grammar */
31 #include "node.h" /* internal parser structure */
32 #include "errcode.h" /* error codes for PyNode_*() */
33 #include "token.h" /* token definitions */
34 #include "grammar.h"
35 #include "parsetok.h"
36 /* ISTERMINAL() / ISNONTERMINAL() */
37 #include "compile.h"
38 #undef Yield
39 #include "ast.h"
40 #include "pyarena.h"
41
42 extern grammar _PyParser_Grammar; /* From graminit.c */
43
44 #ifdef lint
45 #include <note.h>
46 #else
47 #define NOTE(x)
48 #endif
49
50 /* String constants used to initialize module attributes.
51 *
52 */
53 static char parser_copyright_string[] =
54 "Copyright 1995-1996 by Virginia Polytechnic Institute & State\n\
55 University, Blacksburg, Virginia, USA, and Fred L. Drake, Jr., Reston,\n\
56 Virginia, USA. Portions copyright 1991-1995 by Stichting Mathematisch\n\
57 Centrum, Amsterdam, The Netherlands.";
58
59
60 PyDoc_STRVAR(parser_doc_string,
61 "This is an interface to Python's internal parser.");
62
63 static char parser_version_string[] = "0.5";
64
65
66 typedef PyObject* (*SeqMaker) (Py_ssize_t length);
67 typedef int (*SeqInserter) (PyObject* sequence,
68 Py_ssize_t index,
69 PyObject* element);
70
71 /* The function below is copyrighted by Stichting Mathematisch Centrum. The
72 * original copyright statement is included below, and continues to apply
73 * in full to the function immediately following. All other material is
74 * original, copyrighted by Fred L. Drake, Jr. and Virginia Polytechnic
75 * Institute and State University. Changes were made to comply with the
76 * new naming conventions. Added arguments to provide support for creating
77 * lists as well as tuples, and optionally including the line numbers.
78 */
79
80
81 static PyObject*
82 node2tuple(node *n, /* node to convert */
83 SeqMaker mkseq, /* create sequence */
84 SeqInserter addelem, /* func. to add elem. in seq. */
85 int lineno, /* include line numbers? */
86 int col_offset) /* include column offsets? */
87 {
88 if (n == NULL) {
89 Py_INCREF(Py_None);
90 return (Py_None);
91 }
92 if (ISNONTERMINAL(TYPE(n))) {
93 int i;
94 PyObject *v;
95 PyObject *w;
96
97 v = mkseq(1 + NCH(n) + (TYPE(n) == encoding_decl));
98 if (v == NULL)
99 return (v);
100 w = PyInt_FromLong(TYPE(n));
101 if (w == NULL) {
102 Py_DECREF(v);
103 return ((PyObject*) NULL);
104 }
105 (void) addelem(v, 0, w);
106 for (i = 0; i < NCH(n); i++) {
107 w = node2tuple(CHILD(n, i), mkseq, addelem, lineno, col_offset);
108 if (w == NULL) {
109 Py_DECREF(v);
110 return ((PyObject*) NULL);
111 }
112 (void) addelem(v, i+1, w);
113 }
114
115 if (TYPE(n) == encoding_decl)
116 (void) addelem(v, i+1, PyString_FromString(STR(n)));
117 return (v);
118 }
119 else if (ISTERMINAL(TYPE(n))) {
120 PyObject *result = mkseq(2 + lineno + col_offset);
121 if (result != NULL) {
122 (void) addelem(result, 0, PyInt_FromLong(TYPE(n)));
123 (void) addelem(result, 1, PyString_FromString(STR(n)));
124 if (lineno)
125 (void) addelem(result, 2, PyInt_FromLong(n->n_lineno));
126 if (col_offset)
127 (void) addelem(result, 2 + lineno, PyInt_FromLong(n->n_col_offset));
128 }
129 return (result);
130 }
131 else {
132 PyErr_SetString(PyExc_SystemError,
133 "unrecognized parse tree node type");
134 return ((PyObject*) NULL);
135 }
136 }
137 /*
138 * End of material copyrighted by Stichting Mathematisch Centrum.
139 */
140
141
142
143 /* There are two types of intermediate objects we're interested in:
144 * 'eval' and 'exec' types. These constants can be used in the st_type
145 * field of the object type to identify which any given object represents.
146 * These should probably go in an external header to allow other extensions
147 * to use them, but then, we really should be using C++ too. ;-)
148 */
149
150 #define PyST_EXPR 1
151 #define PyST_SUITE 2
152
153
154 /* These are the internal objects and definitions required to implement the
155 * ST type. Most of the internal names are more reminiscent of the 'old'
156 * naming style, but the code uses the new naming convention.
157 */
158
159 static PyObject*
160 parser_error = 0;
161
162
163 typedef struct {
164 PyObject_HEAD /* standard object header */
165 node* st_node; /* the node* returned by the parser */
166 int st_type; /* EXPR or SUITE ? */
167 PyCompilerFlags st_flags; /* Parser and compiler flags */
168 } PyST_Object;
169
170
171 static void parser_free(PyST_Object *st);
172 static PyObject* parser_sizeof(PyST_Object *, void *);
173 static int parser_compare(PyST_Object *left, PyST_Object *right);
174 static PyObject *parser_getattr(PyObject *self, char *name);
175 static PyObject* parser_compilest(PyST_Object *, PyObject *, PyObject *);
176 static PyObject* parser_isexpr(PyST_Object *, PyObject *, PyObject *);
177 static PyObject* parser_issuite(PyST_Object *, PyObject *, PyObject *);
178 static PyObject* parser_st2list(PyST_Object *, PyObject *, PyObject *);
179 static PyObject* parser_st2tuple(PyST_Object *, PyObject *, PyObject *);
180
181 #define PUBLIC_METHOD_TYPE (METH_VARARGS|METH_KEYWORDS)
182
183 static PyMethodDef
184 parser_methods[] = {
185 {"compile", (PyCFunction)parser_compilest, PUBLIC_METHOD_TYPE,
186 PyDoc_STR("Compile this ST object into a code object.")},
187 {"isexpr", (PyCFunction)parser_isexpr, PUBLIC_METHOD_TYPE,
188 PyDoc_STR("Determines if this ST object was created from an expression.")},
189 {"issuite", (PyCFunction)parser_issuite, PUBLIC_METHOD_TYPE,
190 PyDoc_STR("Determines if this ST object was created from a suite.")},
191 {"tolist", (PyCFunction)parser_st2list, PUBLIC_METHOD_TYPE,
192 PyDoc_STR("Creates a list-tree representation of this ST.")},
193 {"totuple", (PyCFunction)parser_st2tuple, PUBLIC_METHOD_TYPE,
194 PyDoc_STR("Creates a tuple-tree representation of this ST.")},
195 {"__sizeof__", (PyCFunction)parser_sizeof, METH_NOARGS,
196 PyDoc_STR("Returns size in memory, in bytes.")},
197 {NULL, NULL, 0, NULL}
198 };
199
200 static
201 PyTypeObject PyST_Type = {
202 PyVarObject_HEAD_INIT(NULL, 0)
203 "parser.st", /* tp_name */
204 (int) sizeof(PyST_Object), /* tp_basicsize */
205 0, /* tp_itemsize */
206 (destructor)parser_free, /* tp_dealloc */
207 0, /* tp_print */
208 parser_getattr, /* tp_getattr */
209 0, /* tp_setattr */
210 (cmpfunc)parser_compare, /* tp_compare */
211 0, /* tp_repr */
212 0, /* tp_as_number */
213 0, /* tp_as_sequence */
214 0, /* tp_as_mapping */
215 0, /* tp_hash */
216 0, /* tp_call */
217 0, /* tp_str */
218 0, /* tp_getattro */
219 0, /* tp_setattro */
220
221 /* Functions to access object as input/output buffer */
222 0, /* tp_as_buffer */
223
224 Py_TPFLAGS_DEFAULT, /* tp_flags */
225
226 /* __doc__ */
227 "Intermediate representation of a Python parse tree.",
228 0, /* tp_traverse */
229 0, /* tp_clear */
230 0, /* tp_richcompare */
231 0, /* tp_weaklistoffset */
232 0, /* tp_iter */
233 0, /* tp_iternext */
234 parser_methods, /* tp_methods */
235 }; /* PyST_Type */
236
237
238 static int
239 parser_compare_nodes(node *left, node *right)
240 {
241 int j;
242
243 if (TYPE(left) < TYPE(right))
244 return (-1);
245
246 if (TYPE(right) < TYPE(left))
247 return (1);
248
249 if (ISTERMINAL(TYPE(left)))
250 return (strcmp(STR(left), STR(right)));
251
252 if (NCH(left) < NCH(right))
253 return (-1);
254
255 if (NCH(right) < NCH(left))
256 return (1);
257
258 for (j = 0; j < NCH(left); ++j) {
259 int v = parser_compare_nodes(CHILD(left, j), CHILD(right, j));
260
261 if (v != 0)
262 return (v);
263 }
264 return (0);
265 }
266
267
268 /* int parser_compare(PyST_Object* left, PyST_Object* right)
269 *
270 * Comparison function used by the Python operators ==, !=, <, >, <=, >=
271 * This really just wraps a call to parser_compare_nodes() with some easy
272 * checks and protection code.
273 *
274 */
275 static int
276 parser_compare(PyST_Object *left, PyST_Object *right)
277 {
278 if (left == right)
279 return (0);
280
281 if ((left == 0) || (right == 0))
282 return (-1);
283
284 return (parser_compare_nodes(left->st_node, right->st_node));
285 }
286
287
288 /* parser_newstobject(node* st)
289 *
290 * Allocates a new Python object representing an ST. This is simply the
291 * 'wrapper' object that holds a node* and allows it to be passed around in
292 * Python code.
293 *
294 */
295 static PyObject*
296 parser_newstobject(node *st, int type)
297 {
298 PyST_Object* o = PyObject_New(PyST_Object, &PyST_Type);
299
300 if (o != 0) {
301 o->st_node = st;
302 o->st_type = type;
303 o->st_flags.cf_flags = 0;
304 }
305 else {
306 PyNode_Free(st);
307 }
308 return ((PyObject*)o);
309 }
310
311
312 /* void parser_free(PyST_Object* st)
313 *
314 * This is called by a del statement that reduces the reference count to 0.
315 *
316 */
317 static void
318 parser_free(PyST_Object *st)
319 {
320 PyNode_Free(st->st_node);
321 PyObject_Del(st);
322 }
323
324
325 /* parser_st2tuple(PyObject* self, PyObject* args, PyObject* kw)
326 *
327 * This provides conversion from a node* to a tuple object that can be
328 * returned to the Python-level caller. The ST object is not modified.
329 *
330 */
331 static PyObject*
332 parser_st2tuple(PyST_Object *self, PyObject *args, PyObject *kw)
333 {
334 PyObject *line_option = 0;
335 PyObject *col_option = 0;
336 PyObject *res = 0;
337 int ok;
338
339 static char *keywords[] = {"ast", "line_info", "col_info", NULL};
340
341 if (self == NULL) {
342 ok = PyArg_ParseTupleAndKeywords(args, kw, "O!|OO:st2tuple", keywords,
343 &PyST_Type, &self, &line_option,
344 &col_option);
345 }
346 else
347 ok = PyArg_ParseTupleAndKeywords(args, kw, "|OO:totuple", &keywords[1],
348 &line_option, &col_option);
349 if (ok != 0) {
350 int lineno = 0;
351 int col_offset = 0;
352 if (line_option != NULL) {
353 lineno = PyObject_IsTrue(line_option);
354 if (lineno < 0)
355 return NULL;
356 }
357 if (col_option != NULL) {
358 col_offset = PyObject_IsTrue(col_option);
359 if (col_offset < 0)
360 return NULL;
361 }
362 /*
363 * Convert ST into a tuple representation. Use Guido's function,
364 * since it's known to work already.
365 */
366 res = node2tuple(((PyST_Object*)self)->st_node,
367 PyTuple_New, PyTuple_SetItem, lineno, col_offset);
368 }
369 return (res);
370 }
371
372 static PyObject*
373 parser_ast2tuple(PyST_Object *self, PyObject *args, PyObject *kw)
374 {
375 if (PyErr_WarnPy3k("ast2tuple is removed in 3.x; use st2tuple", 1) < 0)
376 return NULL;
377 return parser_st2tuple(self, args, kw);
378 }
379
380
381 /* parser_st2list(PyObject* self, PyObject* args, PyObject* kw)
382 *
383 * This provides conversion from a node* to a list object that can be
384 * returned to the Python-level caller. The ST object is not modified.
385 *
386 */
387 static PyObject*
388 parser_st2list(PyST_Object *self, PyObject *args, PyObject *kw)
389 {
390 PyObject *line_option = 0;
391 PyObject *col_option = 0;
392 PyObject *res = 0;
393 int ok;
394
395 static char *keywords[] = {"ast", "line_info", "col_info", NULL};
396
397 if (self == NULL)
398 ok = PyArg_ParseTupleAndKeywords(args, kw, "O!|OO:st2list", keywords,
399 &PyST_Type, &self, &line_option,
400 &col_option);
401 else
402 ok = PyArg_ParseTupleAndKeywords(args, kw, "|OO:tolist", &keywords[1],
403 &line_option, &col_option);
404 if (ok) {
405 int lineno = 0;
406 int col_offset = 0;
407 if (line_option != 0) {
408 lineno = PyObject_IsTrue(line_option);
409 if (lineno < 0)
410 return NULL;
411 }
412 if (col_option != 0) {
413 col_offset = PyObject_IsTrue(col_option);
414 if (col_offset < 0)
415 return NULL;
416 }
417 /*
418 * Convert ST into a tuple representation. Use Guido's function,
419 * since it's known to work already.
420 */
421 res = node2tuple(self->st_node,
422 PyList_New, PyList_SetItem, lineno, col_offset);
423 }
424 return (res);
425 }
426
427 static PyObject*
428 parser_ast2list(PyST_Object *self, PyObject *args, PyObject *kw)
429 {
430 if (PyErr_WarnPy3k("ast2list is removed in 3.x; use st2list", 1) < 0)
431 return NULL;
432 return parser_st2list(self, args, kw);
433 }
434
435
436 /* parser_compilest(PyObject* self, PyObject* args)
437 *
438 * This function creates code objects from the parse tree represented by
439 * the passed-in data object. An optional file name is passed in as well.
440 *
441 */
442 static PyObject*
443 parser_compilest(PyST_Object *self, PyObject *args, PyObject *kw)
444 {
445 PyObject* res = 0;
446 PyArena* arena;
447 mod_ty mod;
448 char* str = "<syntax-tree>";
449 int ok;
450
451 static char *keywords[] = {"ast", "filename", NULL};
452
453 if (self == NULL)
454 ok = PyArg_ParseTupleAndKeywords(args, kw, "O!|s:compilest", keywords,
455 &PyST_Type, &self, &str);
456 else
457 ok = PyArg_ParseTupleAndKeywords(args, kw, "|s:compile", &keywords[1],
458 &str);
459
460 if (ok) {
461 arena = PyArena_New();
462 if (arena) {
463 mod = PyAST_FromNode(self->st_node, &(self->st_flags), str, arena);
464 if (mod) {
465 res = (PyObject *)PyAST_Compile(mod, str, &(self->st_flags), arena);
466 }
467 PyArena_Free(arena);
468 }
469 }
470
471 return (res);
472 }
473
474 static PyObject*
475 parser_compileast(PyST_Object *self, PyObject *args, PyObject *kw)
476 {
477 if (PyErr_WarnPy3k("compileast is removed in 3.x; use compilest", 1) < 0)
478 return NULL;
479 return parser_compilest(self, args, kw);
480 }
481
482
483 /* PyObject* parser_isexpr(PyObject* self, PyObject* args)
484 * PyObject* parser_issuite(PyObject* self, PyObject* args)
485 *
486 * Checks the passed-in ST object to determine if it is an expression or
487 * a statement suite, respectively. The return is a Python truth value.
488 *
489 */
490 static PyObject*
491 parser_isexpr(PyST_Object *self, PyObject *args, PyObject *kw)
492 {
493 PyObject* res = 0;
494 int ok;
495
496 static char *keywords[] = {"ast", NULL};
497
498 if (self == NULL)
499 ok = PyArg_ParseTupleAndKeywords(args, kw, "O!:isexpr", keywords,
500 &PyST_Type, &self);
501 else
502 ok = PyArg_ParseTupleAndKeywords(args, kw, ":isexpr", &keywords[1]);
503
504 if (ok) {
505 /* Check to see if the ST represents an expression or not. */
506 res = (self->st_type == PyST_EXPR) ? Py_True : Py_False;
507 Py_INCREF(res);
508 }
509 return (res);
510 }
511
512
513 static PyObject*
514 parser_issuite(PyST_Object *self, PyObject *args, PyObject *kw)
515 {
516 PyObject* res = 0;
517 int ok;
518
519 static char *keywords[] = {"ast", NULL};
520
521 if (self == NULL)
522 ok = PyArg_ParseTupleAndKeywords(args, kw, "O!:issuite", keywords,
523 &PyST_Type, &self);
524 else
525 ok = PyArg_ParseTupleAndKeywords(args, kw, ":issuite", &keywords[1]);
526
527 if (ok) {
528 /* Check to see if the ST represents an expression or not. */
529 res = (self->st_type == PyST_EXPR) ? Py_False : Py_True;
530 Py_INCREF(res);
531 }
532 return (res);
533 }
534
535
536 static PyObject*
537 parser_getattr(PyObject *self, char *name)
538 {
539 return (Py_FindMethod(parser_methods, self, name));
540 }
541
542
543 /* err_string(char* message)
544 *
545 * Sets the error string for an exception of type ParserError.
546 *
547 */
548 static void
549 err_string(char *message)
550 {
551 PyErr_SetString(parser_error, message);
552 }
553
554
555 /* PyObject* parser_do_parse(PyObject* args, int type)
556 *
557 * Internal function to actually execute the parse and return the result if
558 * successful or set an exception if not.
559 *
560 */
561 static PyObject*
562 parser_do_parse(PyObject *args, PyObject *kw, char *argspec, int type)
563 {
564 char* string = 0;
565 PyObject* res = 0;
566 int flags = 0;
567 perrdetail err;
568
569 static char *keywords[] = {"source", NULL};
570
571 if (PyArg_ParseTupleAndKeywords(args, kw, argspec, keywords, &string)) {
572 node* n = PyParser_ParseStringFlagsFilenameEx(string, NULL,
573 &_PyParser_Grammar,
574 (type == PyST_EXPR)
575 ? eval_input : file_input,
576 &err, &flags);
577
578 if (n) {
579 res = parser_newstobject(n, type);
580 if (res)
581 ((PyST_Object *)res)->st_flags.cf_flags = flags & PyCF_MASK;
582 }
583 else
584 PyParser_SetError(&err);
585 }
586 return (res);
587 }
588
589
590 /* PyObject* parser_expr(PyObject* self, PyObject* args)
591 * PyObject* parser_suite(PyObject* self, PyObject* args)
592 *
593 * External interfaces to the parser itself. Which is called determines if
594 * the parser attempts to recognize an expression ('eval' form) or statement
595 * suite ('exec' form). The real work is done by parser_do_parse() above.
596 *
597 */
598 static PyObject*
599 parser_expr(PyST_Object *self, PyObject *args, PyObject *kw)
600 {
601 NOTE(ARGUNUSED(self))
602 return (parser_do_parse(args, kw, "s:expr", PyST_EXPR));
603 }
604
605
606 static PyObject*
607 parser_suite(PyST_Object *self, PyObject *args, PyObject *kw)
608 {
609 NOTE(ARGUNUSED(self))
610 return (parser_do_parse(args, kw, "s:suite", PyST_SUITE));
611 }
612
613
614
615 /* This is the messy part of the code. Conversion from a tuple to an ST
616 * object requires that the input tuple be valid without having to rely on
617 * catching an exception from the compiler. This is done to allow the
618 * compiler itself to remain fast, since most of its input will come from
619 * the parser directly, and therefore be known to be syntactically correct.
620 * This validation is done to ensure that we don't core dump the compile
621 * phase, returning an exception instead.
622 *
623 * Two aspects can be broken out in this code: creating a node tree from
624 * the tuple passed in, and verifying that it is indeed valid. It may be
625 * advantageous to expand the number of ST types to include funcdefs and
626 * lambdadefs to take advantage of the optimizer, recognizing those STs
627 * here. They are not necessary, and not quite as useful in a raw form.
628 * For now, let's get expressions and suites working reliably.
629 */
630
631
632 static node* build_node_tree(PyObject *tuple);
633 static int validate_expr_tree(node *tree);
634 static int validate_file_input(node *tree);
635 static int validate_encoding_decl(node *tree);
636
637 /* PyObject* parser_tuple2st(PyObject* self, PyObject* args)
638 *
639 * This is the public function, called from the Python code. It receives a
640 * single tuple object from the caller, and creates an ST object if the
641 * tuple can be validated. It does this by checking the first code of the
642 * tuple, and, if acceptable, builds the internal representation. If this
643 * step succeeds, the internal representation is validated as fully as
644 * possible with the various validate_*() routines defined below.
645 *
646 * This function must be changed if support is to be added for PyST_FRAGMENT
647 * ST objects.
648 *
649 */
650 static PyObject*
651 parser_tuple2st(PyST_Object *self, PyObject *args, PyObject *kw)
652 {
653 NOTE(ARGUNUSED(self))
654 PyObject *st = 0;
655 PyObject *tuple;
656 node *tree;
657
658 static char *keywords[] = {"sequence", NULL};
659
660 if (!PyArg_ParseTupleAndKeywords(args, kw, "O:sequence2st", keywords,
661 &tuple))
662 return (0);
663 if (!PySequence_Check(tuple)) {
664 PyErr_SetString(PyExc_ValueError,
665 "sequence2st() requires a single sequence argument");
666 return (0);
667 }
668 /*
669 * Convert the tree to the internal form before checking it.
670 */
671 tree = build_node_tree(tuple);
672 if (tree != 0) {
673 int start_sym = TYPE(tree);
674 if (start_sym == eval_input) {
675 /* Might be an eval form. */
676 if (validate_expr_tree(tree))
677 st = parser_newstobject(tree, PyST_EXPR);
678 else
679 PyNode_Free(tree);
680 }
681 else if (start_sym == file_input) {
682 /* This looks like an exec form so far. */
683 if (validate_file_input(tree))
684 st = parser_newstobject(tree, PyST_SUITE);
685 else
686 PyNode_Free(tree);
687 }
688 else if (start_sym == encoding_decl) {
689 /* This looks like an encoding_decl so far. */
690 if (validate_encoding_decl(tree))
691 st = parser_newstobject(tree, PyST_SUITE);
692 else
693 PyNode_Free(tree);
694 }
695 else {
696 /* This is a fragment, at best. */
697 PyNode_Free(tree);
698 err_string("parse tree does not use a valid start symbol");
699 }
700 }
701 /* Make sure we raise an exception on all errors. We should never
702 * get this, but we'd do well to be sure something is done.
703 */
704 if (st == NULL && !PyErr_Occurred())
705 err_string("unspecified ST error occurred");
706
707 return st;
708 }
709
710 static PyObject*
711 parser_tuple2ast(PyST_Object *self, PyObject *args, PyObject *kw)
712 {
713 if (PyErr_WarnPy3k("tuple2ast is removed in 3.x; use tuple2st", 1) < 0)
714 return NULL;
715 return parser_tuple2st(self, args, kw);
716 }
717
718 static PyObject *
719 parser_sizeof(PyST_Object *st, void *unused)
720 {
721 Py_ssize_t res;
722
723 res = _PyObject_SIZE(Py_TYPE(st)) + _PyNode_SizeOf(st->st_node);
724 return PyLong_FromSsize_t(res);
725 }
726
727
728 /* node* build_node_children()
729 *
730 * Iterate across the children of the current non-terminal node and build
731 * their structures. If successful, return the root of this portion of
732 * the tree, otherwise, 0. Any required exception will be specified already,
733 * and no memory will have been deallocated.
734 *
735 */
736 static node*
737 build_node_children(PyObject *tuple, node *root, int *line_num)
738 {
739 Py_ssize_t len = PyObject_Size(tuple);
740 Py_ssize_t i;
741 int err;
742
743 if (len < 0) {
744 return NULL;
745 }
746 for (i = 1; i < len; ++i) {
747 /* elem must always be a sequence, however simple */
748 PyObject* elem = PySequence_GetItem(tuple, i);
749 int ok = elem != NULL;
750 long type = 0;
751 char *strn = 0;
752
753 if (ok)
754 ok = PySequence_Check(elem);
755 if (ok) {
756 PyObject *temp = PySequence_GetItem(elem, 0);
757 if (temp == NULL)
758 ok = 0;
759 else {
760 ok = PyInt_Check(temp);
761 if (ok)
762 type = PyInt_AS_LONG(temp);
763 Py_DECREF(temp);
764 }
765 }
766 if (!ok) {
767 PyObject *err = Py_BuildValue("os", elem,
768 "Illegal node construct.");
769 PyErr_SetObject(parser_error, err);
770 Py_XDECREF(err);
771 Py_XDECREF(elem);
772 return NULL;
773 }
774 if (ISTERMINAL(type)) {
775 Py_ssize_t len = PyObject_Size(elem);
776 PyObject *temp;
777
778 if ((len != 2) && (len != 3)) {
779 err_string("terminal nodes must have 2 or 3 entries");
780 Py_DECREF(elem);
781 return NULL;
782 }
783 temp = PySequence_GetItem(elem, 1);
784 if (temp == NULL) {
785 Py_DECREF(elem);
786 return NULL;
787 }
788 if (!PyString_Check(temp)) {
789 PyErr_Format(parser_error,
790 "second item in terminal node must be a string,"
791 " found %s",
792 Py_TYPE(temp)->tp_name);
793 Py_DECREF(temp);
794 Py_DECREF(elem);
795 return NULL;
796 }
797 if (len == 3) {
798 PyObject *o = PySequence_GetItem(elem, 2);
799 if (o == NULL) {
800 Py_DECREF(temp);
801 Py_DECREF(elem);
802 return NULL;
803 }
804 if (PyInt_Check(o))
805 *line_num = PyInt_AS_LONG(o);
806 else {
807 PyErr_Format(parser_error,
808 "third item in terminal node must be an"
809 " integer, found %s",
810 Py_TYPE(temp)->tp_name);
811 Py_DECREF(o);
812 Py_DECREF(temp);
813 Py_DECREF(elem);
814 return NULL;
815 }
816 Py_DECREF(o);
817 }
818 len = PyString_GET_SIZE(temp) + 1;
819 strn = (char *)PyObject_MALLOC(len);
820 if (strn == NULL) {
821 Py_DECREF(temp);
822 Py_DECREF(elem);
823 PyErr_NoMemory();
824 return NULL;
825 }
826 (void) memcpy(strn, PyString_AS_STRING(temp), len);
827 Py_DECREF(temp);
828 }
829 else if (!ISNONTERMINAL(type)) {
830 /*
831 * It has to be one or the other; this is an error.
832 * Raise an exception.
833 */
834 PyObject *err = Py_BuildValue("Os", elem, "unknown node type.");
835 PyErr_SetObject(parser_error, err);
836 Py_XDECREF(err);
837 Py_DECREF(elem);
838 return NULL;
839 }
840 err = PyNode_AddChild(root, type, strn, *line_num, 0);
841 if (err == E_NOMEM) {
842 Py_DECREF(elem);
843 PyObject_FREE(strn);
844 PyErr_NoMemory();
845 return NULL;
846 }
847 if (err == E_OVERFLOW) {
848 Py_DECREF(elem);
849 PyObject_FREE(strn);
850 PyErr_SetString(PyExc_ValueError,
851 "unsupported number of child nodes");
852 return NULL;
853 }
854
855 if (ISNONTERMINAL(type)) {
856 node* new_child = CHILD(root, i - 1);
857
858 if (new_child != build_node_children(elem, new_child, line_num)) {
859 Py_DECREF(elem);
860 return NULL;
861 }
862 }
863 else if (type == NEWLINE) { /* It's true: we increment the */
864 ++(*line_num); /* line number *after* the newline! */
865 }
866 Py_DECREF(elem);
867 }
868 return root;
869 }
870
871
872 static node*
873 build_node_tree(PyObject *tuple)
874 {
875 node* res = 0;
876 PyObject *temp = PySequence_GetItem(tuple, 0);
877 long num = -1;
878
879 if (temp != NULL)
880 num = PyInt_AsLong(temp);
881 Py_XDECREF(temp);
882 if (ISTERMINAL(num)) {
883 /*
884 * The tuple is simple, but it doesn't start with a start symbol.
885 * Raise an exception now and be done with it.
886 */
887 tuple = Py_BuildValue("os", tuple,
888 "Illegal syntax-tree; cannot start with terminal symbol.");
889 PyErr_SetObject(parser_error, tuple);
890 Py_XDECREF(tuple);
891 }
892 else if (ISNONTERMINAL(num)) {
893 /*
894 * Not efficient, but that can be handled later.
895 */
896 int line_num = 0;
897 PyObject *encoding = NULL;
898
899 if (num == encoding_decl) {
900 encoding = PySequence_GetItem(tuple, 2);
901 if (encoding == NULL) {
902 PyErr_SetString(parser_error, "missed encoding");
903 return NULL;
904 }
905 if (!PyString_Check(encoding)) {
906 PyErr_Format(parser_error,
907 "encoding must be a string, found %.200s",
908 Py_TYPE(encoding)->tp_name);
909 Py_DECREF(encoding);
910 return NULL;
911 }
912 /* tuple isn't borrowed anymore here, need to DECREF */
913 tuple = PySequence_GetSlice(tuple, 0, 2);
914 if (tuple == NULL) {
915 Py_DECREF(encoding);
916 return NULL;
917 }
918 }
919 res = PyNode_New(num);
920 if (res != NULL) {
921 if (res != build_node_children(tuple, res, &line_num)) {
922 PyNode_Free(res);
923 res = NULL;
924 }
925 if (res && encoding) {
926 Py_ssize_t len;
927 len = PyString_GET_SIZE(encoding) + 1;
928 res->n_str = (char *)PyObject_MALLOC(len);
929 if (res->n_str == NULL) {
930 PyNode_Free(res);
931 Py_DECREF(encoding);
932 Py_DECREF(tuple);
933 PyErr_NoMemory();
934 return NULL;
935 }
936 (void) memcpy(res->n_str, PyString_AS_STRING(encoding), len);
937 }
938 }
939 if (encoding != NULL) {
940 Py_DECREF(encoding);
941 Py_DECREF(tuple);
942 }
943 }
944 else {
945 /* The tuple is illegal -- if the number is neither TERMINAL nor
946 * NONTERMINAL, we can't use it. Not sure the implementation
947 * allows this condition, but the API doesn't preclude it.
948 */
949 PyObject *err = Py_BuildValue("Os", tuple,
950 "Illegal component tuple.");
951 PyErr_SetObject(parser_error, err);
952 Py_XDECREF(err);
953 }
954
955 return (res);
956 }
957
958
959 /*
960 * Validation routines used within the validation section:
961 */
962 static int validate_terminal(node *terminal, int type, char *string);
963
964 #define validate_ampersand(ch) validate_terminal(ch, AMPER, "&")
965 #define validate_circumflex(ch) validate_terminal(ch, CIRCUMFLEX, "^")
966 #define validate_colon(ch) validate_terminal(ch, COLON, ":")
967 #define validate_comma(ch) validate_terminal(ch, COMMA, ",")
968 #define validate_dedent(ch) validate_terminal(ch, DEDENT, "")
969 #define validate_equal(ch) validate_terminal(ch, EQUAL, "=")
970 #define validate_indent(ch) validate_terminal(ch, INDENT, (char*)NULL)
971 #define validate_lparen(ch) validate_terminal(ch, LPAR, "(")
972 #define validate_newline(ch) validate_terminal(ch, NEWLINE, (char*)NULL)
973 #define validate_rparen(ch) validate_terminal(ch, RPAR, ")")
974 #define validate_semi(ch) validate_terminal(ch, SEMI, ";")
975 #define validate_star(ch) validate_terminal(ch, STAR, "*")
976 #define validate_vbar(ch) validate_terminal(ch, VBAR, "|")
977 #define validate_doublestar(ch) validate_terminal(ch, DOUBLESTAR, "**")
978 #define validate_dot(ch) validate_terminal(ch, DOT, ".")
979 #define validate_at(ch) validate_terminal(ch, AT, "@")
980 #define validate_name(ch, str) validate_terminal(ch, NAME, str)
981
982 #define VALIDATER(n) static int validate_##n(node *tree)
983
984 VALIDATER(node); VALIDATER(small_stmt);
985 VALIDATER(class); VALIDATER(node);
986 VALIDATER(parameters); VALIDATER(suite);
987 VALIDATER(testlist); VALIDATER(varargslist);
988 VALIDATER(fpdef); VALIDATER(fplist);
989 VALIDATER(stmt); VALIDATER(simple_stmt);
990 VALIDATER(expr_stmt); VALIDATER(power);
991 VALIDATER(print_stmt); VALIDATER(del_stmt);
992 VALIDATER(return_stmt); VALIDATER(list_iter);
993 VALIDATER(raise_stmt); VALIDATER(import_stmt);
994 VALIDATER(import_name); VALIDATER(import_from);
995 VALIDATER(global_stmt); VALIDATER(list_if);
996 VALIDATER(assert_stmt); VALIDATER(list_for);
997 VALIDATER(exec_stmt); VALIDATER(compound_stmt);
998 VALIDATER(while); VALIDATER(for);
999 VALIDATER(try); VALIDATER(except_clause);
1000 VALIDATER(test); VALIDATER(and_test);
1001 VALIDATER(not_test); VALIDATER(comparison);
1002 VALIDATER(comp_op); VALIDATER(expr);
1003 VALIDATER(xor_expr); VALIDATER(and_expr);
1004 VALIDATER(shift_expr); VALIDATER(arith_expr);
1005 VALIDATER(term); VALIDATER(factor);
1006 VALIDATER(atom); VALIDATER(lambdef);
1007 VALIDATER(trailer); VALIDATER(subscript);
1008 VALIDATER(subscriptlist); VALIDATER(sliceop);
1009 VALIDATER(exprlist); VALIDATER(dictorsetmaker);
1010 VALIDATER(arglist); VALIDATER(argument);
1011 VALIDATER(listmaker); VALIDATER(yield_stmt);
1012 VALIDATER(testlist1); VALIDATER(comp_for);
1013 VALIDATER(comp_iter); VALIDATER(comp_if);
1014 VALIDATER(testlist_comp); VALIDATER(yield_expr);
1015 VALIDATER(yield_or_testlist); VALIDATER(or_test);
1016 VALIDATER(old_test); VALIDATER(old_lambdef);
1017
1018 #undef VALIDATER
1019
1020 #define is_even(n) (((n) & 1) == 0)
1021 #define is_odd(n) (((n) & 1) == 1)
1022
1023
1024 static int
1025 validate_ntype(node *n, int t)
1026 {
1027 if (TYPE(n) != t) {
1028 PyErr_Format(parser_error, "Expected node type %d, got %d.",
1029 t, TYPE(n));
1030 return 0;
1031 }
1032 return 1;
1033 }
1034
1035
1036 /* Verifies that the number of child nodes is exactly 'num', raising
1037 * an exception if it isn't. The exception message does not indicate
1038 * the exact number of nodes, allowing this to be used to raise the
1039 * "right" exception when the wrong number of nodes is present in a
1040 * specific variant of a statement's syntax. This is commonly used
1041 * in that fashion.
1042 */
1043 static int
1044 validate_numnodes(node *n, int num, const char *const name)
1045 {
1046 if (NCH(n) != num) {
1047 PyErr_Format(parser_error,
1048 "Illegal number of children for %s node.", name);
1049 return 0;
1050 }
1051 return 1;
1052 }
1053
1054
1055 static int
1056 validate_terminal(node *terminal, int type, char *string)
1057 {
1058 if (!validate_ntype(terminal, type)) {
1059 return 0;
1060 }
1061 if (string != NULL && strcmp(string, STR(terminal)) != 0) {
1062 PyErr_Format(parser_error,
1063 "Illegal terminal: expected \"%s\"", string);
1064 return 0;
1065 }
1066 return 1;
1067 }
1068
1069
1070 /* X (',' X) [',']
1071 */
1072 static int
1073 validate_repeating_list(node *tree, int ntype, int (*vfunc)(node *),
1074 const char *const name)
1075 {
1076 int nch = NCH(tree);
1077 int res = (nch && validate_ntype(tree, ntype)
1078 && vfunc(CHILD(tree, 0)));
1079
1080 if (!res && !PyErr_Occurred())
1081 (void) validate_numnodes(tree, 1, name);
1082 else {
1083 if (is_even(nch))
1084 res = validate_comma(CHILD(tree, --nch));
1085 if (res && nch > 1) {
1086 int pos = 1;
1087 for ( ; res && pos < nch; pos += 2)
1088 res = (validate_comma(CHILD(tree, pos))
1089 && vfunc(CHILD(tree, pos + 1)));
1090 }
1091 }
1092 return (res);
1093 }
1094
1095
1096 /* validate_class()
1097 *
1098 * classdef:
1099 * 'class' NAME ['(' testlist ')'] ':' suite
1100 */
1101 static int
1102 validate_class(node *tree)
1103 {
1104 int nch = NCH(tree);
1105 int res = (validate_ntype(tree, classdef) &&
1106 ((nch == 4) || (nch == 6) || (nch == 7)));
1107
1108 if (res) {
1109 res = (validate_name(CHILD(tree, 0), "class")
1110 && validate_ntype(CHILD(tree, 1), NAME)
1111 && validate_colon(CHILD(tree, nch - 2))
1112 && validate_suite(CHILD(tree, nch - 1)));
1113 }
1114 else {
1115 (void) validate_numnodes(tree, 4, "class");
1116 }
1117
1118 if (res) {
1119 if (nch == 7) {
1120 res = ((validate_lparen(CHILD(tree, 2)) &&
1121 validate_testlist(CHILD(tree, 3)) &&
1122 validate_rparen(CHILD(tree, 4))));
1123 }
1124 else if (nch == 6) {
1125 res = (validate_lparen(CHILD(tree,2)) &&
1126 validate_rparen(CHILD(tree,3)));
1127 }
1128 }
1129 return (res);
1130 }
1131
1132
1133 /* if_stmt:
1134 * 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
1135 */
1136 static int
1137 validate_if(node *tree)
1138 {
1139 int nch = NCH(tree);
1140 int res = (validate_ntype(tree, if_stmt)
1141 && (nch >= 4)
1142 && validate_name(CHILD(tree, 0), "if")
1143 && validate_test(CHILD(tree, 1))
1144 && validate_colon(CHILD(tree, 2))
1145 && validate_suite(CHILD(tree, 3)));
1146
1147 if (res && ((nch % 4) == 3)) {
1148 /* ... 'else' ':' suite */
1149 res = (validate_name(CHILD(tree, nch - 3), "else")
1150 && validate_colon(CHILD(tree, nch - 2))
1151 && validate_suite(CHILD(tree, nch - 1)));
1152 nch -= 3;
1153 }
1154 else if (!res && !PyErr_Occurred())
1155 (void) validate_numnodes(tree, 4, "if");
1156 if ((nch % 4) != 0)
1157 /* Will catch the case for nch < 4 */
1158 res = validate_numnodes(tree, 0, "if");
1159 else if (res && (nch > 4)) {
1160 /* ... ('elif' test ':' suite)+ ... */
1161 int j = 4;
1162 while ((j < nch) && res) {
1163 res = (validate_name(CHILD(tree, j), "elif")
1164 && validate_colon(CHILD(tree, j + 2))
1165 && validate_test(CHILD(tree, j + 1))
1166 && validate_suite(CHILD(tree, j + 3)));
1167 j += 4;
1168 }
1169 }
1170 return (res);
1171 }
1172
1173
1174 /* parameters:
1175 * '(' [varargslist] ')'
1176 *
1177 */
1178 static int
1179 validate_parameters(node *tree)
1180 {
1181 int nch = NCH(tree);
1182 int res = validate_ntype(tree, parameters) && ((nch == 2) || (nch == 3));
1183
1184 if (res) {
1185 res = (validate_lparen(CHILD(tree, 0))
1186 && validate_rparen(CHILD(tree, nch - 1)));
1187 if (res && (nch == 3))
1188 res = validate_varargslist(CHILD(tree, 1));
1189 }
1190 else {
1191 (void) validate_numnodes(tree, 2, "parameters");
1192 }
1193 return (res);
1194 }
1195
1196
1197 /* validate_suite()
1198 *
1199 * suite:
1200 * simple_stmt
1201 * | NEWLINE INDENT stmt+ DEDENT
1202 */
1203 static int
1204 validate_suite(node *tree)
1205 {
1206 int nch = NCH(tree);
1207 int res = (validate_ntype(tree, suite) && ((nch == 1) || (nch >= 4)));
1208
1209 if (res && (nch == 1))
1210 res = validate_simple_stmt(CHILD(tree, 0));
1211 else if (res) {
1212 /* NEWLINE INDENT stmt+ DEDENT */
1213 res = (validate_newline(CHILD(tree, 0))
1214 && validate_indent(CHILD(tree, 1))
1215 && validate_stmt(CHILD(tree, 2))
1216 && validate_dedent(CHILD(tree, nch - 1)));
1217
1218 if (res && (nch > 4)) {
1219 int i = 3;
1220 --nch; /* forget the DEDENT */
1221 for ( ; res && (i < nch); ++i)
1222 res = validate_stmt(CHILD(tree, i));
1223 }
1224 else if (nch < 4)
1225 res = validate_numnodes(tree, 4, "suite");
1226 }
1227 return (res);
1228 }
1229
1230
1231 static int
1232 validate_testlist(node *tree)
1233 {
1234 return (validate_repeating_list(tree, testlist,
1235 validate_test, "testlist"));
1236 }
1237
1238
1239 static int
1240 validate_testlist1(node *tree)
1241 {
1242 return (validate_repeating_list(tree, testlist1,
1243 validate_test, "testlist1"));
1244 }
1245
1246
1247 static int
1248 validate_testlist_safe(node *tree)
1249 {
1250 return (validate_repeating_list(tree, testlist_safe,
1251 validate_old_test, "testlist_safe"));
1252 }
1253
1254
1255 /* '*' NAME [',' '**' NAME] | '**' NAME
1256 */
1257 static int
1258 validate_varargslist_trailer(node *tree, int start)
1259 {
1260 int nch = NCH(tree);
1261 int res = 0;
1262 int sym;
1263
1264 if (nch <= start) {
1265 err_string("expected variable argument trailer for varargslist");
1266 return 0;
1267 }
1268 sym = TYPE(CHILD(tree, start));
1269 if (sym == STAR) {
1270 /*
1271 * ('*' NAME [',' '**' NAME]
1272 */
1273 if (nch-start == 2)
1274 res = validate_name(CHILD(tree, start+1), NULL);
1275 else if (nch-start == 5)
1276 res = (validate_name(CHILD(tree, start+1), NULL)
1277 && validate_comma(CHILD(tree, start+2))
1278 && validate_doublestar(CHILD(tree, start+3))
1279 && validate_name(CHILD(tree, start+4), NULL));
1280 }
1281 else if (sym == DOUBLESTAR) {
1282 /*
1283 * '**' NAME
1284 */
1285 if (nch-start == 2)
1286 res = validate_name(CHILD(tree, start+1), NULL);
1287 }
1288 if (!res)
1289 err_string("illegal variable argument trailer for varargslist");
1290 return res;
1291 }
1292
1293
1294 /* validate_varargslist()
1295 *
1296 * varargslist:
1297 * (fpdef ['=' test] ',')*
1298 * ('*' NAME [',' '**' NAME]
1299 * | '**' NAME)
1300 * | fpdef ['=' test] (',' fpdef ['=' test])* [',']
1301 *
1302 */
1303 static int
1304 validate_varargslist(node *tree)
1305 {
1306 int nch = NCH(tree);
1307 int res = validate_ntype(tree, varargslist) && (nch != 0);
1308 int sym;
1309
1310 if (!res)
1311 return 0;
1312 if (nch < 1) {
1313 err_string("varargslist missing child nodes");
1314 return 0;
1315 }
1316 sym = TYPE(CHILD(tree, 0));
1317 if (sym == STAR || sym == DOUBLESTAR)
1318 /* whole thing matches:
1319 * '*' NAME [',' '**' NAME] | '**' NAME
1320 */
1321 res = validate_varargslist_trailer(tree, 0);
1322 else if (sym == fpdef) {
1323 int i = 0;
1324
1325 sym = TYPE(CHILD(tree, nch-1));
1326 if (sym == NAME) {
1327 /*
1328 * (fpdef ['=' test] ',')+
1329 * ('*' NAME [',' '**' NAME]
1330 * | '**' NAME)
1331 */
1332 /* skip over (fpdef ['=' test] ',')+ */
1333 while (res && (i+2 <= nch)) {
1334 res = validate_fpdef(CHILD(tree, i));
1335 ++i;
1336 if (res && TYPE(CHILD(tree, i)) == EQUAL && (i+2 <= nch)) {
1337 res = (validate_equal(CHILD(tree, i))
1338 && validate_test(CHILD(tree, i+1)));
1339 if (res)
1340 i += 2;
1341 }
1342 if (res && i < nch) {
1343 res = validate_comma(CHILD(tree, i));
1344 ++i;
1345 if (res && i < nch
1346 && (TYPE(CHILD(tree, i)) == DOUBLESTAR
1347 || TYPE(CHILD(tree, i)) == STAR))
1348 break;
1349 }
1350 }
1351 /* ... '*' NAME [',' '**' NAME] | '**' NAME
1352 * i --^^^
1353 */
1354 if (res)
1355 res = validate_varargslist_trailer(tree, i);
1356 }
1357 else {
1358 /*
1359 * fpdef ['=' test] (',' fpdef ['=' test])* [',']
1360 */
1361 /* strip trailing comma node */
1362 if (sym == COMMA) {
1363 res = validate_comma(CHILD(tree, nch-1));
1364 if (!res)
1365 return 0;
1366 --nch;
1367 }
1368 /*
1369 * fpdef ['=' test] (',' fpdef ['=' test])*
1370 */
1371 res = validate_fpdef(CHILD(tree, 0));
1372 ++i;
1373 if (res && (i+2 <= nch) && TYPE(CHILD(tree, i)) == EQUAL) {
1374 res = (validate_equal(CHILD(tree, i))
1375 && validate_test(CHILD(tree, i+1)));
1376 i += 2;
1377 }
1378 /*
1379 * ... (',' fpdef ['=' test])*
1380 * i ---^^^
1381 */
1382 while (res && (nch - i) >= 2) {
1383 res = (validate_comma(CHILD(tree, i))
1384 && validate_fpdef(CHILD(tree, i+1)));
1385 i += 2;
1386 if (res && (nch - i) >= 2 && TYPE(CHILD(tree, i)) == EQUAL) {
1387 res = (validate_equal(CHILD(tree, i))
1388 && validate_test(CHILD(tree, i+1)));
1389 i += 2;
1390 }
1391 }
1392 if (res && nch - i != 0) {
1393 res = 0;
1394 err_string("illegal formation for varargslist");
1395 }
1396 }
1397 }
1398 return res;
1399 }
1400
1401
1402 /* list_iter: list_for | list_if
1403 */
1404 static int
1405 validate_list_iter(node *tree)
1406 {
1407 int res = (validate_ntype(tree, list_iter)
1408 && validate_numnodes(tree, 1, "list_iter"));
1409 if (res && TYPE(CHILD(tree, 0)) == list_for)
1410 res = validate_list_for(CHILD(tree, 0));
1411 else
1412 res = validate_list_if(CHILD(tree, 0));
1413
1414 return res;
1415 }
1416
1417 /* comp_iter: comp_for | comp_if
1418 */
1419 static int
1420 validate_comp_iter(node *tree)
1421 {
1422 int res = (validate_ntype(tree, comp_iter)
1423 && validate_numnodes(tree, 1, "comp_iter"));
1424 if (res && TYPE(CHILD(tree, 0)) == comp_for)
1425 res = validate_comp_for(CHILD(tree, 0));
1426 else
1427 res = validate_comp_if(CHILD(tree, 0));
1428
1429 return res;
1430 }
1431
1432 /* list_for: 'for' exprlist 'in' testlist [list_iter]
1433 */
1434 static int
1435 validate_list_for(node *tree)
1436 {
1437 int nch = NCH(tree);
1438 int res;
1439
1440 if (nch == 5)
1441 res = validate_list_iter(CHILD(tree, 4));
1442 else
1443 res = validate_numnodes(tree, 4, "list_for");
1444
1445 if (res)
1446 res = (validate_name(CHILD(tree, 0), "for")
1447 && validate_exprlist(CHILD(tree, 1))
1448 && validate_name(CHILD(tree, 2), "in")
1449 && validate_testlist_safe(CHILD(tree, 3)));
1450
1451 return res;
1452 }
1453
1454 /* comp_for: 'for' exprlist 'in' test [comp_iter]
1455 */
1456 static int
1457 validate_comp_for(node *tree)
1458 {
1459 int nch = NCH(tree);
1460 int res;
1461
1462 if (nch == 5)
1463 res = validate_comp_iter(CHILD(tree, 4));
1464 else
1465 res = validate_numnodes(tree, 4, "comp_for");
1466
1467 if (res)
1468 res = (validate_name(CHILD(tree, 0), "for")
1469 && validate_exprlist(CHILD(tree, 1))
1470 && validate_name(CHILD(tree, 2), "in")
1471 && validate_or_test(CHILD(tree, 3)));
1472
1473 return res;
1474 }
1475
1476 /* list_if: 'if' old_test [list_iter]
1477 */
1478 static int
1479 validate_list_if(node *tree)
1480 {
1481 int nch = NCH(tree);
1482 int res;
1483
1484 if (nch == 3)
1485 res = validate_list_iter(CHILD(tree, 2));
1486 else
1487 res = validate_numnodes(tree, 2, "list_if");
1488
1489 if (res)
1490 res = (validate_name(CHILD(tree, 0), "if")
1491 && validate_old_test(CHILD(tree, 1)));
1492
1493 return res;
1494 }
1495
1496 /* comp_if: 'if' old_test [comp_iter]
1497 */
1498 static int
1499 validate_comp_if(node *tree)
1500 {
1501 int nch = NCH(tree);
1502 int res;
1503
1504 if (nch == 3)
1505 res = validate_comp_iter(CHILD(tree, 2));
1506 else
1507 res = validate_numnodes(tree, 2, "comp_if");
1508
1509 if (res)
1510 res = (validate_name(CHILD(tree, 0), "if")
1511 && validate_old_test(CHILD(tree, 1)));
1512
1513 return res;
1514 }
1515
1516 /* validate_fpdef()
1517 *
1518 * fpdef:
1519 * NAME
1520 * | '(' fplist ')'
1521 */
1522 static int
1523 validate_fpdef(node *tree)
1524 {
1525 int nch = NCH(tree);
1526 int res = validate_ntype(tree, fpdef);
1527
1528 if (res) {
1529 if (nch == 1)
1530 res = validate_ntype(CHILD(tree, 0), NAME);
1531 else if (nch == 3)
1532 res = (validate_lparen(CHILD(tree, 0))
1533 && validate_fplist(CHILD(tree, 1))
1534 && validate_rparen(CHILD(tree, 2)));
1535 else
1536 res = validate_numnodes(tree, 1, "fpdef");
1537 }
1538 return (res);
1539 }
1540
1541
1542 static int
1543 validate_fplist(node *tree)
1544 {
1545 return (validate_repeating_list(tree, fplist,
1546 validate_fpdef, "fplist"));
1547 }
1548
1549
1550 /* simple_stmt | compound_stmt
1551 *
1552 */
1553 static int
1554 validate_stmt(node *tree)
1555 {
1556 int res = (validate_ntype(tree, stmt)
1557 && validate_numnodes(tree, 1, "stmt"));
1558
1559 if (res) {
1560 tree = CHILD(tree, 0);
1561
1562 if (TYPE(tree) == simple_stmt)
1563 res = validate_simple_stmt(tree);
1564 else
1565 res = validate_compound_stmt(tree);
1566 }
1567 return (res);
1568 }
1569
1570
1571 /* small_stmt (';' small_stmt)* [';'] NEWLINE
1572 *
1573 */
1574 static int
1575 validate_simple_stmt(node *tree)
1576 {
1577 int nch = NCH(tree);
1578 int res = (validate_ntype(tree, simple_stmt)
1579 && (nch >= 2)
1580 && validate_small_stmt(CHILD(tree, 0))
1581 && validate_newline(CHILD(tree, nch - 1)));
1582
1583 if (nch < 2)
1584 res = validate_numnodes(tree, 2, "simple_stmt");
1585 --nch; /* forget the NEWLINE */
1586 if (res && is_even(nch))
1587 res = validate_semi(CHILD(tree, --nch));
1588 if (res && (nch > 2)) {
1589 int i;
1590
1591 for (i = 1; res && (i < nch); i += 2)
1592 res = (validate_semi(CHILD(tree, i))
1593 && validate_small_stmt(CHILD(tree, i + 1)));
1594 }
1595 return (res);
1596 }
1597
1598
1599 static int
1600 validate_small_stmt(node *tree)
1601 {
1602 int nch = NCH(tree);
1603 int res = validate_numnodes(tree, 1, "small_stmt");
1604
1605 if (res) {
1606 int ntype = TYPE(CHILD(tree, 0));
1607
1608 if ( (ntype == expr_stmt)
1609 || (ntype == print_stmt)
1610 || (ntype == del_stmt)
1611 || (ntype == pass_stmt)
1612 || (ntype == flow_stmt)
1613 || (ntype == import_stmt)
1614 || (ntype == global_stmt)
1615 || (ntype == assert_stmt)
1616 || (ntype == exec_stmt))
1617 res = validate_node(CHILD(tree, 0));
1618 else {
1619 res = 0;
1620 err_string("illegal small_stmt child type");
1621 }
1622 }
1623 else if (nch == 1) {
1624 res = 0;
1625 PyErr_Format(parser_error,
1626 "Unrecognized child node of small_stmt: %d.",
1627 TYPE(CHILD(tree, 0)));
1628 }
1629 return (res);
1630 }
1631
1632
1633 /* compound_stmt:
1634 * if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated
1635 */
1636 static int
1637 validate_compound_stmt(node *tree)
1638 {
1639 int res = (validate_ntype(tree, compound_stmt)
1640 && validate_numnodes(tree, 1, "compound_stmt"));
1641 int ntype;
1642
1643 if (!res)
1644 return (0);
1645
1646 tree = CHILD(tree, 0);
1647 ntype = TYPE(tree);
1648 if ( (ntype == if_stmt)
1649 || (ntype == while_stmt)
1650 || (ntype == for_stmt)
1651 || (ntype == try_stmt)
1652 || (ntype == with_stmt)
1653 || (ntype == funcdef)
1654 || (ntype == classdef)
1655 || (ntype == decorated))
1656 res = validate_node(tree);
1657 else {
1658 res = 0;
1659 PyErr_Format(parser_error,
1660 "Illegal compound statement type: %d.", TYPE(tree));
1661 }
1662 return (res);
1663 }
1664
1665 static int
1666 validate_yield_or_testlist(node *tree)
1667 {
1668 if (TYPE(tree) == yield_expr)
1669 return validate_yield_expr(tree);
1670 else
1671 return validate_testlist(tree);
1672 }
1673
1674 static int
1675 validate_expr_stmt(node *tree)
1676 {
1677 int j;
1678 int nch = NCH(tree);
1679 int res = (validate_ntype(tree, expr_stmt)
1680 && is_odd(nch)
1681 && validate_testlist(CHILD(tree, 0)));
1682
1683 if (res && nch == 3
1684 && TYPE(CHILD(tree, 1)) == augassign) {
1685 res = validate_numnodes(CHILD(tree, 1), 1, "augassign")
1686 && validate_yield_or_testlist(CHILD(tree, 2));
1687
1688 if (res) {
1689 char *s = STR(CHILD(CHILD(tree, 1), 0));
1690
1691 res = (strcmp(s, "+=") == 0
1692 || strcmp(s, "-=") == 0
1693 || strcmp(s, "*=") == 0
1694 || strcmp(s, "/=") == 0
1695 || strcmp(s, "//=") == 0
1696 || strcmp(s, "%=") == 0
1697 || strcmp(s, "&=") == 0
1698 || strcmp(s, "|=") == 0
1699 || strcmp(s, "^=") == 0
1700 || strcmp(s, "<<=") == 0
1701 || strcmp(s, ">>=") == 0
1702 || strcmp(s, "**=") == 0);
1703 if (!res)
1704 err_string("illegal augmented assignment operator");
1705 }
1706 }
1707 else {
1708 for (j = 1; res && (j < nch); j += 2)
1709 res = validate_equal(CHILD(tree, j))
1710 && validate_yield_or_testlist(CHILD(tree, j + 1));
1711 }
1712 return (res);
1713 }
1714
1715
1716 /* print_stmt:
1717 *
1718 * 'print' ( [ test (',' test)* [','] ]
1719 * | '>>' test [ (',' test)+ [','] ] )
1720 */
1721 static int
1722 validate_print_stmt(node *tree)
1723 {
1724 int nch = NCH(tree);
1725 int res = (validate_ntype(tree, print_stmt)
1726 && (nch > 0)
1727 && validate_name(CHILD(tree, 0), "print"));
1728
1729 if (res && nch > 1) {
1730 int sym = TYPE(CHILD(tree, 1));
1731 int i = 1;
1732 int allow_trailing_comma = 1;
1733
1734 if (sym == test)
1735 res = validate_test(CHILD(tree, i++));
1736 else {
1737 if (nch < 3)
1738 res = validate_numnodes(tree, 3, "print_stmt");
1739 else {
1740 res = (validate_ntype(CHILD(tree, i), RIGHTSHIFT)
1741 && validate_test(CHILD(tree, i+1)));
1742 i += 2;
1743 allow_trailing_comma = 0;
1744 }
1745 }
1746 if (res) {
1747 /* ... (',' test)* [','] */
1748 while (res && i+2 <= nch) {
1749 res = (validate_comma(CHILD(tree, i))
1750 && validate_test(CHILD(tree, i+1)));
1751 allow_trailing_comma = 1;
1752 i += 2;
1753 }
1754 if (res && !allow_trailing_comma)
1755 res = validate_numnodes(tree, i, "print_stmt");
1756 else if (res && i < nch)
1757 res = validate_comma(CHILD(tree, i));
1758 }
1759 }
1760 return (res);
1761 }
1762
1763
1764 static int
1765 validate_del_stmt(node *tree)
1766 {
1767 return (validate_numnodes(tree, 2, "del_stmt")
1768 && validate_name(CHILD(tree, 0), "del")
1769 && validate_exprlist(CHILD(tree, 1)));
1770 }
1771
1772
1773 static int
1774 validate_return_stmt(node *tree)
1775 {
1776 int nch = NCH(tree);
1777 int res = (validate_ntype(tree, return_stmt)
1778 && ((nch == 1) || (nch == 2))
1779 && validate_name(CHILD(tree, 0), "return"));
1780
1781 if (res && (nch == 2))
1782 res = validate_testlist(CHILD(tree, 1));
1783
1784 return (res);
1785 }
1786
1787
1788 static int
1789 validate_raise_stmt(node *tree)
1790 {
1791 int nch = NCH(tree);
1792 int res = (validate_ntype(tree, raise_stmt)
1793 && ((nch == 1) || (nch == 2) || (nch == 4) || (nch == 6)));
1794
1795 if (res) {
1796 res = validate_name(CHILD(tree, 0), "raise");
1797 if (res && (nch >= 2))
1798 res = validate_test(CHILD(tree, 1));
1799 if (res && nch > 2) {
1800 res = (validate_comma(CHILD(tree, 2))
1801 && validate_test(CHILD(tree, 3)));
1802 if (res && (nch > 4))
1803 res = (validate_comma(CHILD(tree, 4))
1804 && validate_test(CHILD(tree, 5)));
1805 }
1806 }
1807 else
1808 (void) validate_numnodes(tree, 2, "raise");
1809 if (res && (nch == 4))
1810 res = (validate_comma(CHILD(tree, 2))
1811 && validate_test(CHILD(tree, 3)));
1812
1813 return (res);
1814 }
1815
1816
1817 /* yield_expr: 'yield' [testlist]
1818 */
1819 static int
1820 validate_yield_expr(node *tree)
1821 {
1822 int nch = NCH(tree);
1823 int res = (validate_ntype(tree, yield_expr)
1824 && ((nch == 1) || (nch == 2))
1825 && validate_name(CHILD(tree, 0), "yield"));
1826
1827 if (res && (nch == 2))
1828 res = validate_testlist(CHILD(tree, 1));
1829
1830 return (res);
1831 }
1832
1833
1834 /* yield_stmt: yield_expr
1835 */
1836 static int
1837 validate_yield_stmt(node *tree)
1838 {
1839 return (validate_ntype(tree, yield_stmt)
1840 && validate_numnodes(tree, 1, "yield_stmt")
1841 && validate_yield_expr(CHILD(tree, 0)));
1842 }
1843
1844
1845 static int
1846 validate_import_as_name(node *tree)
1847 {
1848 int nch = NCH(tree);
1849 int ok = validate_ntype(tree, import_as_name);
1850
1851 if (ok) {
1852 if (nch == 1)
1853 ok = validate_name(CHILD(tree, 0), NULL);
1854 else if (nch == 3)
1855 ok = (validate_name(CHILD(tree, 0), NULL)
1856 && validate_name(CHILD(tree, 1), "as")
1857 && validate_name(CHILD(tree, 2), NULL));
1858 else
1859 ok = validate_numnodes(tree, 3, "import_as_name");
1860 }
1861 return ok;
1862 }
1863
1864
1865 /* dotted_name: NAME ("." NAME)*
1866 */
1867 static int
1868 validate_dotted_name(node *tree)
1869 {
1870 int nch = NCH(tree);
1871 int res = (validate_ntype(tree, dotted_name)
1872 && is_odd(nch)
1873 && validate_name(CHILD(tree, 0), NULL));
1874 int i;
1875
1876 for (i = 1; res && (i < nch); i += 2) {
1877 res = (validate_dot(CHILD(tree, i))
1878 && validate_name(CHILD(tree, i+1), NULL));
1879 }
1880 return res;
1881 }
1882
1883
1884 /* dotted_as_name: dotted_name [NAME NAME]
1885 */
1886 static int
1887 validate_dotted_as_name(node *tree)
1888 {
1889 int nch = NCH(tree);
1890 int res = validate_ntype(tree, dotted_as_name);
1891
1892 if (res) {
1893 if (nch == 1)
1894 res = validate_dotted_name(CHILD(tree, 0));
1895 else if (nch == 3)
1896 res = (validate_dotted_name(CHILD(tree, 0))
1897 && validate_name(CHILD(tree, 1), "as")
1898 && validate_name(CHILD(tree, 2), NULL));
1899 else {
1900 res = 0;
1901 err_string("illegal number of children for dotted_as_name");
1902 }
1903 }
1904 return res;
1905 }
1906
1907
1908 /* dotted_as_name (',' dotted_as_name)* */
1909 static int
1910 validate_dotted_as_names(node *tree)
1911 {
1912 int nch = NCH(tree);
1913 int res = is_odd(nch) && validate_dotted_as_name(CHILD(tree, 0));
1914 int i;
1915
1916 for (i = 1; res && (i < nch); i += 2)
1917 res = (validate_comma(CHILD(tree, i))
1918 && validate_dotted_as_name(CHILD(tree, i + 1)));
1919 return (res);
1920 }
1921
1922
1923 /* import_as_name (',' import_as_name)* [','] */
1924 static int
1925 validate_import_as_names(node *tree)
1926 {
1927 int nch = NCH(tree);
1928 int res = validate_import_as_name(CHILD(tree, 0));
1929 int i;
1930
1931 for (i = 1; res && (i + 1 < nch); i += 2)
1932 res = (validate_comma(CHILD(tree, i))
1933 && validate_import_as_name(CHILD(tree, i + 1)));
1934 return (res);
1935 }
1936
1937
1938 /* 'import' dotted_as_names */
1939 static int
1940 validate_import_name(node *tree)
1941 {
1942 return (validate_ntype(tree, import_name)
1943 && validate_numnodes(tree, 2, "import_name")
1944 && validate_name(CHILD(tree, 0), "import")
1945 && validate_dotted_as_names(CHILD(tree, 1)));
1946 }
1947
1948 /* Helper function to count the number of leading dots in
1949 * 'from ...module import name'
1950 */
1951 static int
1952 count_from_dots(node *tree)
1953 {
1954 int i;
1955 for (i = 1; i < NCH(tree); i++)
1956 if (TYPE(CHILD(tree, i)) != DOT)
1957 break;
1958 return i-1;
1959 }
1960
1961 /* import_from: ('from' ('.'* dotted_name | '.'+)
1962 * 'import' ('*' | '(' import_as_names ')' | import_as_names))
1963 */
1964 static int
1965 validate_import_from(node *tree)
1966 {
1967 int nch = NCH(tree);
1968 int ndots = count_from_dots(tree);
1969 int havename = (TYPE(CHILD(tree, ndots + 1)) == dotted_name);
1970 int offset = ndots + havename;
1971 int res = validate_ntype(tree, import_from)
1972 && (offset >= 1)
1973 && (nch >= 3 + offset)
1974 && validate_name(CHILD(tree, 0), "from")
1975 && (!havename || validate_dotted_name(CHILD(tree, ndots + 1)))
1976 && validate_name(CHILD(tree, offset + 1), "import");
1977
1978 if (res && TYPE(CHILD(tree, offset + 2)) == LPAR)
1979 res = ((nch == offset + 5)
1980 && validate_lparen(CHILD(tree, offset + 2))
1981 && validate_import_as_names(CHILD(tree, offset + 3))
1982 && validate_rparen(CHILD(tree, offset + 4)));
1983 else if (res && TYPE(CHILD(tree, offset + 2)) != STAR)
1984 res = validate_import_as_names(CHILD(tree, offset + 2));
1985 return (res);
1986 }
1987
1988
1989 /* import_stmt: import_name | import_from */
1990 static int
1991 validate_import_stmt(node *tree)
1992 {
1993 int nch = NCH(tree);
1994 int res = validate_numnodes(tree, 1, "import_stmt");
1995
1996 if (res) {
1997 int ntype = TYPE(CHILD(tree, 0));
1998
1999 if (ntype == import_name || ntype == import_from)
2000 res = validate_node(CHILD(tree, 0));
2001 else {
2002 res = 0;
2003 err_string("illegal import_stmt child type");
2004 }
2005 }
2006 else if (nch == 1) {
2007 res = 0;
2008 PyErr_Format(parser_error,
2009 "Unrecognized child node of import_stmt: %d.",
2010 TYPE(CHILD(tree, 0)));
2011 }
2012 return (res);
2013 }
2014
2015
2016
2017
2018 static int
2019 validate_global_stmt(node *tree)
2020 {
2021 int j;
2022 int nch = NCH(tree);
2023 int res = (validate_ntype(tree, global_stmt)
2024 && is_even(nch) && (nch >= 2));
2025
2026 if (!res && !PyErr_Occurred())
2027 err_string("illegal global statement");
2028
2029 if (res)
2030 res = (validate_name(CHILD(tree, 0), "global")
2031 && validate_ntype(CHILD(tree, 1), NAME));
2032 for (j = 2; res && (j < nch); j += 2)
2033 res = (validate_comma(CHILD(tree, j))
2034 && validate_ntype(CHILD(tree, j + 1), NAME));
2035
2036 return (res);
2037 }
2038
2039
2040 /* exec_stmt:
2041 *
2042 * 'exec' expr ['in' test [',' test]]
2043 */
2044 static int
2045 validate_exec_stmt(node *tree)
2046 {
2047 int nch = NCH(tree);
2048 int res = (validate_ntype(tree, exec_stmt)
2049 && ((nch == 2) || (nch == 4) || (nch == 6))
2050 && validate_name(CHILD(tree, 0), "exec")
2051 && validate_expr(CHILD(tree, 1)));
2052
2053 if (!res && !PyErr_Occurred())
2054 err_string("illegal exec statement");
2055 if (res && (nch > 2))
2056 res = (validate_name(CHILD(tree, 2), "in")
2057 && validate_test(CHILD(tree, 3)));
2058 if (res && (nch == 6))
2059 res = (validate_comma(CHILD(tree, 4))
2060 && validate_test(CHILD(tree, 5)));
2061
2062 return (res);
2063 }
2064
2065
2066 /* assert_stmt:
2067 *
2068 * 'assert' test [',' test]
2069 */
2070 static int
2071 validate_assert_stmt(node *tree)
2072 {
2073 int nch = NCH(tree);
2074 int res = (validate_ntype(tree, assert_stmt)
2075 && ((nch == 2) || (nch == 4))
2076 && (validate_name(CHILD(tree, 0), "assert"))
2077 && validate_test(CHILD(tree, 1)));
2078
2079 if (!res && !PyErr_Occurred())
2080 err_string("illegal assert statement");
2081 if (res && (nch > 2))
2082 res = (validate_comma(CHILD(tree, 2))
2083 && validate_test(CHILD(tree, 3)));
2084
2085 return (res);
2086 }
2087
2088
2089 static int
2090 validate_while(node *tree)
2091 {
2092 int nch = NCH(tree);
2093 int res = (validate_ntype(tree, while_stmt)
2094 && ((nch == 4) || (nch == 7))
2095 && validate_name(CHILD(tree, 0), "while")
2096 && validate_test(CHILD(tree, 1))
2097 && validate_colon(CHILD(tree, 2))
2098 && validate_suite(CHILD(tree, 3)));
2099
2100 if (res && (nch == 7))
2101 res = (validate_name(CHILD(tree, 4), "else")
2102 && validate_colon(CHILD(tree, 5))
2103 && validate_suite(CHILD(tree, 6)));
2104
2105 return (res);
2106 }
2107
2108
2109 static int
2110 validate_for(node *tree)
2111 {
2112 int nch = NCH(tree);
2113 int res = (validate_ntype(tree, for_stmt)
2114 && ((nch == 6) || (nch == 9))
2115 && validate_name(CHILD(tree, 0), "for")
2116 && validate_exprlist(CHILD(tree, 1))
2117 && validate_name(CHILD(tree, 2), "in")
2118 && validate_testlist(CHILD(tree, 3))
2119 && validate_colon(CHILD(tree, 4))
2120 && validate_suite(CHILD(tree, 5)));
2121
2122 if (res && (nch == 9))
2123 res = (validate_name(CHILD(tree, 6), "else")
2124 && validate_colon(CHILD(tree, 7))
2125 && validate_suite(CHILD(tree, 8)));
2126
2127 return (res);
2128 }
2129
2130
2131 /* try_stmt:
2132 * 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
2133 ['finally' ':' suite]
2134 * | 'try' ':' suite 'finally' ':' suite
2135 *
2136 */
2137 static int
2138 validate_try(node *tree)
2139 {
2140 int nch = NCH(tree);
2141 int pos = 3;
2142 int res = (validate_ntype(tree, try_stmt)
2143 && (nch >= 6) && ((nch % 3) == 0));
2144
2145 if (res)
2146 res = (validate_name(CHILD(tree, 0), "try")
2147 && validate_colon(CHILD(tree, 1))
2148 && validate_suite(CHILD(tree, 2))
2149 && validate_colon(CHILD(tree, nch - 2))
2150 && validate_suite(CHILD(tree, nch - 1)));
2151 else if (!PyErr_Occurred()) {
2152 const char* name = "except";
2153 if (TYPE(CHILD(tree, nch - 3)) != except_clause)
2154 name = STR(CHILD(tree, nch - 3));
2155
2156 PyErr_Format(parser_error,
2157 "Illegal number of children for try/%s node.", name);
2158 }
2159 /* Handle try/finally statement */
2160 if (res && (TYPE(CHILD(tree, pos)) == NAME) &&
2161 (strcmp(STR(CHILD(tree, pos)), "finally") == 0)) {
2162 res = (validate_numnodes(tree, 6, "try/finally")
2163 && validate_colon(CHILD(tree, 4))
2164 && validate_suite(CHILD(tree, 5)));
2165 return (res);
2166 }
2167 /* try/except statement: skip past except_clause sections */
2168 while (res && pos < nch && (TYPE(CHILD(tree, pos)) == except_clause)) {
2169 res = (validate_except_clause(CHILD(tree, pos))
2170 && validate_colon(CHILD(tree, pos + 1))
2171 && validate_suite(CHILD(tree, pos + 2)));
2172 pos += 3;
2173 }
2174 /* skip else clause */
2175 if (res && pos < nch && (TYPE(CHILD(tree, pos)) == NAME) &&
2176 (strcmp(STR(CHILD(tree, pos)), "else") == 0)) {
2177 res = (validate_colon(CHILD(tree, pos + 1))
2178 && validate_suite(CHILD(tree, pos + 2)));
2179 pos += 3;
2180 }
2181 if (res && pos < nch) {
2182 /* last clause must be a finally */
2183 res = (validate_name(CHILD(tree, pos), "finally")
2184 && validate_numnodes(tree, pos + 3, "try/except/finally")
2185 && validate_colon(CHILD(tree, pos + 1))
2186 && validate_suite(CHILD(tree, pos + 2)));
2187 }
2188 return (res);
2189 }
2190
2191
2192 static int
2193 validate_except_clause(node *tree)
2194 {
2195 int nch = NCH(tree);
2196 int res = (validate_ntype(tree, except_clause)
2197 && ((nch == 1) || (nch == 2) || (nch == 4))
2198 && validate_name(CHILD(tree, 0), "except"));
2199
2200 if (res && (nch > 1))
2201 res = validate_test(CHILD(tree, 1));
2202 if (res && (nch == 4)) {
2203 if (TYPE(CHILD(tree, 2)) == NAME)
2204 res = validate_name(CHILD(tree, 2), "as");
2205 else
2206 res = validate_comma(CHILD(tree, 2));
2207 res = res && validate_test(CHILD(tree, 3));
2208 }
2209 return (res);
2210 }
2211
2212
2213 static int
2214 validate_test(node *tree)
2215 {
2216 int nch = NCH(tree);
2217 int res = validate_ntype(tree, test) && is_odd(nch);
2218
2219 if (res && (TYPE(CHILD(tree, 0)) == lambdef))
2220 res = ((nch == 1)
2221 && validate_lambdef(CHILD(tree, 0)));
2222 else if (res) {
2223 res = validate_or_test(CHILD(tree, 0));
2224 res = (res && (nch == 1 || (nch == 5 &&
2225 validate_name(CHILD(tree, 1), "if") &&
2226 validate_or_test(CHILD(tree, 2)) &&
2227 validate_name(CHILD(tree, 3), "else") &&
2228 validate_test(CHILD(tree, 4)))));
2229 }
2230 return (res);
2231 }
2232
2233 static int
2234 validate_old_test(node *tree)
2235 {
2236 int nch = NCH(tree);
2237 int res = validate_ntype(tree, old_test) && (nch == 1);
2238
2239 if (res && (TYPE(CHILD(tree, 0)) == old_lambdef))
2240 res = (validate_old_lambdef(CHILD(tree, 0)));
2241 else if (res) {
2242 res = (validate_or_test(CHILD(tree, 0)));
2243 }
2244 return (res);
2245 }
2246
2247 static int
2248 validate_or_test(node *tree)
2249 {
2250 int nch = NCH(tree);
2251 int res = validate_ntype(tree, or_test) && is_odd(nch);
2252
2253 if (res) {
2254 int pos;
2255 res = validate_and_test(CHILD(tree, 0));
2256 for (pos = 1; res && (pos < nch); pos += 2)
2257 res = (validate_name(CHILD(tree, pos), "or")
2258 && validate_and_test(CHILD(tree, pos + 1)));
2259 }
2260 return (res);
2261 }
2262
2263
2264 static int
2265 validate_and_test(node *tree)
2266 {
2267 int pos;
2268 int nch = NCH(tree);
2269 int res = (validate_ntype(tree, and_test)
2270 && is_odd(nch)
2271 && validate_not_test(CHILD(tree, 0)));
2272
2273 for (pos = 1; res && (pos < nch); pos += 2)
2274 res = (validate_name(CHILD(tree, pos), "and")
2275 && validate_not_test(CHILD(tree, 0)));
2276
2277 return (res);
2278 }
2279
2280
2281 static int
2282 validate_not_test(node *tree)
2283 {
2284 int nch = NCH(tree);
2285 int res = validate_ntype(tree, not_test) && ((nch == 1) || (nch == 2));
2286
2287 if (res) {
2288 if (nch == 2)
2289 res = (validate_name(CHILD(tree, 0), "not")
2290 && validate_not_test(CHILD(tree, 1)));
2291 else if (nch == 1)
2292 res = validate_comparison(CHILD(tree, 0));
2293 }
2294 return (res);
2295 }
2296
2297
2298 static int
2299 validate_comparison(node *tree)
2300 {
2301 int pos;
2302 int nch = NCH(tree);
2303 int res = (validate_ntype(tree, comparison)
2304 && is_odd(nch)
2305 && validate_expr(CHILD(tree, 0)));
2306
2307 for (pos = 1; res && (pos < nch); pos += 2)
2308 res = (validate_comp_op(CHILD(tree, pos))
2309 && validate_expr(CHILD(tree, pos + 1)));
2310
2311 return (res);
2312 }
2313
2314
2315 static int
2316 validate_comp_op(node *tree)
2317 {
2318 int res = 0;
2319 int nch = NCH(tree);
2320
2321 if (!validate_ntype(tree, comp_op))
2322 return (0);
2323 if (nch == 1) {
2324 /*
2325 * Only child will be a terminal with a well-defined symbolic name
2326 * or a NAME with a string of either 'is' or 'in'
2327 */
2328 tree = CHILD(tree, 0);
2329 switch (TYPE(tree)) {
2330 case LESS:
2331 case GREATER:
2332 case EQEQUAL:
2333 case EQUAL:
2334 case LESSEQUAL:
2335 case GREATEREQUAL:
2336 case NOTEQUAL:
2337 res = 1;
2338 break;
2339 case NAME:
2340 res = ((strcmp(STR(tree), "in") == 0)
2341 || (strcmp(STR(tree), "is") == 0));
2342 if (!res) {
2343 PyErr_Format(parser_error,
2344 "illegal operator '%s'", STR(tree));
2345 }
2346 break;
2347 default:
2348 err_string("illegal comparison operator type");
2349 break;
2350 }
2351 }
2352 else if ((res = validate_numnodes(tree, 2, "comp_op")) != 0) {
2353 res = (validate_ntype(CHILD(tree, 0), NAME)
2354 && validate_ntype(CHILD(tree, 1), NAME)
2355 && (((strcmp(STR(CHILD(tree, 0)), "is") == 0)
2356 && (strcmp(STR(CHILD(tree, 1)), "not") == 0))
2357 || ((strcmp(STR(CHILD(tree, 0)), "not") == 0)
2358 && (strcmp(STR(CHILD(tree, 1)), "in") == 0))));
2359 if (!res && !PyErr_Occurred())
2360 err_string("unknown comparison operator");
2361 }
2362 return (res);
2363 }
2364
2365
2366 static int
2367 validate_expr(node *tree)
2368 {
2369 int j;
2370 int nch = NCH(tree);
2371 int res = (validate_ntype(tree, expr)
2372 && is_odd(nch)
2373 && validate_xor_expr(CHILD(tree, 0)));
2374
2375 for (j = 2; res && (j < nch); j += 2)
2376 res = (validate_xor_expr(CHILD(tree, j))
2377 && validate_vbar(CHILD(tree, j - 1)));
2378
2379 return (res);
2380 }
2381
2382
2383 static int
2384 validate_xor_expr(node *tree)
2385 {
2386 int j;
2387 int nch = NCH(tree);
2388 int res = (validate_ntype(tree, xor_expr)
2389 && is_odd(nch)
2390 && validate_and_expr(CHILD(tree, 0)));
2391
2392 for (j = 2; res && (j < nch); j += 2)
2393 res = (validate_circumflex(CHILD(tree, j - 1))
2394 && validate_and_expr(CHILD(tree, j)));
2395
2396 return (res);
2397 }
2398
2399
2400 static int
2401 validate_and_expr(node *tree)
2402 {
2403 int pos;
2404 int nch = NCH(tree);
2405 int res = (validate_ntype(tree, and_expr)
2406 && is_odd(nch)
2407 && validate_shift_expr(CHILD(tree, 0)));
2408
2409 for (pos = 1; res && (pos < nch); pos += 2)
2410 res = (validate_ampersand(CHILD(tree, pos))
2411 && validate_shift_expr(CHILD(tree, pos + 1)));
2412
2413 return (res);
2414 }
2415
2416
2417 static int
2418 validate_chain_two_ops(node *tree, int (*termvalid)(node *), int op1, int op2)
2419 {
2420 int pos = 1;
2421 int nch = NCH(tree);
2422 int res = (is_odd(nch)
2423 && (*termvalid)(CHILD(tree, 0)));
2424
2425 for ( ; res && (pos < nch); pos += 2) {
2426 if (TYPE(CHILD(tree, pos)) != op1)
2427 res = validate_ntype(CHILD(tree, pos), op2);
2428 if (res)
2429 res = (*termvalid)(CHILD(tree, pos + 1));
2430 }
2431 return (res);
2432 }
2433
2434
2435 static int
2436 validate_shift_expr(node *tree)
2437 {
2438 return (validate_ntype(tree, shift_expr)
2439 && validate_chain_two_ops(tree, validate_arith_expr,
2440 LEFTSHIFT, RIGHTSHIFT));
2441 }
2442
2443
2444 static int
2445 validate_arith_expr(node *tree)
2446 {
2447 return (validate_ntype(tree, arith_expr)
2448 && validate_chain_two_ops(tree, validate_term, PLUS, MINUS));
2449 }
2450
2451
2452 static int
2453 validate_term(node *tree)
2454 {
2455 int pos = 1;
2456 int nch = NCH(tree);
2457 int res = (validate_ntype(tree, term)
2458 && is_odd(nch)
2459 && validate_factor(CHILD(tree, 0)));
2460
2461 for ( ; res && (pos < nch); pos += 2)
2462 res = (((TYPE(CHILD(tree, pos)) == STAR)
2463 || (TYPE(CHILD(tree, pos)) == SLASH)
2464 || (TYPE(CHILD(tree, pos)) == DOUBLESLASH)
2465 || (TYPE(CHILD(tree, pos)) == PERCENT))
2466 && validate_factor(CHILD(tree, pos + 1)));
2467
2468 return (res);
2469 }
2470
2471
2472 /* factor:
2473 *
2474 * factor: ('+'|'-'|'~') factor | power
2475 */
2476 static int
2477 validate_factor(node *tree)
2478 {
2479 int nch = NCH(tree);
2480 int res = (validate_ntype(tree, factor)
2481 && (((nch == 2)
2482 && ((TYPE(CHILD(tree, 0)) == PLUS)
2483 || (TYPE(CHILD(tree, 0)) == MINUS)
2484 || (TYPE(CHILD(tree, 0)) == TILDE))
2485 && validate_factor(CHILD(tree, 1)))
2486 || ((nch == 1)
2487 && validate_power(CHILD(tree, 0)))));
2488 return (res);
2489 }
2490
2491
2492 /* power:
2493 *
2494 * power: atom trailer* ('**' factor)*
2495 */
2496 static int
2497 validate_power(node *tree)
2498 {
2499 int pos = 1;
2500 int nch = NCH(tree);
2501 int res = (validate_ntype(tree, power) && (nch >= 1)
2502 && validate_atom(CHILD(tree, 0)));
2503
2504 while (res && (pos < nch) && (TYPE(CHILD(tree, pos)) == trailer))
2505 res = validate_trailer(CHILD(tree, pos++));
2506 if (res && (pos < nch)) {
2507 if (!is_even(nch - pos)) {
2508 err_string("illegal number of nodes for 'power'");
2509 return (0);
2510 }
2511 for ( ; res && (pos < (nch - 1)); pos += 2)
2512 res = (validate_doublestar(CHILD(tree, pos))
2513 && validate_factor(CHILD(tree, pos + 1)));
2514 }
2515 return (res);
2516 }
2517
2518
2519 static int
2520 validate_atom(node *tree)
2521 {
2522 int pos;
2523 int nch = NCH(tree);
2524 int res = validate_ntype(tree, atom);
2525
2526 if (res && nch < 1)
2527 res = validate_numnodes(tree, nch+1, "atom");
2528 if (res) {
2529 switch (TYPE(CHILD(tree, 0))) {
2530 case LPAR:
2531 res = ((nch <= 3)
2532 && (validate_rparen(CHILD(tree, nch - 1))));
2533
2534 if (res && (nch == 3)) {
2535 if (TYPE(CHILD(tree, 1))==yield_expr)
2536 res = validate_yield_expr(CHILD(tree, 1));
2537 else
2538 res = validate_testlist_comp(CHILD(tree, 1));
2539 }
2540 break;
2541 case LSQB:
2542 if (nch == 2)
2543 res = validate_ntype(CHILD(tree, 1), RSQB);
2544 else if (nch == 3)
2545 res = (validate_listmaker(CHILD(tree, 1))
2546 && validate_ntype(CHILD(tree, 2), RSQB));
2547 else {
2548 res = 0;
2549 err_string("illegal list display atom");
2550 }
2551 break;
2552 case LBRACE:
2553 res = ((nch <= 3)
2554 && validate_ntype(CHILD(tree, nch - 1), RBRACE));
2555
2556 if (res && (nch == 3))
2557 res = validate_dictorsetmaker(CHILD(tree, 1));
2558 break;
2559 case BACKQUOTE:
2560 res = ((nch == 3)
2561 && validate_testlist1(CHILD(tree, 1))
2562 && validate_ntype(CHILD(tree, 2), BACKQUOTE));
2563 break;
2564 case NAME:
2565 case NUMBER:
2566 res = (nch == 1);
2567 break;
2568 case STRING:
2569 for (pos = 1; res && (pos < nch); ++pos)
2570 res = validate_ntype(CHILD(tree, pos), STRING);
2571 break;
2572 default:
2573 res = 0;
2574 break;
2575 }
2576 }
2577 return (res);
2578 }
2579
2580
2581 /* listmaker:
2582 * test ( list_for | (',' test)* [','] )
2583 */
2584 static int
2585 validate_listmaker(node *tree)
2586 {
2587 int nch = NCH(tree);
2588 int ok = nch;
2589
2590 if (nch == 0)
2591 err_string("missing child nodes of listmaker");
2592 else
2593 ok = validate_test(CHILD(tree, 0));
2594
2595 /*
2596 * list_for | (',' test)* [',']
2597 */
2598 if (nch == 2 && TYPE(CHILD(tree, 1)) == list_for)
2599 ok = validate_list_for(CHILD(tree, 1));
2600 else {
2601 /* (',' test)* [','] */
2602 int i = 1;
2603 while (ok && nch - i >= 2) {
2604 ok = (validate_comma(CHILD(tree, i))
2605 && validate_test(CHILD(tree, i+1)));
2606 i += 2;
2607 }
2608 if (ok && i == nch-1)
2609 ok = validate_comma(CHILD(tree, i));
2610 else if (i != nch) {
2611 ok = 0;
2612 err_string("illegal trailing nodes for listmaker");
2613 }
2614 }
2615 return ok;
2616 }
2617
2618 /* testlist_comp:
2619 * test ( comp_for | (',' test)* [','] )
2620 */
2621 static int
2622 validate_testlist_comp(node *tree)
2623 {
2624 int nch = NCH(tree);
2625 int ok = nch;
2626
2627 if (nch == 0)
2628 err_string("missing child nodes of testlist_comp");
2629 else {
2630 ok = validate_test(CHILD(tree, 0));
2631 }
2632
2633 /*
2634 * comp_for | (',' test)* [',']
2635 */
2636 if (nch == 2 && TYPE(CHILD(tree, 1)) == comp_for)
2637 ok = validate_comp_for(CHILD(tree, 1));
2638 else {
2639 /* (',' test)* [','] */
2640 int i = 1;
2641 while (ok && nch - i >= 2) {
2642 ok = (validate_comma(CHILD(tree, i))
2643 && validate_test(CHILD(tree, i+1)));
2644 i += 2;
2645 }
2646 if (ok && i == nch-1)
2647 ok = validate_comma(CHILD(tree, i));
2648 else if (i != nch) {
2649 ok = 0;
2650 err_string("illegal trailing nodes for testlist_comp");
2651 }
2652 }
2653 return ok;
2654 }
2655
2656 /* decorator:
2657 * '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
2658 */
2659 static int
2660 validate_decorator(node *tree)
2661 {
2662 int ok;
2663 int nch = NCH(tree);
2664 ok = (validate_ntype(tree, decorator) &&
2665 (nch == 3 || nch == 5 || nch == 6) &&
2666 validate_at(CHILD(tree, 0)) &&
2667 validate_dotted_name(CHILD(tree, 1)) &&
2668 validate_newline(RCHILD(tree, -1)));
2669
2670 if (ok && nch != 3) {
2671 ok = (validate_lparen(CHILD(tree, 2)) &&
2672 validate_rparen(RCHILD(tree, -2)));
2673
2674 if (ok && nch == 6)
2675 ok = validate_arglist(CHILD(tree, 3));
2676 }
2677
2678 return ok;
2679 }
2680
2681 /* decorators:
2682 * decorator+
2683 */
2684 static int
2685 validate_decorators(node *tree)
2686 {
2687 int i, nch, ok;
2688 nch = NCH(tree);
2689 ok = validate_ntype(tree, decorators) && nch >= 1;
2690
2691 for (i = 0; ok && i < nch; ++i)
2692 ok = validate_decorator(CHILD(tree, i));
2693
2694 return ok;
2695 }
2696
2697 /* with_item:
2698 * test ['as' expr]
2699 */
2700 static int
2701 validate_with_item(node *tree)
2702 {
2703 int nch = NCH(tree);
2704 int ok = (validate_ntype(tree, with_item)
2705 && (nch == 1 || nch == 3)
2706 && validate_test(CHILD(tree, 0)));
2707 if (ok && nch == 3)
2708 ok = (validate_name(CHILD(tree, 1), "as")
2709 && validate_expr(CHILD(tree, 2)));
2710 return ok;
2711 }
2712
2713 /* with_stmt:
2714 * 0 1 ... -2 -1
2715 * 'with' with_item (',' with_item)* ':' suite
2716 */
2717 static int
2718 validate_with_stmt(node *tree)
2719 {
2720 int i;
2721 int nch = NCH(tree);
2722 int ok = (validate_ntype(tree, with_stmt)
2723 && (nch % 2 == 0)
2724 && validate_name(CHILD(tree, 0), "with")
2725 && validate_colon(RCHILD(tree, -2))
2726 && validate_suite(RCHILD(tree, -1)));
2727 for (i = 1; ok && i < nch - 2; i += 2)
2728 ok = validate_with_item(CHILD(tree, i));
2729 return ok;
2730 }
2731
2732 /* funcdef:
2733 *
2734 * -5 -4 -3 -2 -1
2735 * 'def' NAME parameters ':' suite
2736 */
2737 static int
2738 validate_funcdef(node *tree)
2739 {
2740 int nch = NCH(tree);
2741 int ok = (validate_ntype(tree, funcdef)
2742 && (nch == 5)
2743 && validate_name(RCHILD(tree, -5), "def")
2744 && validate_ntype(RCHILD(tree, -4), NAME)
2745 && validate_colon(RCHILD(tree, -2))
2746 && validate_parameters(RCHILD(tree, -3))
2747 && validate_suite(RCHILD(tree, -1)));
2748 return ok;
2749 }
2750
2751
2752 /* decorated
2753 * decorators (classdef | funcdef)
2754 */
2755 static int
2756 validate_decorated(node *tree)
2757 {
2758 int nch = NCH(tree);
2759 int ok = (validate_ntype(tree, decorated)
2760 && (nch == 2)
2761 && validate_decorators(RCHILD(tree, -2)));
2762 if (TYPE(RCHILD(tree, -1)) == funcdef)
2763 ok = ok && validate_funcdef(RCHILD(tree, -1));
2764 else
2765 ok = ok && validate_class(RCHILD(tree, -1));
2766 return ok;
2767 }
2768
2769 static int
2770 validate_lambdef(node *tree)
2771 {
2772 int nch = NCH(tree);
2773 int res = (validate_ntype(tree, lambdef)
2774 && ((nch == 3) || (nch == 4))
2775 && validate_name(CHILD(tree, 0), "lambda")
2776 && validate_colon(CHILD(tree, nch - 2))
2777 && validate_test(CHILD(tree, nch - 1)));
2778
2779 if (res && (nch == 4))
2780 res = validate_varargslist(CHILD(tree, 1));
2781 else if (!res && !PyErr_Occurred())
2782 (void) validate_numnodes(tree, 3, "lambdef");
2783
2784 return (res);
2785 }
2786
2787
2788 static int
2789 validate_old_lambdef(node *tree)
2790 {
2791 int nch = NCH(tree);
2792 int res = (validate_ntype(tree, old_lambdef)
2793 && ((nch == 3) || (nch == 4))
2794 && validate_name(CHILD(tree, 0), "lambda")
2795 && validate_colon(CHILD(tree, nch - 2))
2796 && validate_test(CHILD(tree, nch - 1)));
2797
2798 if (res && (nch == 4))
2799 res = validate_varargslist(CHILD(tree, 1));
2800 else if (!res && !PyErr_Occurred())
2801 (void) validate_numnodes(tree, 3, "old_lambdef");
2802
2803 return (res);
2804 }
2805
2806
2807 /* arglist:
2808 *
2809 * (argument ',')* (argument [','] | '*' test [',' '**' test] | '**' test)
2810 */
2811 static int
2812 validate_arglist(node *tree)
2813 {
2814 int nch = NCH(tree);
2815 int i = 0;
2816 int ok = 1;
2817
2818 if (nch <= 0)
2819 /* raise the right error from having an invalid number of children */
2820 return validate_numnodes(tree, nch + 1, "arglist");
2821
2822 if (nch > 1) {
2823 for (i=0; i<nch; i++) {
2824 if (TYPE(CHILD(tree, i)) == argument) {
2825 node *ch = CHILD(tree, i);
2826 if (NCH(ch) == 2 && TYPE(CHILD(ch, 1)) == comp_for) {
2827 err_string("need '(', ')' for generator expression");
2828 return 0;
2829 }
2830 }
2831 }
2832 }
2833
2834 while (ok && nch-i >= 2) {
2835 /* skip leading (argument ',') */
2836 ok = (validate_argument(CHILD(tree, i))
2837 && validate_comma(CHILD(tree, i+1)));
2838 if (ok)
2839 i += 2;
2840 else
2841 PyErr_Clear();
2842 }
2843 ok = 1;
2844 if (nch-i > 0) {
2845 /*
2846 * argument | '*' test [',' '**' test] | '**' test
2847 */
2848 int sym = TYPE(CHILD(tree, i));
2849
2850 if (sym == argument) {
2851 ok = validate_argument(CHILD(tree, i));
2852 if (ok && i+1 != nch) {
2853 err_string("illegal arglist specification"
2854 " (extra stuff on end)");
2855 ok = 0;
2856 }
2857 }
2858 else if (sym == STAR) {
2859 ok = validate_star(CHILD(tree, i));
2860 if (ok && (nch-i == 2))
2861 ok = validate_test(CHILD(tree, i+1));
2862 else if (ok && (nch-i == 5))
2863 ok = (validate_test(CHILD(tree, i+1))
2864 && validate_comma(CHILD(tree, i+2))
2865 && validate_doublestar(CHILD(tree, i+3))
2866 && validate_test(CHILD(tree, i+4)));
2867 else {
2868 err_string("illegal use of '*' in arglist");
2869 ok = 0;
2870 }
2871 }
2872 else if (sym == DOUBLESTAR) {
2873 if (nch-i == 2)
2874 ok = (validate_doublestar(CHILD(tree, i))
2875 && validate_test(CHILD(tree, i+1)));
2876 else {
2877 err_string("illegal use of '**' in arglist");
2878 ok = 0;
2879 }
2880 }
2881 else {
2882 err_string("illegal arglist specification");
2883 ok = 0;
2884 }
2885 }
2886 return (ok);
2887 }
2888
2889
2890
2891 /* argument:
2892 *
2893 * [test '='] test [comp_for]
2894 */
2895 static int
2896 validate_argument(node *tree)
2897 {
2898 int nch = NCH(tree);
2899 int res = (validate_ntype(tree, argument)
2900 && ((nch == 1) || (nch == 2) || (nch == 3))
2901 && validate_test(CHILD(tree, 0)));
2902
2903 if (res && (nch == 2))
2904 res = validate_comp_for(CHILD(tree, 1));
2905 else if (res && (nch == 3))
2906 res = (validate_equal(CHILD(tree, 1))
2907 && validate_test(CHILD(tree, 2)));
2908
2909 return (res);
2910 }
2911
2912
2913
2914 /* trailer:
2915 *
2916 * '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
2917 */
2918 static int
2919 validate_trailer(node *tree)
2920 {
2921 int nch = NCH(tree);
2922 int res = validate_ntype(tree, trailer) && ((nch == 2) || (nch == 3));
2923
2924 if (res) {
2925 switch (TYPE(CHILD(tree, 0))) {
2926 case LPAR:
2927 res = validate_rparen(CHILD(tree, nch - 1));
2928 if (res && (nch == 3))
2929 res = validate_arglist(CHILD(tree, 1));
2930 break;
2931 case LSQB:
2932 res = (validate_numnodes(tree, 3, "trailer")
2933 && validate_subscriptlist(CHILD(tree, 1))
2934 && validate_ntype(CHILD(tree, 2), RSQB));
2935 break;
2936 case DOT:
2937 res = (validate_numnodes(tree, 2, "trailer")
2938 && validate_ntype(CHILD(tree, 1), NAME));
2939 break;
2940 default:
2941 res = 0;
2942 break;
2943 }
2944 }
2945 else {
2946 (void) validate_numnodes(tree, 2, "trailer");
2947 }
2948 return (res);
2949 }
2950
2951
2952 /* subscriptlist:
2953 *
2954 * subscript (',' subscript)* [',']
2955 */
2956 static int
2957 validate_subscriptlist(node *tree)
2958 {
2959 return (validate_repeating_list(tree, subscriptlist,
2960 validate_subscript, "subscriptlist"));
2961 }
2962
2963
2964 /* subscript:
2965 *
2966 * '.' '.' '.' | test | [test] ':' [test] [sliceop]
2967 */
2968 static int
2969 validate_subscript(node *tree)
2970 {
2971 int offset = 0;
2972 int nch = NCH(tree);
2973 int res = validate_ntype(tree, subscript) && (nch >= 1) && (nch <= 4);
2974
2975 if (!res) {
2976 if (!PyErr_Occurred())
2977 err_string("invalid number of arguments for subscript node");
2978 return (0);
2979 }
2980 if (TYPE(CHILD(tree, 0)) == DOT)
2981 /* take care of ('.' '.' '.') possibility */
2982 return (validate_numnodes(tree, 3, "subscript")
2983 && validate_dot(CHILD(tree, 0))
2984 && validate_dot(CHILD(tree, 1))
2985 && validate_dot(CHILD(tree, 2)));
2986 if (nch == 1) {
2987 if (TYPE(CHILD(tree, 0)) == test)
2988 res = validate_test(CHILD(tree, 0));
2989 else
2990 res = validate_colon(CHILD(tree, 0));
2991 return (res);
2992 }
2993 /* Must be [test] ':' [test] [sliceop],
2994 * but at least one of the optional components will
2995 * be present, but we don't know which yet.
2996 */
2997 if ((TYPE(CHILD(tree, 0)) != COLON) || (nch == 4)) {
2998 res = validate_test(CHILD(tree, 0));
2999 offset = 1;
3000 }
3001 if (res)
3002 res = validate_colon(CHILD(tree, offset));
3003 if (res) {
3004 int rem = nch - ++offset;
3005 if (rem) {
3006 if (TYPE(CHILD(tree, offset)) == test) {
3007 res = validate_test(CHILD(tree, offset));
3008 ++offset;
3009 --rem;
3010 }
3011 if (res && rem)
3012 res = validate_sliceop(CHILD(tree, offset));
3013 }
3014 }
3015 return (res);
3016 }
3017
3018
3019 static int
3020 validate_sliceop(node *tree)
3021 {
3022 int nch = NCH(tree);
3023 int res = ((nch == 1) || validate_numnodes(tree, 2, "sliceop"))
3024 && validate_ntype(tree, sliceop);
3025 if (!res && !PyErr_Occurred()) {
3026 res = validate_numnodes(tree, 1, "sliceop");
3027 }
3028 if (res)
3029 res = validate_colon(CHILD(tree, 0));
3030 if (res && (nch == 2))
3031 res = validate_test(CHILD(tree, 1));
3032
3033 return (res);
3034 }
3035
3036
3037 static int
3038 validate_exprlist(node *tree)
3039 {
3040 return (validate_repeating_list(tree, exprlist,
3041 validate_expr, "exprlist"));
3042 }
3043
3044
3045 /*
3046 * dictorsetmaker:
3047 *
3048 * (test ':' test (comp_for | (',' test ':' test)* [','])) |
3049 * (test (comp_for | (',' test)* [',']))
3050 */
3051 static int
3052 validate_dictorsetmaker(node *tree)
3053 {
3054 int nch = NCH(tree);
3055 int ok = validate_ntype(tree, dictorsetmaker);
3056 int i = 0;
3057 int check_trailing_comma = 0;
3058
3059 assert(nch > 0);
3060
3061 if (ok && (nch == 1 || TYPE(CHILD(tree, 1)) == COMMA)) {
3062 /* We got a set:
3063 * test (',' test)* [',']
3064 */
3065 ok = validate_test(CHILD(tree, i++));
3066 while (ok && nch - i >= 2) {
3067 ok = (validate_comma(CHILD(tree, i))
3068 && validate_test(CHILD(tree, i+1)));
3069 i += 2;
3070 }
3071 check_trailing_comma = 1;
3072 }
3073 else if (ok && TYPE(CHILD(tree, 1)) == comp_for) {
3074 /* We got a set comprehension:
3075 * test comp_for
3076 */
3077 ok = (validate_test(CHILD(tree, 0))
3078 && validate_comp_for(CHILD(tree, 1)));
3079 }
3080 else if (ok && NCH(tree) > 3 && TYPE(CHILD(tree, 3)) == comp_for) {
3081 /* We got a dict comprehension:
3082 * test ':' test comp_for
3083 */
3084 ok = (validate_test(CHILD(tree, 0))
3085 && validate_colon(CHILD(tree, 1))
3086 && validate_test(CHILD(tree, 2))
3087 && validate_comp_for(CHILD(tree, 3)));
3088 }
3089 else if (ok) {
3090 /* We got a dict:
3091 * test ':' test (',' test ':' test)* [',']
3092 */
3093 if (nch >= 3) {
3094 ok = (validate_test(CHILD(tree, i))
3095 && validate_colon(CHILD(tree, i+1))
3096 && validate_test(CHILD(tree, i+2)));
3097 i += 3;
3098 }
3099 else {
3100 ok = 0;
3101 err_string("illegal number of nodes for dictorsetmaker");
3102 }
3103
3104 while (ok && nch - i >= 4) {
3105 ok = (validate_comma(CHILD(tree, i))
3106 && validate_test(CHILD(tree, i+1))
3107 && validate_colon(CHILD(tree, i+2))
3108 && validate_test(CHILD(tree, i+3)));
3109 i += 4;
3110 }
3111 check_trailing_comma = 1;
3112 }
3113 if (ok && check_trailing_comma) {
3114 if (i == nch-1)
3115 ok = validate_comma(CHILD(tree, i));
3116 else if (i != nch) {
3117 ok = 0;
3118 err_string("illegal trailing nodes for dictorsetmaker");
3119 }
3120 }
3121
3122 return ok;
3123 }
3124
3125
3126 static int
3127 validate_eval_input(node *tree)
3128 {
3129 int pos;
3130 int nch = NCH(tree);
3131 int res = (validate_ntype(tree, eval_input)
3132 && (nch >= 2)
3133 && validate_testlist(CHILD(tree, 0))
3134 && validate_ntype(CHILD(tree, nch - 1), ENDMARKER));
3135
3136 for (pos = 1; res && (pos < (nch - 1)); ++pos)
3137 res = validate_ntype(CHILD(tree, pos), NEWLINE);
3138
3139 return (res);
3140 }
3141
3142
3143 static int
3144 validate_node(node *tree)
3145 {
3146 int nch = 0; /* num. children on current node */
3147 int res = 1; /* result value */
3148 node* next = 0; /* node to process after this one */
3149
3150 while (res && (tree != 0)) {
3151 nch = NCH(tree);
3152 next = 0;
3153 switch (TYPE(tree)) {
3154 /*
3155 * Definition nodes.
3156 */
3157 case funcdef:
3158 res = validate_funcdef(tree);
3159 break;
3160 case with_stmt:
3161 res = validate_with_stmt(tree);
3162 break;
3163 case classdef:
3164 res = validate_class(tree);
3165 break;
3166 case decorated:
3167 res = validate_decorated(tree);
3168 break;
3169 /*
3170 * "Trivial" parse tree nodes.
3171 * (Why did I call these trivial?)
3172 */
3173 case stmt:
3174 res = validate_stmt(tree);
3175 break;
3176 case small_stmt:
3177 /*
3178 * expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt
3179 * | import_stmt | global_stmt | exec_stmt | assert_stmt
3180 */
3181 res = validate_small_stmt(tree);
3182 break;
3183 case flow_stmt:
3184 res = (validate_numnodes(tree, 1, "flow_stmt")
3185 && ((TYPE(CHILD(tree, 0)) == break_stmt)
3186 || (TYPE(CHILD(tree, 0)) == continue_stmt)
3187 || (TYPE(CHILD(tree, 0)) == yield_stmt)
3188 || (TYPE(CHILD(tree, 0)) == return_stmt)
3189 || (TYPE(CHILD(tree, 0)) == raise_stmt)));
3190 if (res)
3191 next = CHILD(tree, 0);
3192 else if (nch == 1)
3193 err_string("illegal flow_stmt type");
3194 break;
3195 case yield_stmt:
3196 res = validate_yield_stmt(tree);
3197 break;
3198 /*
3199 * Compound statements.
3200 */
3201 case simple_stmt:
3202 res = validate_simple_stmt(tree);
3203 break;
3204 case compound_stmt:
3205 res = validate_compound_stmt(tree);
3206 break;
3207 /*
3208 * Fundamental statements.
3209 */
3210 case expr_stmt:
3211 res = validate_expr_stmt(tree);
3212 break;
3213 case print_stmt:
3214 res = validate_print_stmt(tree);
3215 break;
3216 case del_stmt:
3217 res = validate_del_stmt(tree);
3218 break;
3219 case pass_stmt:
3220 res = (validate_numnodes(tree, 1, "pass")
3221 && validate_name(CHILD(tree, 0), "pass"));
3222 break;
3223 case break_stmt:
3224 res = (validate_numnodes(tree, 1, "break")
3225 && validate_name(CHILD(tree, 0), "break"));
3226 break;
3227 case continue_stmt:
3228 res = (validate_numnodes(tree, 1, "continue")
3229 && validate_name(CHILD(tree, 0), "continue"));
3230 break;
3231 case return_stmt:
3232 res = validate_return_stmt(tree);
3233 break;
3234 case raise_stmt:
3235 res = validate_raise_stmt(tree);
3236 break;
3237 case import_stmt:
3238 res = validate_import_stmt(tree);
3239 break;
3240 case import_name:
3241 res = validate_import_name(tree);
3242 break;
3243 case import_from:
3244 res = validate_import_from(tree);
3245 break;
3246 case global_stmt:
3247 res = validate_global_stmt(tree);
3248 break;
3249 case exec_stmt:
3250 res = validate_exec_stmt(tree);
3251 break;
3252 case assert_stmt:
3253 res = validate_assert_stmt(tree);
3254 break;
3255 case if_stmt:
3256 res = validate_if(tree);
3257 break;
3258 case while_stmt:
3259 res = validate_while(tree);
3260 break;
3261 case for_stmt:
3262 res = validate_for(tree);
3263 break;
3264 case try_stmt:
3265 res = validate_try(tree);
3266 break;
3267 case suite:
3268 res = validate_suite(tree);
3269 break;
3270 /*
3271 * Expression nodes.
3272 */
3273 case testlist:
3274 res = validate_testlist(tree);
3275 break;
3276 case yield_expr:
3277 res = validate_yield_expr(tree);
3278 break;
3279 case testlist1:
3280 res = validate_testlist1(tree);
3281 break;
3282 case test:
3283 res = validate_test(tree);
3284 break;
3285 case and_test:
3286 res = validate_and_test(tree);
3287 break;
3288 case not_test:
3289 res = validate_not_test(tree);
3290 break;
3291 case comparison:
3292 res = validate_comparison(tree);
3293 break;
3294 case exprlist:
3295 res = validate_exprlist(tree);
3296 break;
3297 case comp_op:
3298 res = validate_comp_op(tree);
3299 break;
3300 case expr:
3301 res = validate_expr(tree);
3302 break;
3303 case xor_expr:
3304 res = validate_xor_expr(tree);
3305 break;
3306 case and_expr:
3307 res = validate_and_expr(tree);
3308 break;
3309 case shift_expr:
3310 res = validate_shift_expr(tree);
3311 break;
3312 case arith_expr:
3313 res = validate_arith_expr(tree);
3314 break;
3315 case term:
3316 res = validate_term(tree);
3317 break;
3318 case factor:
3319 res = validate_factor(tree);
3320 break;
3321 case power:
3322 res = validate_power(tree);
3323 break;
3324 case atom:
3325 res = validate_atom(tree);
3326 break;
3327
3328 default:
3329 /* Hopefully never reached! */
3330 err_string("unrecognized node type");
3331 res = 0;
3332 break;
3333 }
3334 tree = next;
3335 }
3336 return (res);
3337 }
3338
3339
3340 static int
3341 validate_expr_tree(node *tree)
3342 {
3343 int res = validate_eval_input(tree);
3344
3345 if (!res && !PyErr_Occurred())
3346 err_string("could not validate expression tuple");
3347
3348 return (res);
3349 }
3350
3351
3352 /* file_input:
3353 * (NEWLINE | stmt)* ENDMARKER
3354 */
3355 static int
3356 validate_file_input(node *tree)
3357 {
3358 int j;
3359 int nch = NCH(tree) - 1;
3360 int res = ((nch >= 0)
3361 && validate_ntype(CHILD(tree, nch), ENDMARKER));
3362
3363 for (j = 0; res && (j < nch); ++j) {
3364 if (TYPE(CHILD(tree, j)) == stmt)
3365 res = validate_stmt(CHILD(tree, j));
3366 else
3367 res = validate_newline(CHILD(tree, j));
3368 }
3369 /* This stays in to prevent any internal failures from getting to the
3370 * user. Hopefully, this won't be needed. If a user reports getting
3371 * this, we have some debugging to do.
3372 */
3373 if (!res && !PyErr_Occurred())
3374 err_string("VALIDATION FAILURE: report this to the maintainer!");
3375
3376 return (res);
3377 }
3378
3379 static int
3380 validate_encoding_decl(node *tree)
3381 {
3382 int nch = NCH(tree);
3383 int res = ((nch == 1)
3384 && validate_file_input(CHILD(tree, 0)));
3385
3386 if (!res && !PyErr_Occurred())
3387 err_string("Error Parsing encoding_decl");
3388
3389 return res;
3390 }
3391
3392 static PyObject*
3393 pickle_constructor = NULL;
3394
3395
3396 static PyObject*
3397 parser__pickler(PyObject *self, PyObject *args)
3398 {
3399 NOTE(ARGUNUSED(self))
3400 PyObject *result = NULL;
3401 PyObject *st = NULL;
3402 PyObject *empty_dict = NULL;
3403
3404 if (PyArg_ParseTuple(args, "O!:_pickler", &PyST_Type, &st)) {
3405 PyObject *newargs;
3406 PyObject *tuple;
3407
3408 if ((empty_dict = PyDict_New()) == NULL)
3409 goto finally;
3410 if ((newargs = Py_BuildValue("Oi", st, 1)) == NULL)
3411 goto finally;
3412 tuple = parser_st2tuple((PyST_Object*)NULL, newargs, empty_dict);
3413 if (tuple != NULL) {
3414 result = Py_BuildValue("O(O)", pickle_constructor, tuple);
3415 Py_DECREF(tuple);
3416 }
3417 Py_DECREF(newargs);
3418 }
3419 finally:
3420 Py_XDECREF(empty_dict);
3421
3422 return (result);
3423 }
3424
3425
3426 /* Functions exported by this module. Most of this should probably
3427 * be converted into an ST object with methods, but that is better
3428 * done directly in Python, allowing subclasses to be created directly.
3429 * We'd really have to write a wrapper around it all anyway to allow
3430 * inheritance.
3431 */
3432 static PyMethodDef parser_functions[] = {
3433 {"ast2tuple", (PyCFunction)parser_ast2tuple, PUBLIC_METHOD_TYPE,
3434 PyDoc_STR("Creates a tuple-tree representation of an ST.")},
3435 {"ast2list", (PyCFunction)parser_ast2list, PUBLIC_METHOD_TYPE,
3436 PyDoc_STR("Creates a list-tree representation of an ST.")},
3437 {"compileast", (PyCFunction)parser_compileast,PUBLIC_METHOD_TYPE,
3438 PyDoc_STR("Compiles an ST object into a code object.")},
3439 {"compilest", (PyCFunction)parser_compilest, PUBLIC_METHOD_TYPE,
3440 PyDoc_STR("Compiles an ST object into a code object.")},
3441 {"expr", (PyCFunction)parser_expr, PUBLIC_METHOD_TYPE,
3442 PyDoc_STR("Creates an ST object from an expression.")},
3443 {"isexpr", (PyCFunction)parser_isexpr, PUBLIC_METHOD_TYPE,
3444 PyDoc_STR("Determines if an ST object was created from an expression.")},
3445 {"issuite", (PyCFunction)parser_issuite, PUBLIC_METHOD_TYPE,
3446 PyDoc_STR("Determines if an ST object was created from a suite.")},
3447 {"suite", (PyCFunction)parser_suite, PUBLIC_METHOD_TYPE,
3448 PyDoc_STR("Creates an ST object from a suite.")},
3449 {"sequence2ast", (PyCFunction)parser_tuple2ast, PUBLIC_METHOD_TYPE,
3450 PyDoc_STR("Creates an ST object from a tree representation.")},
3451 {"sequence2st", (PyCFunction)parser_tuple2st, PUBLIC_METHOD_TYPE,
3452 PyDoc_STR("Creates an ST object from a tree representation.")},
3453 {"st2tuple", (PyCFunction)parser_st2tuple, PUBLIC_METHOD_TYPE,
3454 PyDoc_STR("Creates a tuple-tree representation of an ST.")},
3455 {"st2list", (PyCFunction)parser_st2list, PUBLIC_METHOD_TYPE,
3456 PyDoc_STR("Creates a list-tree representation of an ST.")},
3457 {"tuple2ast", (PyCFunction)parser_tuple2ast, PUBLIC_METHOD_TYPE,
3458 PyDoc_STR("Creates an ST object from a tree representation.")},
3459 {"tuple2st", (PyCFunction)parser_tuple2st, PUBLIC_METHOD_TYPE,
3460 PyDoc_STR("Creates an ST object from a tree representation.")},
3461
3462 /* private stuff: support pickle module */
3463 {"_pickler", (PyCFunction)parser__pickler, METH_VARARGS,
3464 PyDoc_STR("Returns the pickle magic to allow ST objects to be pickled.")},
3465
3466 {NULL, NULL, 0, NULL}
3467 };
3468
3469
3470 PyMODINIT_FUNC initparser(void); /* supply a prototype */
3471
3472 PyMODINIT_FUNC
3473 initparser(void)
3474 {
3475 PyObject *module, *copyreg;
3476
3477 Py_TYPE(&PyST_Type) = &PyType_Type;
3478 module = Py_InitModule("parser", parser_functions);
3479 if (module == NULL)
3480 return;
3481
3482 if (parser_error == 0)
3483 parser_error = PyErr_NewException("parser.ParserError", NULL, NULL);
3484
3485 if (parser_error == 0)
3486 /* caller will check PyErr_Occurred() */
3487 return;
3488 /* CAUTION: The code next used to skip bumping the refcount on
3489 * parser_error. That's a disaster if initparser() gets called more
3490 * than once. By incref'ing, we ensure that each module dict that
3491 * gets created owns its reference to the shared parser_error object,
3492 * and the file static parser_error vrbl owns a reference too.
3493 */
3494 Py_INCREF(parser_error);
3495 if (PyModule_AddObject(module, "ParserError", parser_error) != 0)
3496 return;
3497
3498 Py_INCREF(&PyST_Type);
3499 PyModule_AddObject(module, "ASTType", (PyObject*)&PyST_Type);
3500 Py_INCREF(&PyST_Type);
3501 PyModule_AddObject(module, "STType", (PyObject*)&PyST_Type);
3502
3503 PyModule_AddStringConstant(module, "__copyright__",
3504 parser_copyright_string);
3505 PyModule_AddStringConstant(module, "__doc__",
3506 parser_doc_string);
3507 PyModule_AddStringConstant(module, "__version__",
3508 parser_version_string);
3509
3510 /* Register to support pickling.
3511 * If this fails, the import of this module will fail because an
3512 * exception will be raised here; should we clear the exception?
3513 */
3514 copyreg = PyImport_ImportModuleNoBlock("copy_reg");
3515 if (copyreg != NULL) {
3516 PyObject *func, *pickler;
3517
3518 func = PyObject_GetAttrString(copyreg, "pickle");
3519 pickle_constructor = PyObject_GetAttrString(module, "sequence2st");
3520 pickler = PyObject_GetAttrString(module, "_pickler");
3521 Py_XINCREF(pickle_constructor);
3522 if ((func != NULL) && (pickle_constructor != NULL)
3523 && (pickler != NULL)) {
3524 PyObject *res;
3525
3526 res = PyObject_CallFunctionObjArgs(func, &PyST_Type, pickler,
3527 pickle_constructor, NULL);
3528 Py_XDECREF(res);
3529 }
3530 Py_XDECREF(func);
3531 Py_XDECREF(pickle_constructor);
3532 Py_XDECREF(pickler);
3533 Py_DECREF(copyreg);
3534 }
3535 }