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.
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
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.
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(...)".
28 #include "Python.h" /* general Python API */
29 #include "graminit.h" /* symbols defined in the grammar */
30 #include "node.h" /* internal parser structure */
31 #include "errcode.h" /* error codes for PyNode_*() */
32 #include "token.h" /* token definitions */
33 /* ISTERMINAL() / ISNONTERMINAL() */
34 #include "compile.h" /* PyNode_Compile() */
42 /* String constants used to initialize module attributes.
45 static char parser_copyright_string
[] =
46 "Copyright 1995-1996 by Virginia Polytechnic Institute & State\n\
47 University, Blacksburg, Virginia, USA, and Fred L. Drake, Jr., Reston,\n\
48 Virginia, USA. Portions copyright 1991-1995 by Stichting Mathematisch\n\
49 Centrum, Amsterdam, The Netherlands.";
52 PyDoc_STRVAR(parser_doc_string
,
53 "This is an interface to Python's internal parser.");
55 static char parser_version_string
[] = "0.5";
58 typedef PyObject
* (*SeqMaker
) (Py_ssize_t length
);
59 typedef int (*SeqInserter
) (PyObject
* sequence
,
63 /* The function below is copyrighted by Stichting Mathematisch Centrum. The
64 * original copyright statement is included below, and continues to apply
65 * in full to the function immediately following. All other material is
66 * original, copyrighted by Fred L. Drake, Jr. and Virginia Polytechnic
67 * Institute and State University. Changes were made to comply with the
68 * new naming conventions. Added arguments to provide support for creating
69 * lists as well as tuples, and optionally including the line numbers.
74 node2tuple(node
*n
, /* node to convert */
75 SeqMaker mkseq
, /* create sequence */
76 SeqInserter addelem
, /* func. to add elem. in seq. */
77 int lineno
, /* include line numbers? */
78 int col_offset
) /* include column offsets? */
84 if (ISNONTERMINAL(TYPE(n
))) {
89 v
= mkseq(1 + NCH(n
) + (TYPE(n
) == encoding_decl
));
92 w
= PyInt_FromLong(TYPE(n
));
95 return ((PyObject
*) NULL
);
97 (void) addelem(v
, 0, w
);
98 for (i
= 0; i
< NCH(n
); i
++) {
99 w
= node2tuple(CHILD(n
, i
), mkseq
, addelem
, lineno
, col_offset
);
102 return ((PyObject
*) NULL
);
104 (void) addelem(v
, i
+1, w
);
107 if (TYPE(n
) == encoding_decl
)
108 (void) addelem(v
, i
+1, PyString_FromString(STR(n
)));
111 else if (ISTERMINAL(TYPE(n
))) {
112 PyObject
*result
= mkseq(2 + lineno
+ col_offset
);
113 if (result
!= NULL
) {
114 (void) addelem(result
, 0, PyInt_FromLong(TYPE(n
)));
115 (void) addelem(result
, 1, PyString_FromString(STR(n
)));
117 (void) addelem(result
, 2, PyInt_FromLong(n
->n_lineno
));
119 (void) addelem(result
, 3, PyInt_FromLong(n
->n_col_offset
));
124 PyErr_SetString(PyExc_SystemError
,
125 "unrecognized parse tree node type");
126 return ((PyObject
*) NULL
);
130 * End of material copyrighted by Stichting Mathematisch Centrum.
135 /* There are two types of intermediate objects we're interested in:
136 * 'eval' and 'exec' types. These constants can be used in the st_type
137 * field of the object type to identify which any given object represents.
138 * These should probably go in an external header to allow other extensions
139 * to use them, but then, we really should be using C++ too. ;-)
146 /* These are the internal objects and definitions required to implement the
147 * ST type. Most of the internal names are more reminiscent of the 'old'
148 * naming style, but the code uses the new naming convention.
156 PyObject_HEAD
/* standard object header */
157 node
* st_node
; /* the node* returned by the parser */
158 int st_type
; /* EXPR or SUITE ? */
162 static void parser_free(PyST_Object
*st
);
163 static int parser_compare(PyST_Object
*left
, PyST_Object
*right
);
164 static PyObject
*parser_getattr(PyObject
*self
, char *name
);
168 PyTypeObject PyST_Type
= {
169 PyVarObject_HEAD_INIT(NULL
, 0)
170 "parser.st", /* tp_name */
171 (int) sizeof(PyST_Object
), /* tp_basicsize */
173 (destructor
)parser_free
, /* tp_dealloc */
175 parser_getattr
, /* tp_getattr */
177 (cmpfunc
)parser_compare
, /* tp_compare */
179 0, /* tp_as_number */
180 0, /* tp_as_sequence */
181 0, /* tp_as_mapping */
188 /* Functions to access object as input/output buffer */
189 0, /* tp_as_buffer */
191 Py_TPFLAGS_DEFAULT
, /* tp_flags */
194 "Intermediate representation of a Python parse tree."
199 parser_compare_nodes(node
*left
, node
*right
)
203 if (TYPE(left
) < TYPE(right
))
206 if (TYPE(right
) < TYPE(left
))
209 if (ISTERMINAL(TYPE(left
)))
210 return (strcmp(STR(left
), STR(right
)));
212 if (NCH(left
) < NCH(right
))
215 if (NCH(right
) < NCH(left
))
218 for (j
= 0; j
< NCH(left
); ++j
) {
219 int v
= parser_compare_nodes(CHILD(left
, j
), CHILD(right
, j
));
228 /* int parser_compare(PyST_Object* left, PyST_Object* right)
230 * Comparison function used by the Python operators ==, !=, <, >, <=, >=
231 * This really just wraps a call to parser_compare_nodes() with some easy
232 * checks and protection code.
236 parser_compare(PyST_Object
*left
, PyST_Object
*right
)
241 if ((left
== 0) || (right
== 0))
244 return (parser_compare_nodes(left
->st_node
, right
->st_node
));
248 /* parser_newstobject(node* st)
250 * Allocates a new Python object representing an ST. This is simply the
251 * 'wrapper' object that holds a node* and allows it to be passed around in
256 parser_newstobject(node
*st
, int type
)
258 PyST_Object
* o
= PyObject_New(PyST_Object
, &PyST_Type
);
267 return ((PyObject
*)o
);
271 /* void parser_free(PyST_Object* st)
273 * This is called by a del statement that reduces the reference count to 0.
277 parser_free(PyST_Object
*st
)
279 PyNode_Free(st
->st_node
);
284 /* parser_st2tuple(PyObject* self, PyObject* args, PyObject* kw)
286 * This provides conversion from a node* to a tuple object that can be
287 * returned to the Python-level caller. The ST object is not modified.
291 parser_st2tuple(PyST_Object
*self
, PyObject
*args
, PyObject
*kw
)
293 PyObject
*line_option
= 0;
294 PyObject
*col_option
= 0;
298 static char *keywords
[] = {"ast", "line_info", "col_info", NULL
};
301 ok
= PyArg_ParseTupleAndKeywords(args
, kw
, "O!|OO:st2tuple", keywords
,
302 &PyST_Type
, &self
, &line_option
,
306 ok
= PyArg_ParseTupleAndKeywords(args
, kw
, "|OO:totuple", &keywords
[1],
307 &line_option
, &col_option
);
311 if (line_option
!= NULL
) {
312 lineno
= (PyObject_IsTrue(line_option
) != 0) ? 1 : 0;
314 if (col_option
!= NULL
) {
315 col_offset
= (PyObject_IsTrue(col_option
) != 0) ? 1 : 0;
318 * Convert ST into a tuple representation. Use Guido's function,
319 * since it's known to work already.
321 res
= node2tuple(((PyST_Object
*)self
)->st_node
,
322 PyTuple_New
, PyTuple_SetItem
, lineno
, col_offset
);
328 /* parser_st2list(PyObject* self, PyObject* args, PyObject* kw)
330 * This provides conversion from a node* to a list object that can be
331 * returned to the Python-level caller. The ST object is not modified.
335 parser_st2list(PyST_Object
*self
, PyObject
*args
, PyObject
*kw
)
337 PyObject
*line_option
= 0;
338 PyObject
*col_option
= 0;
342 static char *keywords
[] = {"ast", "line_info", "col_info", NULL
};
345 ok
= PyArg_ParseTupleAndKeywords(args
, kw
, "O!|OO:st2list", keywords
,
346 &PyST_Type
, &self
, &line_option
,
349 ok
= PyArg_ParseTupleAndKeywords(args
, kw
, "|OO:tolist", &keywords
[1],
350 &line_option
, &col_option
);
354 if (line_option
!= 0) {
355 lineno
= PyObject_IsTrue(line_option
) ? 1 : 0;
357 if (col_option
!= NULL
) {
358 col_offset
= (PyObject_IsTrue(col_option
) != 0) ? 1 : 0;
361 * Convert ST into a tuple representation. Use Guido's function,
362 * since it's known to work already.
364 res
= node2tuple(self
->st_node
,
365 PyList_New
, PyList_SetItem
, lineno
, col_offset
);
371 /* parser_compilest(PyObject* self, PyObject* args)
373 * This function creates code objects from the parse tree represented by
374 * the passed-in data object. An optional file name is passed in as well.
378 parser_compilest(PyST_Object
*self
, PyObject
*args
, PyObject
*kw
)
381 char* str
= "<syntax-tree>";
384 static char *keywords
[] = {"ast", "filename", NULL
};
387 ok
= PyArg_ParseTupleAndKeywords(args
, kw
, "O!|s:compilest", keywords
,
388 &PyST_Type
, &self
, &str
);
390 ok
= PyArg_ParseTupleAndKeywords(args
, kw
, "|s:compile", &keywords
[1],
394 res
= (PyObject
*)PyNode_Compile(self
->st_node
, str
);
400 /* PyObject* parser_isexpr(PyObject* self, PyObject* args)
401 * PyObject* parser_issuite(PyObject* self, PyObject* args)
403 * Checks the passed-in ST object to determine if it is an expression or
404 * a statement suite, respectively. The return is a Python truth value.
408 parser_isexpr(PyST_Object
*self
, PyObject
*args
, PyObject
*kw
)
413 static char *keywords
[] = {"ast", NULL
};
416 ok
= PyArg_ParseTupleAndKeywords(args
, kw
, "O!:isexpr", keywords
,
419 ok
= PyArg_ParseTupleAndKeywords(args
, kw
, ":isexpr", &keywords
[1]);
422 /* Check to see if the ST represents an expression or not. */
423 res
= (self
->st_type
== PyST_EXPR
) ? Py_True
: Py_False
;
431 parser_issuite(PyST_Object
*self
, PyObject
*args
, PyObject
*kw
)
436 static char *keywords
[] = {"ast", NULL
};
439 ok
= PyArg_ParseTupleAndKeywords(args
, kw
, "O!:issuite", keywords
,
442 ok
= PyArg_ParseTupleAndKeywords(args
, kw
, ":issuite", &keywords
[1]);
445 /* Check to see if the ST represents an expression or not. */
446 res
= (self
->st_type
== PyST_EXPR
) ? Py_False
: Py_True
;
453 #define PUBLIC_METHOD_TYPE (METH_VARARGS|METH_KEYWORDS)
457 {"compile", (PyCFunction
)parser_compilest
, PUBLIC_METHOD_TYPE
,
458 PyDoc_STR("Compile this ST object into a code object.")},
459 {"isexpr", (PyCFunction
)parser_isexpr
, PUBLIC_METHOD_TYPE
,
460 PyDoc_STR("Determines if this ST object was created from an expression.")},
461 {"issuite", (PyCFunction
)parser_issuite
, PUBLIC_METHOD_TYPE
,
462 PyDoc_STR("Determines if this ST object was created from a suite.")},
463 {"tolist", (PyCFunction
)parser_st2list
, PUBLIC_METHOD_TYPE
,
464 PyDoc_STR("Creates a list-tree representation of this ST.")},
465 {"totuple", (PyCFunction
)parser_st2tuple
, PUBLIC_METHOD_TYPE
,
466 PyDoc_STR("Creates a tuple-tree representation of this ST.")},
468 {NULL
, NULL
, 0, NULL
}
473 parser_getattr(PyObject
*self
, char *name
)
475 return (Py_FindMethod(parser_methods
, self
, name
));
479 /* err_string(char* message)
481 * Sets the error string for an exception of type ParserError.
485 err_string(char *message
)
487 PyErr_SetString(parser_error
, message
);
491 /* PyObject* parser_do_parse(PyObject* args, int type)
493 * Internal function to actually execute the parse and return the result if
494 * successful or set an exception if not.
498 parser_do_parse(PyObject
*args
, PyObject
*kw
, char *argspec
, int type
)
503 static char *keywords
[] = {"source", NULL
};
505 if (PyArg_ParseTupleAndKeywords(args
, kw
, argspec
, keywords
, &string
)) {
506 node
* n
= PyParser_SimpleParseString(string
,
508 ? eval_input
: file_input
);
511 res
= parser_newstobject(n
, type
);
517 /* PyObject* parser_expr(PyObject* self, PyObject* args)
518 * PyObject* parser_suite(PyObject* self, PyObject* args)
520 * External interfaces to the parser itself. Which is called determines if
521 * the parser attempts to recognize an expression ('eval' form) or statement
522 * suite ('exec' form). The real work is done by parser_do_parse() above.
526 parser_expr(PyST_Object
*self
, PyObject
*args
, PyObject
*kw
)
528 NOTE(ARGUNUSED(self
))
529 return (parser_do_parse(args
, kw
, "s:expr", PyST_EXPR
));
534 parser_suite(PyST_Object
*self
, PyObject
*args
, PyObject
*kw
)
536 NOTE(ARGUNUSED(self
))
537 return (parser_do_parse(args
, kw
, "s:suite", PyST_SUITE
));
542 /* This is the messy part of the code. Conversion from a tuple to an ST
543 * object requires that the input tuple be valid without having to rely on
544 * catching an exception from the compiler. This is done to allow the
545 * compiler itself to remain fast, since most of its input will come from
546 * the parser directly, and therefore be known to be syntactically correct.
547 * This validation is done to ensure that we don't core dump the compile
548 * phase, returning an exception instead.
550 * Two aspects can be broken out in this code: creating a node tree from
551 * the tuple passed in, and verifying that it is indeed valid. It may be
552 * advantageous to expand the number of ST types to include funcdefs and
553 * lambdadefs to take advantage of the optimizer, recognizing those STs
554 * here. They are not necessary, and not quite as useful in a raw form.
555 * For now, let's get expressions and suites working reliably.
559 static node
* build_node_tree(PyObject
*tuple
);
560 static int validate_expr_tree(node
*tree
);
561 static int validate_file_input(node
*tree
);
562 static int validate_encoding_decl(node
*tree
);
564 /* PyObject* parser_tuple2st(PyObject* self, PyObject* args)
566 * This is the public function, called from the Python code. It receives a
567 * single tuple object from the caller, and creates an ST object if the
568 * tuple can be validated. It does this by checking the first code of the
569 * tuple, and, if acceptable, builds the internal representation. If this
570 * step succeeds, the internal representation is validated as fully as
571 * possible with the various validate_*() routines defined below.
573 * This function must be changed if support is to be added for PyST_FRAGMENT
578 parser_tuple2st(PyST_Object
*self
, PyObject
*args
, PyObject
*kw
)
580 NOTE(ARGUNUSED(self
))
585 static char *keywords
[] = {"sequence", NULL
};
587 if (!PyArg_ParseTupleAndKeywords(args
, kw
, "O:sequence2st", keywords
,
590 if (!PySequence_Check(tuple
)) {
591 PyErr_SetString(PyExc_ValueError
,
592 "sequence2st() requires a single sequence argument");
596 * Convert the tree to the internal form before checking it.
598 tree
= build_node_tree(tuple
);
600 int start_sym
= TYPE(tree
);
601 if (start_sym
== eval_input
) {
602 /* Might be an eval form. */
603 if (validate_expr_tree(tree
))
604 st
= parser_newstobject(tree
, PyST_EXPR
);
608 else if (start_sym
== file_input
) {
609 /* This looks like an exec form so far. */
610 if (validate_file_input(tree
))
611 st
= parser_newstobject(tree
, PyST_SUITE
);
615 else if (start_sym
== encoding_decl
) {
616 /* This looks like an encoding_decl so far. */
617 if (validate_encoding_decl(tree
))
618 st
= parser_newstobject(tree
, PyST_SUITE
);
623 /* This is a fragment, at best. */
625 err_string("parse tree does not use a valid start symbol");
628 /* Make sure we throw an exception on all errors. We should never
629 * get this, but we'd do well to be sure something is done.
631 if (st
== NULL
&& !PyErr_Occurred())
632 err_string("unspecified ST error occurred");
638 /* node* build_node_children()
640 * Iterate across the children of the current non-terminal node and build
641 * their structures. If successful, return the root of this portion of
642 * the tree, otherwise, 0. Any required exception will be specified already,
643 * and no memory will have been deallocated.
647 build_node_children(PyObject
*tuple
, node
*root
, int *line_num
)
649 Py_ssize_t len
= PyObject_Size(tuple
);
653 for (i
= 1; i
< len
; ++i
) {
654 /* elem must always be a sequence, however simple */
655 PyObject
* elem
= PySequence_GetItem(tuple
, i
);
656 int ok
= elem
!= NULL
;
661 ok
= PySequence_Check(elem
);
663 PyObject
*temp
= PySequence_GetItem(elem
, 0);
667 ok
= PyInt_Check(temp
);
669 type
= PyInt_AS_LONG(temp
);
674 PyObject
*err
= Py_BuildValue("os", elem
,
675 "Illegal node construct.");
676 PyErr_SetObject(parser_error
, err
);
681 if (ISTERMINAL(type
)) {
682 Py_ssize_t len
= PyObject_Size(elem
);
685 if ((len
!= 2) && (len
!= 3)) {
686 err_string("terminal nodes must have 2 or 3 entries");
689 temp
= PySequence_GetItem(elem
, 1);
692 if (!PyString_Check(temp
)) {
693 PyErr_Format(parser_error
,
694 "second item in terminal node must be a string,"
696 Py_TYPE(temp
)->tp_name
);
701 PyObject
*o
= PySequence_GetItem(elem
, 2);
704 *line_num
= PyInt_AS_LONG(o
);
706 PyErr_Format(parser_error
,
707 "third item in terminal node must be an"
708 " integer, found %s",
709 Py_TYPE(temp
)->tp_name
);
717 len
= PyString_GET_SIZE(temp
) + 1;
718 strn
= (char *)PyObject_MALLOC(len
);
720 (void) memcpy(strn
, PyString_AS_STRING(temp
), len
);
723 else if (!ISNONTERMINAL(type
)) {
725 * It has to be one or the other; this is an error.
726 * Throw an exception.
728 PyObject
*err
= Py_BuildValue("os", elem
, "unknown node type.");
729 PyErr_SetObject(parser_error
, err
);
734 err
= PyNode_AddChild(root
, type
, strn
, *line_num
, 0);
735 if (err
== E_NOMEM
) {
737 return (node
*) PyErr_NoMemory();
739 if (err
== E_OVERFLOW
) {
741 PyErr_SetString(PyExc_ValueError
,
742 "unsupported number of child nodes");
746 if (ISNONTERMINAL(type
)) {
747 node
* new_child
= CHILD(root
, i
- 1);
749 if (new_child
!= build_node_children(elem
, new_child
, line_num
)) {
754 else if (type
== NEWLINE
) { /* It's true: we increment the */
755 ++(*line_num
); /* line number *after* the newline! */
764 build_node_tree(PyObject
*tuple
)
767 PyObject
*temp
= PySequence_GetItem(tuple
, 0);
771 num
= PyInt_AsLong(temp
);
773 if (ISTERMINAL(num
)) {
775 * The tuple is simple, but it doesn't start with a start symbol.
776 * Throw an exception now and be done with it.
778 tuple
= Py_BuildValue("os", tuple
,
779 "Illegal syntax-tree; cannot start with terminal symbol.");
780 PyErr_SetObject(parser_error
, tuple
);
783 else if (ISNONTERMINAL(num
)) {
785 * Not efficient, but that can be handled later.
788 PyObject
*encoding
= NULL
;
790 if (num
== encoding_decl
) {
791 encoding
= PySequence_GetItem(tuple
, 2);
792 /* tuple isn't borrowed anymore here, need to DECREF */
793 tuple
= PySequence_GetSlice(tuple
, 0, 2);
795 res
= PyNode_New(num
);
797 if (res
!= build_node_children(tuple
, res
, &line_num
)) {
801 if (res
&& encoding
) {
803 len
= PyString_GET_SIZE(encoding
) + 1;
804 res
->n_str
= (char *)PyObject_MALLOC(len
);
805 if (res
->n_str
!= NULL
)
806 (void) memcpy(res
->n_str
, PyString_AS_STRING(encoding
), len
);
813 /* The tuple is illegal -- if the number is neither TERMINAL nor
814 * NONTERMINAL, we can't use it. Not sure the implementation
815 * allows this condition, but the API doesn't preclude it.
817 PyObject
*err
= Py_BuildValue("os", tuple
,
818 "Illegal component tuple.");
819 PyErr_SetObject(parser_error
, err
);
828 * Validation routines used within the validation section:
830 static int validate_terminal(node
*terminal
, int type
, char *string
);
832 #define validate_ampersand(ch) validate_terminal(ch, AMPER, "&")
833 #define validate_circumflex(ch) validate_terminal(ch, CIRCUMFLEX, "^")
834 #define validate_colon(ch) validate_terminal(ch, COLON, ":")
835 #define validate_comma(ch) validate_terminal(ch, COMMA, ",")
836 #define validate_dedent(ch) validate_terminal(ch, DEDENT, "")
837 #define validate_equal(ch) validate_terminal(ch, EQUAL, "=")
838 #define validate_indent(ch) validate_terminal(ch, INDENT, (char*)NULL)
839 #define validate_lparen(ch) validate_terminal(ch, LPAR, "(")
840 #define validate_newline(ch) validate_terminal(ch, NEWLINE, (char*)NULL)
841 #define validate_rparen(ch) validate_terminal(ch, RPAR, ")")
842 #define validate_semi(ch) validate_terminal(ch, SEMI, ";")
843 #define validate_star(ch) validate_terminal(ch, STAR, "*")
844 #define validate_vbar(ch) validate_terminal(ch, VBAR, "|")
845 #define validate_doublestar(ch) validate_terminal(ch, DOUBLESTAR, "**")
846 #define validate_dot(ch) validate_terminal(ch, DOT, ".")
847 #define validate_at(ch) validate_terminal(ch, AT, "@")
848 #define validate_name(ch, str) validate_terminal(ch, NAME, str)
850 #define VALIDATER(n) static int validate_##n(node *tree)
852 VALIDATER(node
); VALIDATER(small_stmt
);
853 VALIDATER(class); VALIDATER(node
);
854 VALIDATER(parameters
); VALIDATER(suite
);
855 VALIDATER(testlist
); VALIDATER(varargslist
);
856 VALIDATER(fpdef
); VALIDATER(fplist
);
857 VALIDATER(stmt
); VALIDATER(simple_stmt
);
858 VALIDATER(expr_stmt
); VALIDATER(power
);
859 VALIDATER(print_stmt
); VALIDATER(del_stmt
);
860 VALIDATER(return_stmt
); VALIDATER(list_iter
);
861 VALIDATER(raise_stmt
); VALIDATER(import_stmt
);
862 VALIDATER(import_name
); VALIDATER(import_from
);
863 VALIDATER(global_stmt
); VALIDATER(list_if
);
864 VALIDATER(assert_stmt
); VALIDATER(list_for
);
865 VALIDATER(exec_stmt
); VALIDATER(compound_stmt
);
866 VALIDATER(while); VALIDATER(for);
867 VALIDATER(try); VALIDATER(except_clause
);
868 VALIDATER(test
); VALIDATER(and_test
);
869 VALIDATER(not_test
); VALIDATER(comparison
);
870 VALIDATER(comp_op
); VALIDATER(expr
);
871 VALIDATER(xor_expr
); VALIDATER(and_expr
);
872 VALIDATER(shift_expr
); VALIDATER(arith_expr
);
873 VALIDATER(term
); VALIDATER(factor
);
874 VALIDATER(atom
); VALIDATER(lambdef
);
875 VALIDATER(trailer
); VALIDATER(subscript
);
876 VALIDATER(subscriptlist
); VALIDATER(sliceop
);
877 VALIDATER(exprlist
); VALIDATER(dictmaker
);
878 VALIDATER(arglist
); VALIDATER(argument
);
879 VALIDATER(listmaker
); VALIDATER(yield_stmt
);
880 VALIDATER(testlist1
); VALIDATER(gen_for
);
881 VALIDATER(gen_iter
); VALIDATER(gen_if
);
882 VALIDATER(testlist_gexp
); VALIDATER(yield_expr
);
883 VALIDATER(yield_or_testlist
); VALIDATER(or_test
);
884 VALIDATER(old_test
); VALIDATER(old_lambdef
);
888 #define is_even(n) (((n) & 1) == 0)
889 #define is_odd(n) (((n) & 1) == 1)
893 validate_ntype(node
*n
, int t
)
896 PyErr_Format(parser_error
, "Expected node type %d, got %d.",
904 /* Verifies that the number of child nodes is exactly 'num', raising
905 * an exception if it isn't. The exception message does not indicate
906 * the exact number of nodes, allowing this to be used to raise the
907 * "right" exception when the wrong number of nodes is present in a
908 * specific variant of a statement's syntax. This is commonly used
912 validate_numnodes(node
*n
, int num
, const char *const name
)
915 PyErr_Format(parser_error
,
916 "Illegal number of children for %s node.", name
);
924 validate_terminal(node
*terminal
, int type
, char *string
)
926 int res
= (validate_ntype(terminal
, type
)
927 && ((string
== 0) || (strcmp(string
, STR(terminal
)) == 0)));
929 if (!res
&& !PyErr_Occurred()) {
930 PyErr_Format(parser_error
,
931 "Illegal terminal: expected \"%s\"", string
);
940 validate_repeating_list(node
*tree
, int ntype
, int (*vfunc
)(node
*),
941 const char *const name
)
944 int res
= (nch
&& validate_ntype(tree
, ntype
)
945 && vfunc(CHILD(tree
, 0)));
947 if (!res
&& !PyErr_Occurred())
948 (void) validate_numnodes(tree
, 1, name
);
951 res
= validate_comma(CHILD(tree
, --nch
));
952 if (res
&& nch
> 1) {
954 for ( ; res
&& pos
< nch
; pos
+= 2)
955 res
= (validate_comma(CHILD(tree
, pos
))
956 && vfunc(CHILD(tree
, pos
+ 1)));
966 * 'class' NAME ['(' testlist ')'] ':' suite
969 validate_class(node
*tree
)
972 int res
= (validate_ntype(tree
, classdef
) &&
973 ((nch
== 4) || (nch
== 6) || (nch
== 7)));
976 res
= (validate_name(CHILD(tree
, 0), "class")
977 && validate_ntype(CHILD(tree
, 1), NAME
)
978 && validate_colon(CHILD(tree
, nch
- 2))
979 && validate_suite(CHILD(tree
, nch
- 1)));
982 (void) validate_numnodes(tree
, 4, "class");
987 res
= ((validate_lparen(CHILD(tree
, 2)) &&
988 validate_testlist(CHILD(tree
, 3)) &&
989 validate_rparen(CHILD(tree
, 4))));
992 res
= (validate_lparen(CHILD(tree
,2)) &&
993 validate_rparen(CHILD(tree
,3)));
1001 * 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
1004 validate_if(node
*tree
)
1006 int nch
= NCH(tree
);
1007 int res
= (validate_ntype(tree
, if_stmt
)
1009 && validate_name(CHILD(tree
, 0), "if")
1010 && validate_test(CHILD(tree
, 1))
1011 && validate_colon(CHILD(tree
, 2))
1012 && validate_suite(CHILD(tree
, 3)));
1014 if (res
&& ((nch
% 4) == 3)) {
1015 /* ... 'else' ':' suite */
1016 res
= (validate_name(CHILD(tree
, nch
- 3), "else")
1017 && validate_colon(CHILD(tree
, nch
- 2))
1018 && validate_suite(CHILD(tree
, nch
- 1)));
1021 else if (!res
&& !PyErr_Occurred())
1022 (void) validate_numnodes(tree
, 4, "if");
1024 /* Will catch the case for nch < 4 */
1025 res
= validate_numnodes(tree
, 0, "if");
1026 else if (res
&& (nch
> 4)) {
1027 /* ... ('elif' test ':' suite)+ ... */
1029 while ((j
< nch
) && res
) {
1030 res
= (validate_name(CHILD(tree
, j
), "elif")
1031 && validate_colon(CHILD(tree
, j
+ 2))
1032 && validate_test(CHILD(tree
, j
+ 1))
1033 && validate_suite(CHILD(tree
, j
+ 3)));
1042 * '(' [varargslist] ')'
1046 validate_parameters(node
*tree
)
1048 int nch
= NCH(tree
);
1049 int res
= validate_ntype(tree
, parameters
) && ((nch
== 2) || (nch
== 3));
1052 res
= (validate_lparen(CHILD(tree
, 0))
1053 && validate_rparen(CHILD(tree
, nch
- 1)));
1054 if (res
&& (nch
== 3))
1055 res
= validate_varargslist(CHILD(tree
, 1));
1058 (void) validate_numnodes(tree
, 2, "parameters");
1068 * | NEWLINE INDENT stmt+ DEDENT
1071 validate_suite(node
*tree
)
1073 int nch
= NCH(tree
);
1074 int res
= (validate_ntype(tree
, suite
) && ((nch
== 1) || (nch
>= 4)));
1076 if (res
&& (nch
== 1))
1077 res
= validate_simple_stmt(CHILD(tree
, 0));
1079 /* NEWLINE INDENT stmt+ DEDENT */
1080 res
= (validate_newline(CHILD(tree
, 0))
1081 && validate_indent(CHILD(tree
, 1))
1082 && validate_stmt(CHILD(tree
, 2))
1083 && validate_dedent(CHILD(tree
, nch
- 1)));
1085 if (res
&& (nch
> 4)) {
1087 --nch
; /* forget the DEDENT */
1088 for ( ; res
&& (i
< nch
); ++i
)
1089 res
= validate_stmt(CHILD(tree
, i
));
1092 res
= validate_numnodes(tree
, 4, "suite");
1099 validate_testlist(node
*tree
)
1101 return (validate_repeating_list(tree
, testlist
,
1102 validate_test
, "testlist"));
1107 validate_testlist1(node
*tree
)
1109 return (validate_repeating_list(tree
, testlist1
,
1110 validate_test
, "testlist1"));
1115 validate_testlist_safe(node
*tree
)
1117 return (validate_repeating_list(tree
, testlist_safe
,
1118 validate_old_test
, "testlist_safe"));
1122 /* '*' NAME [',' '**' NAME] | '**' NAME
1125 validate_varargslist_trailer(node
*tree
, int start
)
1127 int nch
= NCH(tree
);
1132 err_string("expected variable argument trailer for varargslist");
1135 sym
= TYPE(CHILD(tree
, start
));
1138 * ('*' NAME [',' '**' NAME]
1141 res
= validate_name(CHILD(tree
, start
+1), NULL
);
1142 else if (nch
-start
== 5)
1143 res
= (validate_name(CHILD(tree
, start
+1), NULL
)
1144 && validate_comma(CHILD(tree
, start
+2))
1145 && validate_doublestar(CHILD(tree
, start
+3))
1146 && validate_name(CHILD(tree
, start
+4), NULL
));
1148 else if (sym
== DOUBLESTAR
) {
1153 res
= validate_name(CHILD(tree
, start
+1), NULL
);
1156 err_string("illegal variable argument trailer for varargslist");
1161 /* validate_varargslist()
1164 * (fpdef ['=' test] ',')*
1165 * ('*' NAME [',' '**' NAME]
1167 * | fpdef ['=' test] (',' fpdef ['=' test])* [',']
1171 validate_varargslist(node
*tree
)
1173 int nch
= NCH(tree
);
1174 int res
= validate_ntype(tree
, varargslist
) && (nch
!= 0);
1180 err_string("varargslist missing child nodes");
1183 sym
= TYPE(CHILD(tree
, 0));
1184 if (sym
== STAR
|| sym
== DOUBLESTAR
)
1185 /* whole thing matches:
1186 * '*' NAME [',' '**' NAME] | '**' NAME
1188 res
= validate_varargslist_trailer(tree
, 0);
1189 else if (sym
== fpdef
) {
1192 sym
= TYPE(CHILD(tree
, nch
-1));
1195 * (fpdef ['=' test] ',')+
1196 * ('*' NAME [',' '**' NAME]
1199 /* skip over (fpdef ['=' test] ',')+ */
1200 while (res
&& (i
+2 <= nch
)) {
1201 res
= validate_fpdef(CHILD(tree
, i
));
1203 if (res
&& TYPE(CHILD(tree
, i
)) == EQUAL
&& (i
+2 <= nch
)) {
1204 res
= (validate_equal(CHILD(tree
, i
))
1205 && validate_test(CHILD(tree
, i
+1)));
1209 if (res
&& i
< nch
) {
1210 res
= validate_comma(CHILD(tree
, i
));
1213 && (TYPE(CHILD(tree
, i
)) == DOUBLESTAR
1214 || TYPE(CHILD(tree
, i
)) == STAR
))
1218 /* ... '*' NAME [',' '**' NAME] | '**' NAME
1222 res
= validate_varargslist_trailer(tree
, i
);
1226 * fpdef ['=' test] (',' fpdef ['=' test])* [',']
1228 /* strip trailing comma node */
1230 res
= validate_comma(CHILD(tree
, nch
-1));
1236 * fpdef ['=' test] (',' fpdef ['=' test])*
1238 res
= validate_fpdef(CHILD(tree
, 0));
1240 if (res
&& (i
+2 <= nch
) && TYPE(CHILD(tree
, i
)) == EQUAL
) {
1241 res
= (validate_equal(CHILD(tree
, i
))
1242 && validate_test(CHILD(tree
, i
+1)));
1246 * ... (',' fpdef ['=' test])*
1249 while (res
&& (nch
- i
) >= 2) {
1250 res
= (validate_comma(CHILD(tree
, i
))
1251 && validate_fpdef(CHILD(tree
, i
+1)));
1253 if (res
&& (nch
- i
) >= 2 && TYPE(CHILD(tree
, i
)) == EQUAL
) {
1254 res
= (validate_equal(CHILD(tree
, i
))
1255 && validate_test(CHILD(tree
, i
+1)));
1259 if (res
&& nch
- i
!= 0) {
1261 err_string("illegal formation for varargslist");
1269 /* list_iter: list_for | list_if
1272 validate_list_iter(node
*tree
)
1274 int res
= (validate_ntype(tree
, list_iter
)
1275 && validate_numnodes(tree
, 1, "list_iter"));
1276 if (res
&& TYPE(CHILD(tree
, 0)) == list_for
)
1277 res
= validate_list_for(CHILD(tree
, 0));
1279 res
= validate_list_if(CHILD(tree
, 0));
1284 /* gen_iter: gen_for | gen_if
1287 validate_gen_iter(node
*tree
)
1289 int res
= (validate_ntype(tree
, gen_iter
)
1290 && validate_numnodes(tree
, 1, "gen_iter"));
1291 if (res
&& TYPE(CHILD(tree
, 0)) == gen_for
)
1292 res
= validate_gen_for(CHILD(tree
, 0));
1294 res
= validate_gen_if(CHILD(tree
, 0));
1299 /* list_for: 'for' exprlist 'in' testlist [list_iter]
1302 validate_list_for(node
*tree
)
1304 int nch
= NCH(tree
);
1308 res
= validate_list_iter(CHILD(tree
, 4));
1310 res
= validate_numnodes(tree
, 4, "list_for");
1313 res
= (validate_name(CHILD(tree
, 0), "for")
1314 && validate_exprlist(CHILD(tree
, 1))
1315 && validate_name(CHILD(tree
, 2), "in")
1316 && validate_testlist_safe(CHILD(tree
, 3)));
1321 /* gen_for: 'for' exprlist 'in' test [gen_iter]
1324 validate_gen_for(node
*tree
)
1326 int nch
= NCH(tree
);
1330 res
= validate_gen_iter(CHILD(tree
, 4));
1332 res
= validate_numnodes(tree
, 4, "gen_for");
1335 res
= (validate_name(CHILD(tree
, 0), "for")
1336 && validate_exprlist(CHILD(tree
, 1))
1337 && validate_name(CHILD(tree
, 2), "in")
1338 && validate_or_test(CHILD(tree
, 3)));
1343 /* list_if: 'if' old_test [list_iter]
1346 validate_list_if(node
*tree
)
1348 int nch
= NCH(tree
);
1352 res
= validate_list_iter(CHILD(tree
, 2));
1354 res
= validate_numnodes(tree
, 2, "list_if");
1357 res
= (validate_name(CHILD(tree
, 0), "if")
1358 && validate_old_test(CHILD(tree
, 1)));
1363 /* gen_if: 'if' old_test [gen_iter]
1366 validate_gen_if(node
*tree
)
1368 int nch
= NCH(tree
);
1372 res
= validate_gen_iter(CHILD(tree
, 2));
1374 res
= validate_numnodes(tree
, 2, "gen_if");
1377 res
= (validate_name(CHILD(tree
, 0), "if")
1378 && validate_old_test(CHILD(tree
, 1)));
1390 validate_fpdef(node
*tree
)
1392 int nch
= NCH(tree
);
1393 int res
= validate_ntype(tree
, fpdef
);
1397 res
= validate_ntype(CHILD(tree
, 0), NAME
);
1399 res
= (validate_lparen(CHILD(tree
, 0))
1400 && validate_fplist(CHILD(tree
, 1))
1401 && validate_rparen(CHILD(tree
, 2)));
1403 res
= validate_numnodes(tree
, 1, "fpdef");
1410 validate_fplist(node
*tree
)
1412 return (validate_repeating_list(tree
, fplist
,
1413 validate_fpdef
, "fplist"));
1417 /* simple_stmt | compound_stmt
1421 validate_stmt(node
*tree
)
1423 int res
= (validate_ntype(tree
, stmt
)
1424 && validate_numnodes(tree
, 1, "stmt"));
1427 tree
= CHILD(tree
, 0);
1429 if (TYPE(tree
) == simple_stmt
)
1430 res
= validate_simple_stmt(tree
);
1432 res
= validate_compound_stmt(tree
);
1438 /* small_stmt (';' small_stmt)* [';'] NEWLINE
1442 validate_simple_stmt(node
*tree
)
1444 int nch
= NCH(tree
);
1445 int res
= (validate_ntype(tree
, simple_stmt
)
1447 && validate_small_stmt(CHILD(tree
, 0))
1448 && validate_newline(CHILD(tree
, nch
- 1)));
1451 res
= validate_numnodes(tree
, 2, "simple_stmt");
1452 --nch
; /* forget the NEWLINE */
1453 if (res
&& is_even(nch
))
1454 res
= validate_semi(CHILD(tree
, --nch
));
1455 if (res
&& (nch
> 2)) {
1458 for (i
= 1; res
&& (i
< nch
); i
+= 2)
1459 res
= (validate_semi(CHILD(tree
, i
))
1460 && validate_small_stmt(CHILD(tree
, i
+ 1)));
1467 validate_small_stmt(node
*tree
)
1469 int nch
= NCH(tree
);
1470 int res
= validate_numnodes(tree
, 1, "small_stmt");
1473 int ntype
= TYPE(CHILD(tree
, 0));
1475 if ( (ntype
== expr_stmt
)
1476 || (ntype
== print_stmt
)
1477 || (ntype
== del_stmt
)
1478 || (ntype
== pass_stmt
)
1479 || (ntype
== flow_stmt
)
1480 || (ntype
== import_stmt
)
1481 || (ntype
== global_stmt
)
1482 || (ntype
== assert_stmt
)
1483 || (ntype
== exec_stmt
))
1484 res
= validate_node(CHILD(tree
, 0));
1487 err_string("illegal small_stmt child type");
1490 else if (nch
== 1) {
1492 PyErr_Format(parser_error
,
1493 "Unrecognized child node of small_stmt: %d.",
1494 TYPE(CHILD(tree
, 0)));
1501 * if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef | decorated
1504 validate_compound_stmt(node
*tree
)
1506 int res
= (validate_ntype(tree
, compound_stmt
)
1507 && validate_numnodes(tree
, 1, "compound_stmt"));
1513 tree
= CHILD(tree
, 0);
1515 if ( (ntype
== if_stmt
)
1516 || (ntype
== while_stmt
)
1517 || (ntype
== for_stmt
)
1518 || (ntype
== try_stmt
)
1519 || (ntype
== funcdef
)
1520 || (ntype
== classdef
)
1521 || (ntype
== decorated
))
1522 res
= validate_node(tree
);
1525 PyErr_Format(parser_error
,
1526 "Illegal compound statement type: %d.", TYPE(tree
));
1532 validate_yield_or_testlist(node
*tree
)
1534 if (TYPE(tree
) == yield_expr
)
1535 return validate_yield_expr(tree
);
1537 return validate_testlist(tree
);
1541 validate_expr_stmt(node
*tree
)
1544 int nch
= NCH(tree
);
1545 int res
= (validate_ntype(tree
, expr_stmt
)
1547 && validate_testlist(CHILD(tree
, 0)));
1550 && TYPE(CHILD(tree
, 1)) == augassign
) {
1551 res
= validate_numnodes(CHILD(tree
, 1), 1, "augassign")
1552 && validate_yield_or_testlist(CHILD(tree
, 2));
1555 char *s
= STR(CHILD(CHILD(tree
, 1), 0));
1557 res
= (strcmp(s
, "+=") == 0
1558 || strcmp(s
, "-=") == 0
1559 || strcmp(s
, "*=") == 0
1560 || strcmp(s
, "/=") == 0
1561 || strcmp(s
, "//=") == 0
1562 || strcmp(s
, "%=") == 0
1563 || strcmp(s
, "&=") == 0
1564 || strcmp(s
, "|=") == 0
1565 || strcmp(s
, "^=") == 0
1566 || strcmp(s
, "<<=") == 0
1567 || strcmp(s
, ">>=") == 0
1568 || strcmp(s
, "**=") == 0);
1570 err_string("illegal augmmented assignment operator");
1574 for (j
= 1; res
&& (j
< nch
); j
+= 2)
1575 res
= validate_equal(CHILD(tree
, j
))
1576 && validate_yield_or_testlist(CHILD(tree
, j
+ 1));
1584 * 'print' ( [ test (',' test)* [','] ]
1585 * | '>>' test [ (',' test)+ [','] ] )
1588 validate_print_stmt(node
*tree
)
1590 int nch
= NCH(tree
);
1591 int res
= (validate_ntype(tree
, print_stmt
)
1593 && validate_name(CHILD(tree
, 0), "print"));
1595 if (res
&& nch
> 1) {
1596 int sym
= TYPE(CHILD(tree
, 1));
1598 int allow_trailing_comma
= 1;
1601 res
= validate_test(CHILD(tree
, i
++));
1604 res
= validate_numnodes(tree
, 3, "print_stmt");
1606 res
= (validate_ntype(CHILD(tree
, i
), RIGHTSHIFT
)
1607 && validate_test(CHILD(tree
, i
+1)));
1609 allow_trailing_comma
= 0;
1613 /* ... (',' test)* [','] */
1614 while (res
&& i
+2 <= nch
) {
1615 res
= (validate_comma(CHILD(tree
, i
))
1616 && validate_test(CHILD(tree
, i
+1)));
1617 allow_trailing_comma
= 1;
1620 if (res
&& !allow_trailing_comma
)
1621 res
= validate_numnodes(tree
, i
, "print_stmt");
1622 else if (res
&& i
< nch
)
1623 res
= validate_comma(CHILD(tree
, i
));
1631 validate_del_stmt(node
*tree
)
1633 return (validate_numnodes(tree
, 2, "del_stmt")
1634 && validate_name(CHILD(tree
, 0), "del")
1635 && validate_exprlist(CHILD(tree
, 1)));
1640 validate_return_stmt(node
*tree
)
1642 int nch
= NCH(tree
);
1643 int res
= (validate_ntype(tree
, return_stmt
)
1644 && ((nch
== 1) || (nch
== 2))
1645 && validate_name(CHILD(tree
, 0), "return"));
1647 if (res
&& (nch
== 2))
1648 res
= validate_testlist(CHILD(tree
, 1));
1655 validate_raise_stmt(node
*tree
)
1657 int nch
= NCH(tree
);
1658 int res
= (validate_ntype(tree
, raise_stmt
)
1659 && ((nch
== 1) || (nch
== 2) || (nch
== 4) || (nch
== 6)));
1662 res
= validate_name(CHILD(tree
, 0), "raise");
1663 if (res
&& (nch
>= 2))
1664 res
= validate_test(CHILD(tree
, 1));
1665 if (res
&& nch
> 2) {
1666 res
= (validate_comma(CHILD(tree
, 2))
1667 && validate_test(CHILD(tree
, 3)));
1668 if (res
&& (nch
> 4))
1669 res
= (validate_comma(CHILD(tree
, 4))
1670 && validate_test(CHILD(tree
, 5)));
1674 (void) validate_numnodes(tree
, 2, "raise");
1675 if (res
&& (nch
== 4))
1676 res
= (validate_comma(CHILD(tree
, 2))
1677 && validate_test(CHILD(tree
, 3)));
1683 /* yield_expr: 'yield' [testlist]
1686 validate_yield_expr(node
*tree
)
1688 int nch
= NCH(tree
);
1689 int res
= (validate_ntype(tree
, yield_expr
)
1690 && ((nch
== 1) || (nch
== 2))
1691 && validate_name(CHILD(tree
, 0), "yield"));
1693 if (res
&& (nch
== 2))
1694 res
= validate_testlist(CHILD(tree
, 1));
1700 /* yield_stmt: yield_expr
1703 validate_yield_stmt(node
*tree
)
1705 return (validate_ntype(tree
, yield_stmt
)
1706 && validate_numnodes(tree
, 1, "yield_stmt")
1707 && validate_yield_expr(CHILD(tree
, 0)));
1712 validate_import_as_name(node
*tree
)
1714 int nch
= NCH(tree
);
1715 int ok
= validate_ntype(tree
, import_as_name
);
1719 ok
= validate_name(CHILD(tree
, 0), NULL
);
1721 ok
= (validate_name(CHILD(tree
, 0), NULL
)
1722 && validate_name(CHILD(tree
, 1), "as")
1723 && validate_name(CHILD(tree
, 2), NULL
));
1725 ok
= validate_numnodes(tree
, 3, "import_as_name");
1731 /* dotted_name: NAME ("." NAME)*
1734 validate_dotted_name(node
*tree
)
1736 int nch
= NCH(tree
);
1737 int res
= (validate_ntype(tree
, dotted_name
)
1739 && validate_name(CHILD(tree
, 0), NULL
));
1742 for (i
= 1; res
&& (i
< nch
); i
+= 2) {
1743 res
= (validate_dot(CHILD(tree
, i
))
1744 && validate_name(CHILD(tree
, i
+1), NULL
));
1750 /* dotted_as_name: dotted_name [NAME NAME]
1753 validate_dotted_as_name(node
*tree
)
1755 int nch
= NCH(tree
);
1756 int res
= validate_ntype(tree
, dotted_as_name
);
1760 res
= validate_dotted_name(CHILD(tree
, 0));
1762 res
= (validate_dotted_name(CHILD(tree
, 0))
1763 && validate_name(CHILD(tree
, 1), "as")
1764 && validate_name(CHILD(tree
, 2), NULL
));
1767 err_string("illegal number of children for dotted_as_name");
1774 /* dotted_as_name (',' dotted_as_name)* */
1776 validate_dotted_as_names(node
*tree
)
1778 int nch
= NCH(tree
);
1779 int res
= is_odd(nch
) && validate_dotted_as_name(CHILD(tree
, 0));
1782 for (i
= 1; res
&& (i
< nch
); i
+= 2)
1783 res
= (validate_comma(CHILD(tree
, i
))
1784 && validate_dotted_as_name(CHILD(tree
, i
+ 1)));
1789 /* import_as_name (',' import_as_name)* [','] */
1791 validate_import_as_names(node
*tree
)
1793 int nch
= NCH(tree
);
1794 int res
= validate_import_as_name(CHILD(tree
, 0));
1797 for (i
= 1; res
&& (i
+ 1 < nch
); i
+= 2)
1798 res
= (validate_comma(CHILD(tree
, i
))
1799 && validate_import_as_name(CHILD(tree
, i
+ 1)));
1804 /* 'import' dotted_as_names */
1806 validate_import_name(node
*tree
)
1808 return (validate_ntype(tree
, import_name
)
1809 && validate_numnodes(tree
, 2, "import_name")
1810 && validate_name(CHILD(tree
, 0), "import")
1811 && validate_dotted_as_names(CHILD(tree
, 1)));
1814 /* Helper function to count the number of leading dots in
1815 * 'from ...module import name'
1818 count_from_dots(node
*tree
)
1821 for (i
= 0; i
< NCH(tree
); i
++)
1822 if (TYPE(CHILD(tree
, i
)) != DOT
)
1827 /* 'from' ('.'* dotted_name | '.') 'import' ('*' | '(' import_as_names ')' |
1831 validate_import_from(node
*tree
)
1833 int nch
= NCH(tree
);
1834 int ndots
= count_from_dots(tree
);
1835 int havename
= (TYPE(CHILD(tree
, ndots
+ 1)) == dotted_name
);
1836 int offset
= ndots
+ havename
;
1837 int res
= validate_ntype(tree
, import_from
)
1838 && (nch
>= 4 + ndots
)
1839 && validate_name(CHILD(tree
, 0), "from")
1840 && (!havename
|| validate_dotted_name(CHILD(tree
, ndots
+ 1)))
1841 && validate_name(CHILD(tree
, offset
+ 1), "import");
1843 if (res
&& TYPE(CHILD(tree
, offset
+ 2)) == LPAR
)
1844 res
= ((nch
== offset
+ 5)
1845 && validate_lparen(CHILD(tree
, offset
+ 2))
1846 && validate_import_as_names(CHILD(tree
, offset
+ 3))
1847 && validate_rparen(CHILD(tree
, offset
+ 4)));
1848 else if (res
&& TYPE(CHILD(tree
, offset
+ 2)) != STAR
)
1849 res
= validate_import_as_names(CHILD(tree
, offset
+ 2));
1854 /* import_stmt: import_name | import_from */
1856 validate_import_stmt(node
*tree
)
1858 int nch
= NCH(tree
);
1859 int res
= validate_numnodes(tree
, 1, "import_stmt");
1862 int ntype
= TYPE(CHILD(tree
, 0));
1864 if (ntype
== import_name
|| ntype
== import_from
)
1865 res
= validate_node(CHILD(tree
, 0));
1868 err_string("illegal import_stmt child type");
1871 else if (nch
== 1) {
1873 PyErr_Format(parser_error
,
1874 "Unrecognized child node of import_stmt: %d.",
1875 TYPE(CHILD(tree
, 0)));
1884 validate_global_stmt(node
*tree
)
1887 int nch
= NCH(tree
);
1888 int res
= (validate_ntype(tree
, global_stmt
)
1889 && is_even(nch
) && (nch
>= 2));
1891 if (!res
&& !PyErr_Occurred())
1892 err_string("illegal global statement");
1895 res
= (validate_name(CHILD(tree
, 0), "global")
1896 && validate_ntype(CHILD(tree
, 1), NAME
));
1897 for (j
= 2; res
&& (j
< nch
); j
+= 2)
1898 res
= (validate_comma(CHILD(tree
, j
))
1899 && validate_ntype(CHILD(tree
, j
+ 1), NAME
));
1907 * 'exec' expr ['in' test [',' test]]
1910 validate_exec_stmt(node
*tree
)
1912 int nch
= NCH(tree
);
1913 int res
= (validate_ntype(tree
, exec_stmt
)
1914 && ((nch
== 2) || (nch
== 4) || (nch
== 6))
1915 && validate_name(CHILD(tree
, 0), "exec")
1916 && validate_expr(CHILD(tree
, 1)));
1918 if (!res
&& !PyErr_Occurred())
1919 err_string("illegal exec statement");
1920 if (res
&& (nch
> 2))
1921 res
= (validate_name(CHILD(tree
, 2), "in")
1922 && validate_test(CHILD(tree
, 3)));
1923 if (res
&& (nch
== 6))
1924 res
= (validate_comma(CHILD(tree
, 4))
1925 && validate_test(CHILD(tree
, 5)));
1933 * 'assert' test [',' test]
1936 validate_assert_stmt(node
*tree
)
1938 int nch
= NCH(tree
);
1939 int res
= (validate_ntype(tree
, assert_stmt
)
1940 && ((nch
== 2) || (nch
== 4))
1941 && (validate_name(CHILD(tree
, 0), "assert"))
1942 && validate_test(CHILD(tree
, 1)));
1944 if (!res
&& !PyErr_Occurred())
1945 err_string("illegal assert statement");
1946 if (res
&& (nch
> 2))
1947 res
= (validate_comma(CHILD(tree
, 2))
1948 && validate_test(CHILD(tree
, 3)));
1955 validate_while(node
*tree
)
1957 int nch
= NCH(tree
);
1958 int res
= (validate_ntype(tree
, while_stmt
)
1959 && ((nch
== 4) || (nch
== 7))
1960 && validate_name(CHILD(tree
, 0), "while")
1961 && validate_test(CHILD(tree
, 1))
1962 && validate_colon(CHILD(tree
, 2))
1963 && validate_suite(CHILD(tree
, 3)));
1965 if (res
&& (nch
== 7))
1966 res
= (validate_name(CHILD(tree
, 4), "else")
1967 && validate_colon(CHILD(tree
, 5))
1968 && validate_suite(CHILD(tree
, 6)));
1975 validate_for(node
*tree
)
1977 int nch
= NCH(tree
);
1978 int res
= (validate_ntype(tree
, for_stmt
)
1979 && ((nch
== 6) || (nch
== 9))
1980 && validate_name(CHILD(tree
, 0), "for")
1981 && validate_exprlist(CHILD(tree
, 1))
1982 && validate_name(CHILD(tree
, 2), "in")
1983 && validate_testlist(CHILD(tree
, 3))
1984 && validate_colon(CHILD(tree
, 4))
1985 && validate_suite(CHILD(tree
, 5)));
1987 if (res
&& (nch
== 9))
1988 res
= (validate_name(CHILD(tree
, 6), "else")
1989 && validate_colon(CHILD(tree
, 7))
1990 && validate_suite(CHILD(tree
, 8)));
1997 * 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
1998 * | 'try' ':' suite 'finally' ':' suite
2002 validate_try(node
*tree
)
2004 int nch
= NCH(tree
);
2006 int res
= (validate_ntype(tree
, try_stmt
)
2007 && (nch
>= 6) && ((nch
% 3) == 0));
2010 res
= (validate_name(CHILD(tree
, 0), "try")
2011 && validate_colon(CHILD(tree
, 1))
2012 && validate_suite(CHILD(tree
, 2))
2013 && validate_colon(CHILD(tree
, nch
- 2))
2014 && validate_suite(CHILD(tree
, nch
- 1)));
2015 else if (!PyErr_Occurred()) {
2016 const char* name
= "except";
2017 if (TYPE(CHILD(tree
, nch
- 3)) != except_clause
)
2018 name
= STR(CHILD(tree
, nch
- 3));
2020 PyErr_Format(parser_error
,
2021 "Illegal number of children for try/%s node.", name
);
2023 /* Skip past except_clause sections: */
2024 while (res
&& (TYPE(CHILD(tree
, pos
)) == except_clause
)) {
2025 res
= (validate_except_clause(CHILD(tree
, pos
))
2026 && validate_colon(CHILD(tree
, pos
+ 1))
2027 && validate_suite(CHILD(tree
, pos
+ 2)));
2030 if (res
&& (pos
< nch
)) {
2031 res
= validate_ntype(CHILD(tree
, pos
), NAME
);
2032 if (res
&& (strcmp(STR(CHILD(tree
, pos
)), "finally") == 0))
2033 res
= (validate_numnodes(tree
, 6, "try/finally")
2034 && validate_colon(CHILD(tree
, 4))
2035 && validate_suite(CHILD(tree
, 5)));
2037 if (nch
== (pos
+ 3)) {
2038 res
= ((strcmp(STR(CHILD(tree
, pos
)), "except") == 0)
2039 || (strcmp(STR(CHILD(tree
, pos
)), "else") == 0));
2041 err_string("illegal trailing triple in try statement");
2043 else if (nch
== (pos
+ 6)) {
2044 res
= (validate_name(CHILD(tree
, pos
), "except")
2045 && validate_colon(CHILD(tree
, pos
+ 1))
2046 && validate_suite(CHILD(tree
, pos
+ 2))
2047 && validate_name(CHILD(tree
, pos
+ 3), "else"));
2050 res
= validate_numnodes(tree
, pos
+ 3, "try/except");
2058 validate_except_clause(node
*tree
)
2060 int nch
= NCH(tree
);
2061 int res
= (validate_ntype(tree
, except_clause
)
2062 && ((nch
== 1) || (nch
== 2) || (nch
== 4))
2063 && validate_name(CHILD(tree
, 0), "except"));
2065 if (res
&& (nch
> 1))
2066 res
= validate_test(CHILD(tree
, 1));
2067 if (res
&& (nch
== 4))
2068 res
= (validate_comma(CHILD(tree
, 2))
2069 && validate_test(CHILD(tree
, 3)));
2076 validate_test(node
*tree
)
2078 int nch
= NCH(tree
);
2079 int res
= validate_ntype(tree
, test
) && is_odd(nch
);
2081 if (res
&& (TYPE(CHILD(tree
, 0)) == lambdef
))
2083 && validate_lambdef(CHILD(tree
, 0)));
2085 res
= validate_or_test(CHILD(tree
, 0));
2086 res
= (res
&& (nch
== 1 || (nch
== 5 &&
2087 validate_name(CHILD(tree
, 1), "if") &&
2088 validate_or_test(CHILD(tree
, 2)) &&
2089 validate_name(CHILD(tree
, 3), "else") &&
2090 validate_test(CHILD(tree
, 4)))));
2096 validate_old_test(node
*tree
)
2098 int nch
= NCH(tree
);
2099 int res
= validate_ntype(tree
, old_test
) && (nch
== 1);
2101 if (res
&& (TYPE(CHILD(tree
, 0)) == old_lambdef
))
2102 res
= (validate_old_lambdef(CHILD(tree
, 0)));
2104 res
= (validate_or_test(CHILD(tree
, 0)));
2110 validate_or_test(node
*tree
)
2112 int nch
= NCH(tree
);
2113 int res
= validate_ntype(tree
, or_test
) && is_odd(nch
);
2117 res
= validate_and_test(CHILD(tree
, 0));
2118 for (pos
= 1; res
&& (pos
< nch
); pos
+= 2)
2119 res
= (validate_name(CHILD(tree
, pos
), "or")
2120 && validate_and_test(CHILD(tree
, pos
+ 1)));
2127 validate_and_test(node
*tree
)
2130 int nch
= NCH(tree
);
2131 int res
= (validate_ntype(tree
, and_test
)
2133 && validate_not_test(CHILD(tree
, 0)));
2135 for (pos
= 1; res
&& (pos
< nch
); pos
+= 2)
2136 res
= (validate_name(CHILD(tree
, pos
), "and")
2137 && validate_not_test(CHILD(tree
, 0)));
2144 validate_not_test(node
*tree
)
2146 int nch
= NCH(tree
);
2147 int res
= validate_ntype(tree
, not_test
) && ((nch
== 1) || (nch
== 2));
2151 res
= (validate_name(CHILD(tree
, 0), "not")
2152 && validate_not_test(CHILD(tree
, 1)));
2154 res
= validate_comparison(CHILD(tree
, 0));
2161 validate_comparison(node
*tree
)
2164 int nch
= NCH(tree
);
2165 int res
= (validate_ntype(tree
, comparison
)
2167 && validate_expr(CHILD(tree
, 0)));
2169 for (pos
= 1; res
&& (pos
< nch
); pos
+= 2)
2170 res
= (validate_comp_op(CHILD(tree
, pos
))
2171 && validate_expr(CHILD(tree
, pos
+ 1)));
2178 validate_comp_op(node
*tree
)
2181 int nch
= NCH(tree
);
2183 if (!validate_ntype(tree
, comp_op
))
2187 * Only child will be a terminal with a well-defined symbolic name
2188 * or a NAME with a string of either 'is' or 'in'
2190 tree
= CHILD(tree
, 0);
2191 switch (TYPE(tree
)) {
2202 res
= ((strcmp(STR(tree
), "in") == 0)
2203 || (strcmp(STR(tree
), "is") == 0));
2205 PyErr_Format(parser_error
,
2206 "illegal operator '%s'", STR(tree
));
2210 err_string("illegal comparison operator type");
2214 else if ((res
= validate_numnodes(tree
, 2, "comp_op")) != 0) {
2215 res
= (validate_ntype(CHILD(tree
, 0), NAME
)
2216 && validate_ntype(CHILD(tree
, 1), NAME
)
2217 && (((strcmp(STR(CHILD(tree
, 0)), "is") == 0)
2218 && (strcmp(STR(CHILD(tree
, 1)), "not") == 0))
2219 || ((strcmp(STR(CHILD(tree
, 0)), "not") == 0)
2220 && (strcmp(STR(CHILD(tree
, 1)), "in") == 0))));
2221 if (!res
&& !PyErr_Occurred())
2222 err_string("unknown comparison operator");
2229 validate_expr(node
*tree
)
2232 int nch
= NCH(tree
);
2233 int res
= (validate_ntype(tree
, expr
)
2235 && validate_xor_expr(CHILD(tree
, 0)));
2237 for (j
= 2; res
&& (j
< nch
); j
+= 2)
2238 res
= (validate_xor_expr(CHILD(tree
, j
))
2239 && validate_vbar(CHILD(tree
, j
- 1)));
2246 validate_xor_expr(node
*tree
)
2249 int nch
= NCH(tree
);
2250 int res
= (validate_ntype(tree
, xor_expr
)
2252 && validate_and_expr(CHILD(tree
, 0)));
2254 for (j
= 2; res
&& (j
< nch
); j
+= 2)
2255 res
= (validate_circumflex(CHILD(tree
, j
- 1))
2256 && validate_and_expr(CHILD(tree
, j
)));
2263 validate_and_expr(node
*tree
)
2266 int nch
= NCH(tree
);
2267 int res
= (validate_ntype(tree
, and_expr
)
2269 && validate_shift_expr(CHILD(tree
, 0)));
2271 for (pos
= 1; res
&& (pos
< nch
); pos
+= 2)
2272 res
= (validate_ampersand(CHILD(tree
, pos
))
2273 && validate_shift_expr(CHILD(tree
, pos
+ 1)));
2280 validate_chain_two_ops(node
*tree
, int (*termvalid
)(node
*), int op1
, int op2
)
2283 int nch
= NCH(tree
);
2284 int res
= (is_odd(nch
)
2285 && (*termvalid
)(CHILD(tree
, 0)));
2287 for ( ; res
&& (pos
< nch
); pos
+= 2) {
2288 if (TYPE(CHILD(tree
, pos
)) != op1
)
2289 res
= validate_ntype(CHILD(tree
, pos
), op2
);
2291 res
= (*termvalid
)(CHILD(tree
, pos
+ 1));
2298 validate_shift_expr(node
*tree
)
2300 return (validate_ntype(tree
, shift_expr
)
2301 && validate_chain_two_ops(tree
, validate_arith_expr
,
2302 LEFTSHIFT
, RIGHTSHIFT
));
2307 validate_arith_expr(node
*tree
)
2309 return (validate_ntype(tree
, arith_expr
)
2310 && validate_chain_two_ops(tree
, validate_term
, PLUS
, MINUS
));
2315 validate_term(node
*tree
)
2318 int nch
= NCH(tree
);
2319 int res
= (validate_ntype(tree
, term
)
2321 && validate_factor(CHILD(tree
, 0)));
2323 for ( ; res
&& (pos
< nch
); pos
+= 2)
2324 res
= (((TYPE(CHILD(tree
, pos
)) == STAR
)
2325 || (TYPE(CHILD(tree
, pos
)) == SLASH
)
2326 || (TYPE(CHILD(tree
, pos
)) == DOUBLESLASH
)
2327 || (TYPE(CHILD(tree
, pos
)) == PERCENT
))
2328 && validate_factor(CHILD(tree
, pos
+ 1)));
2336 * factor: ('+'|'-'|'~') factor | power
2339 validate_factor(node
*tree
)
2341 int nch
= NCH(tree
);
2342 int res
= (validate_ntype(tree
, factor
)
2344 && ((TYPE(CHILD(tree
, 0)) == PLUS
)
2345 || (TYPE(CHILD(tree
, 0)) == MINUS
)
2346 || (TYPE(CHILD(tree
, 0)) == TILDE
))
2347 && validate_factor(CHILD(tree
, 1)))
2349 && validate_power(CHILD(tree
, 0)))));
2356 * power: atom trailer* ('**' factor)*
2359 validate_power(node
*tree
)
2362 int nch
= NCH(tree
);
2363 int res
= (validate_ntype(tree
, power
) && (nch
>= 1)
2364 && validate_atom(CHILD(tree
, 0)));
2366 while (res
&& (pos
< nch
) && (TYPE(CHILD(tree
, pos
)) == trailer
))
2367 res
= validate_trailer(CHILD(tree
, pos
++));
2368 if (res
&& (pos
< nch
)) {
2369 if (!is_even(nch
- pos
)) {
2370 err_string("illegal number of nodes for 'power'");
2373 for ( ; res
&& (pos
< (nch
- 1)); pos
+= 2)
2374 res
= (validate_doublestar(CHILD(tree
, pos
))
2375 && validate_factor(CHILD(tree
, pos
+ 1)));
2382 validate_atom(node
*tree
)
2385 int nch
= NCH(tree
);
2386 int res
= validate_ntype(tree
, atom
);
2389 res
= validate_numnodes(tree
, nch
+1, "atom");
2391 switch (TYPE(CHILD(tree
, 0))) {
2394 && (validate_rparen(CHILD(tree
, nch
- 1))));
2396 if (res
&& (nch
== 3)) {
2397 if (TYPE(CHILD(tree
, 1))==yield_expr
)
2398 res
= validate_yield_expr(CHILD(tree
, 1));
2400 res
= validate_testlist_gexp(CHILD(tree
, 1));
2405 res
= validate_ntype(CHILD(tree
, 1), RSQB
);
2407 res
= (validate_listmaker(CHILD(tree
, 1))
2408 && validate_ntype(CHILD(tree
, 2), RSQB
));
2411 err_string("illegal list display atom");
2416 && validate_ntype(CHILD(tree
, nch
- 1), RBRACE
));
2418 if (res
&& (nch
== 3))
2419 res
= validate_dictmaker(CHILD(tree
, 1));
2423 && validate_testlist1(CHILD(tree
, 1))
2424 && validate_ntype(CHILD(tree
, 2), BACKQUOTE
));
2431 for (pos
= 1; res
&& (pos
< nch
); ++pos
)
2432 res
= validate_ntype(CHILD(tree
, pos
), STRING
);
2444 * test ( list_for | (',' test)* [','] )
2447 validate_listmaker(node
*tree
)
2449 int nch
= NCH(tree
);
2453 err_string("missing child nodes of listmaker");
2455 ok
= validate_test(CHILD(tree
, 0));
2458 * list_for | (',' test)* [',']
2460 if (nch
== 2 && TYPE(CHILD(tree
, 1)) == list_for
)
2461 ok
= validate_list_for(CHILD(tree
, 1));
2463 /* (',' test)* [','] */
2465 while (ok
&& nch
- i
>= 2) {
2466 ok
= (validate_comma(CHILD(tree
, i
))
2467 && validate_test(CHILD(tree
, i
+1)));
2470 if (ok
&& i
== nch
-1)
2471 ok
= validate_comma(CHILD(tree
, i
));
2472 else if (i
!= nch
) {
2474 err_string("illegal trailing nodes for listmaker");
2481 * test ( gen_for | (',' test)* [','] )
2484 validate_testlist_gexp(node
*tree
)
2486 int nch
= NCH(tree
);
2490 err_string("missing child nodes of testlist_gexp");
2492 ok
= validate_test(CHILD(tree
, 0));
2496 * gen_for | (',' test)* [',']
2498 if (nch
== 2 && TYPE(CHILD(tree
, 1)) == gen_for
)
2499 ok
= validate_gen_for(CHILD(tree
, 1));
2501 /* (',' test)* [','] */
2503 while (ok
&& nch
- i
>= 2) {
2504 ok
= (validate_comma(CHILD(tree
, i
))
2505 && validate_test(CHILD(tree
, i
+1)));
2508 if (ok
&& i
== nch
-1)
2509 ok
= validate_comma(CHILD(tree
, i
));
2510 else if (i
!= nch
) {
2512 err_string("illegal trailing nodes for testlist_gexp");
2519 * '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
2522 validate_decorator(node
*tree
)
2525 int nch
= NCH(tree
);
2526 ok
= (validate_ntype(tree
, decorator
) &&
2527 (nch
== 3 || nch
== 5 || nch
== 6) &&
2528 validate_at(CHILD(tree
, 0)) &&
2529 validate_dotted_name(CHILD(tree
, 1)) &&
2530 validate_newline(RCHILD(tree
, -1)));
2532 if (ok
&& nch
!= 3) {
2533 ok
= (validate_lparen(CHILD(tree
, 2)) &&
2534 validate_rparen(RCHILD(tree
, -2)));
2537 ok
= validate_arglist(CHILD(tree
, 3));
2547 validate_decorators(node
*tree
)
2551 ok
= validate_ntype(tree
, decorators
) && nch
>= 1;
2553 for (i
= 0; ok
&& i
< nch
; ++i
)
2554 ok
= validate_decorator(CHILD(tree
, i
));
2562 * 'def' NAME parameters ':' suite
2565 validate_funcdef(node
*tree
)
2567 int nch
= NCH(tree
);
2568 int ok
= (validate_ntype(tree
, funcdef
)
2570 && validate_name(RCHILD(tree
, -5), "def")
2571 && validate_ntype(RCHILD(tree
, -4), NAME
)
2572 && validate_colon(RCHILD(tree
, -2))
2573 && validate_parameters(RCHILD(tree
, -3))
2574 && validate_suite(RCHILD(tree
, -1)));
2580 * decorators (classdef | funcdef)
2583 validate_decorated(node
*tree
)
2585 int nch
= NCH(tree
);
2586 int ok
= (validate_ntype(tree
, decorated
)
2588 && validate_decorators(RCHILD(tree
, -2))
2589 && (validate_funcdef(RCHILD(tree
, -1))
2590 || validate_class(RCHILD(tree
, -1)))
2596 validate_lambdef(node
*tree
)
2598 int nch
= NCH(tree
);
2599 int res
= (validate_ntype(tree
, lambdef
)
2600 && ((nch
== 3) || (nch
== 4))
2601 && validate_name(CHILD(tree
, 0), "lambda")
2602 && validate_colon(CHILD(tree
, nch
- 2))
2603 && validate_test(CHILD(tree
, nch
- 1)));
2605 if (res
&& (nch
== 4))
2606 res
= validate_varargslist(CHILD(tree
, 1));
2607 else if (!res
&& !PyErr_Occurred())
2608 (void) validate_numnodes(tree
, 3, "lambdef");
2615 validate_old_lambdef(node
*tree
)
2617 int nch
= NCH(tree
);
2618 int res
= (validate_ntype(tree
, old_lambdef
)
2619 && ((nch
== 3) || (nch
== 4))
2620 && validate_name(CHILD(tree
, 0), "lambda")
2621 && validate_colon(CHILD(tree
, nch
- 2))
2622 && validate_test(CHILD(tree
, nch
- 1)));
2624 if (res
&& (nch
== 4))
2625 res
= validate_varargslist(CHILD(tree
, 1));
2626 else if (!res
&& !PyErr_Occurred())
2627 (void) validate_numnodes(tree
, 3, "old_lambdef");
2635 * (argument ',')* (argument [','] | '*' test [',' '**' test] | '**' test)
2638 validate_arglist(node
*tree
)
2640 int nch
= NCH(tree
);
2645 /* raise the right error from having an invalid number of children */
2646 return validate_numnodes(tree
, nch
+ 1, "arglist");
2649 for (i
=0; i
<nch
; i
++) {
2650 if (TYPE(CHILD(tree
, i
)) == argument
) {
2651 node
*ch
= CHILD(tree
, i
);
2652 if (NCH(ch
) == 2 && TYPE(CHILD(ch
, 1)) == gen_for
) {
2653 err_string("need '(', ')' for generator expression");
2660 while (ok
&& nch
-i
>= 2) {
2661 /* skip leading (argument ',') */
2662 ok
= (validate_argument(CHILD(tree
, i
))
2663 && validate_comma(CHILD(tree
, i
+1)));
2672 * argument | '*' test [',' '**' test] | '**' test
2674 int sym
= TYPE(CHILD(tree
, i
));
2676 if (sym
== argument
) {
2677 ok
= validate_argument(CHILD(tree
, i
));
2678 if (ok
&& i
+1 != nch
) {
2679 err_string("illegal arglist specification"
2680 " (extra stuff on end)");
2684 else if (sym
== STAR
) {
2685 ok
= validate_star(CHILD(tree
, i
));
2686 if (ok
&& (nch
-i
== 2))
2687 ok
= validate_test(CHILD(tree
, i
+1));
2688 else if (ok
&& (nch
-i
== 5))
2689 ok
= (validate_test(CHILD(tree
, i
+1))
2690 && validate_comma(CHILD(tree
, i
+2))
2691 && validate_doublestar(CHILD(tree
, i
+3))
2692 && validate_test(CHILD(tree
, i
+4)));
2694 err_string("illegal use of '*' in arglist");
2698 else if (sym
== DOUBLESTAR
) {
2700 ok
= (validate_doublestar(CHILD(tree
, i
))
2701 && validate_test(CHILD(tree
, i
+1)));
2703 err_string("illegal use of '**' in arglist");
2708 err_string("illegal arglist specification");
2719 * [test '='] test [gen_for]
2722 validate_argument(node
*tree
)
2724 int nch
= NCH(tree
);
2725 int res
= (validate_ntype(tree
, argument
)
2726 && ((nch
== 1) || (nch
== 2) || (nch
== 3))
2727 && validate_test(CHILD(tree
, 0)));
2729 if (res
&& (nch
== 2))
2730 res
= validate_gen_for(CHILD(tree
, 1));
2731 else if (res
&& (nch
== 3))
2732 res
= (validate_equal(CHILD(tree
, 1))
2733 && validate_test(CHILD(tree
, 2)));
2742 * '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
2745 validate_trailer(node
*tree
)
2747 int nch
= NCH(tree
);
2748 int res
= validate_ntype(tree
, trailer
) && ((nch
== 2) || (nch
== 3));
2751 switch (TYPE(CHILD(tree
, 0))) {
2753 res
= validate_rparen(CHILD(tree
, nch
- 1));
2754 if (res
&& (nch
== 3))
2755 res
= validate_arglist(CHILD(tree
, 1));
2758 res
= (validate_numnodes(tree
, 3, "trailer")
2759 && validate_subscriptlist(CHILD(tree
, 1))
2760 && validate_ntype(CHILD(tree
, 2), RSQB
));
2763 res
= (validate_numnodes(tree
, 2, "trailer")
2764 && validate_ntype(CHILD(tree
, 1), NAME
));
2772 (void) validate_numnodes(tree
, 2, "trailer");
2780 * subscript (',' subscript)* [',']
2783 validate_subscriptlist(node
*tree
)
2785 return (validate_repeating_list(tree
, subscriptlist
,
2786 validate_subscript
, "subscriptlist"));
2792 * '.' '.' '.' | test | [test] ':' [test] [sliceop]
2795 validate_subscript(node
*tree
)
2798 int nch
= NCH(tree
);
2799 int res
= validate_ntype(tree
, subscript
) && (nch
>= 1) && (nch
<= 4);
2802 if (!PyErr_Occurred())
2803 err_string("invalid number of arguments for subscript node");
2806 if (TYPE(CHILD(tree
, 0)) == DOT
)
2807 /* take care of ('.' '.' '.') possibility */
2808 return (validate_numnodes(tree
, 3, "subscript")
2809 && validate_dot(CHILD(tree
, 0))
2810 && validate_dot(CHILD(tree
, 1))
2811 && validate_dot(CHILD(tree
, 2)));
2813 if (TYPE(CHILD(tree
, 0)) == test
)
2814 res
= validate_test(CHILD(tree
, 0));
2816 res
= validate_colon(CHILD(tree
, 0));
2819 /* Must be [test] ':' [test] [sliceop],
2820 * but at least one of the optional components will
2821 * be present, but we don't know which yet.
2823 if ((TYPE(CHILD(tree
, 0)) != COLON
) || (nch
== 4)) {
2824 res
= validate_test(CHILD(tree
, 0));
2828 res
= validate_colon(CHILD(tree
, offset
));
2830 int rem
= nch
- ++offset
;
2832 if (TYPE(CHILD(tree
, offset
)) == test
) {
2833 res
= validate_test(CHILD(tree
, offset
));
2838 res
= validate_sliceop(CHILD(tree
, offset
));
2846 validate_sliceop(node
*tree
)
2848 int nch
= NCH(tree
);
2849 int res
= ((nch
== 1) || validate_numnodes(tree
, 2, "sliceop"))
2850 && validate_ntype(tree
, sliceop
);
2851 if (!res
&& !PyErr_Occurred()) {
2852 res
= validate_numnodes(tree
, 1, "sliceop");
2855 res
= validate_colon(CHILD(tree
, 0));
2856 if (res
&& (nch
== 2))
2857 res
= validate_test(CHILD(tree
, 1));
2864 validate_exprlist(node
*tree
)
2866 return (validate_repeating_list(tree
, exprlist
,
2867 validate_expr
, "exprlist"));
2872 validate_dictmaker(node
*tree
)
2874 int nch
= NCH(tree
);
2875 int res
= (validate_ntype(tree
, dictmaker
)
2877 && validate_test(CHILD(tree
, 0))
2878 && validate_colon(CHILD(tree
, 1))
2879 && validate_test(CHILD(tree
, 2)));
2881 if (res
&& ((nch
% 4) == 0))
2882 res
= validate_comma(CHILD(tree
, --nch
));
2884 res
= ((nch
% 4) == 3);
2886 if (res
&& (nch
> 3)) {
2888 /* ( ',' test ':' test )* */
2889 while (res
&& (pos
< nch
)) {
2890 res
= (validate_comma(CHILD(tree
, pos
))
2891 && validate_test(CHILD(tree
, pos
+ 1))
2892 && validate_colon(CHILD(tree
, pos
+ 2))
2893 && validate_test(CHILD(tree
, pos
+ 3)));
2902 validate_eval_input(node
*tree
)
2905 int nch
= NCH(tree
);
2906 int res
= (validate_ntype(tree
, eval_input
)
2908 && validate_testlist(CHILD(tree
, 0))
2909 && validate_ntype(CHILD(tree
, nch
- 1), ENDMARKER
));
2911 for (pos
= 1; res
&& (pos
< (nch
- 1)); ++pos
)
2912 res
= validate_ntype(CHILD(tree
, pos
), NEWLINE
);
2919 validate_node(node
*tree
)
2921 int nch
= 0; /* num. children on current node */
2922 int res
= 1; /* result value */
2923 node
* next
= 0; /* node to process after this one */
2925 while (res
&& (tree
!= 0)) {
2928 switch (TYPE(tree
)) {
2933 res
= validate_funcdef(tree
);
2936 res
= validate_class(tree
);
2939 res
= validate_decorated(tree
);
2942 * "Trivial" parse tree nodes.
2943 * (Why did I call these trivial?)
2946 res
= validate_stmt(tree
);
2950 * expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt
2951 * | import_stmt | global_stmt | exec_stmt | assert_stmt
2953 res
= validate_small_stmt(tree
);
2956 res
= (validate_numnodes(tree
, 1, "flow_stmt")
2957 && ((TYPE(CHILD(tree
, 0)) == break_stmt
)
2958 || (TYPE(CHILD(tree
, 0)) == continue_stmt
)
2959 || (TYPE(CHILD(tree
, 0)) == yield_stmt
)
2960 || (TYPE(CHILD(tree
, 0)) == return_stmt
)
2961 || (TYPE(CHILD(tree
, 0)) == raise_stmt
)));
2963 next
= CHILD(tree
, 0);
2965 err_string("illegal flow_stmt type");
2968 res
= validate_yield_stmt(tree
);
2971 * Compound statements.
2974 res
= validate_simple_stmt(tree
);
2977 res
= validate_compound_stmt(tree
);
2980 * Fundamental statements.
2983 res
= validate_expr_stmt(tree
);
2986 res
= validate_print_stmt(tree
);
2989 res
= validate_del_stmt(tree
);
2992 res
= (validate_numnodes(tree
, 1, "pass")
2993 && validate_name(CHILD(tree
, 0), "pass"));
2996 res
= (validate_numnodes(tree
, 1, "break")
2997 && validate_name(CHILD(tree
, 0), "break"));
3000 res
= (validate_numnodes(tree
, 1, "continue")
3001 && validate_name(CHILD(tree
, 0), "continue"));
3004 res
= validate_return_stmt(tree
);
3007 res
= validate_raise_stmt(tree
);
3010 res
= validate_import_stmt(tree
);
3013 res
= validate_import_name(tree
);
3016 res
= validate_import_from(tree
);
3019 res
= validate_global_stmt(tree
);
3022 res
= validate_exec_stmt(tree
);
3025 res
= validate_assert_stmt(tree
);
3028 res
= validate_if(tree
);
3031 res
= validate_while(tree
);
3034 res
= validate_for(tree
);
3037 res
= validate_try(tree
);
3040 res
= validate_suite(tree
);
3046 res
= validate_testlist(tree
);
3049 res
= validate_yield_expr(tree
);
3052 res
= validate_testlist1(tree
);
3055 res
= validate_test(tree
);
3058 res
= validate_and_test(tree
);
3061 res
= validate_not_test(tree
);
3064 res
= validate_comparison(tree
);
3067 res
= validate_exprlist(tree
);
3070 res
= validate_comp_op(tree
);
3073 res
= validate_expr(tree
);
3076 res
= validate_xor_expr(tree
);
3079 res
= validate_and_expr(tree
);
3082 res
= validate_shift_expr(tree
);
3085 res
= validate_arith_expr(tree
);
3088 res
= validate_term(tree
);
3091 res
= validate_factor(tree
);
3094 res
= validate_power(tree
);
3097 res
= validate_atom(tree
);
3101 /* Hopefully never reached! */
3102 err_string("unrecognized node type");
3113 validate_expr_tree(node
*tree
)
3115 int res
= validate_eval_input(tree
);
3117 if (!res
&& !PyErr_Occurred())
3118 err_string("could not validate expression tuple");
3125 * (NEWLINE | stmt)* ENDMARKER
3128 validate_file_input(node
*tree
)
3131 int nch
= NCH(tree
) - 1;
3132 int res
= ((nch
>= 0)
3133 && validate_ntype(CHILD(tree
, nch
), ENDMARKER
));
3135 for (j
= 0; res
&& (j
< nch
); ++j
) {
3136 if (TYPE(CHILD(tree
, j
)) == stmt
)
3137 res
= validate_stmt(CHILD(tree
, j
));
3139 res
= validate_newline(CHILD(tree
, j
));
3141 /* This stays in to prevent any internal failures from getting to the
3142 * user. Hopefully, this won't be needed. If a user reports getting
3143 * this, we have some debugging to do.
3145 if (!res
&& !PyErr_Occurred())
3146 err_string("VALIDATION FAILURE: report this to the maintainer!");
3152 validate_encoding_decl(node
*tree
)
3154 int nch
= NCH(tree
);
3155 int res
= ((nch
== 1)
3156 && validate_file_input(CHILD(tree
, 0)));
3158 if (!res
&& !PyErr_Occurred())
3159 err_string("Error Parsing encoding_decl");
3165 pickle_constructor
= NULL
;
3169 parser__pickler(PyObject
*self
, PyObject
*args
)
3171 NOTE(ARGUNUSED(self
))
3172 PyObject
*result
= NULL
;
3173 PyObject
*st
= NULL
;
3174 PyObject
*empty_dict
= NULL
;
3176 if (PyArg_ParseTuple(args
, "O!:_pickler", &PyST_Type
, &st
)) {
3180 if ((empty_dict
= PyDict_New()) == NULL
)
3182 if ((newargs
= Py_BuildValue("Oi", st
, 1)) == NULL
)
3184 tuple
= parser_st2tuple((PyST_Object
*)NULL
, newargs
, empty_dict
);
3185 if (tuple
!= NULL
) {
3186 result
= Py_BuildValue("O(O)", pickle_constructor
, tuple
);
3189 Py_DECREF(empty_dict
);
3193 Py_XDECREF(empty_dict
);
3199 /* Functions exported by this module. Most of this should probably
3200 * be converted into an ST object with methods, but that is better
3201 * done directly in Python, allowing subclasses to be created directly.
3202 * We'd really have to write a wrapper around it all anyway to allow
3205 static PyMethodDef parser_functions
[] = {
3206 {"ast2tuple", (PyCFunction
)parser_st2tuple
, PUBLIC_METHOD_TYPE
,
3207 PyDoc_STR("Creates a tuple-tree representation of an ST.")},
3208 {"ast2list", (PyCFunction
)parser_st2list
, PUBLIC_METHOD_TYPE
,
3209 PyDoc_STR("Creates a list-tree representation of an ST.")},
3210 {"compileast", (PyCFunction
)parser_compilest
, PUBLIC_METHOD_TYPE
,
3211 PyDoc_STR("Compiles an ST object into a code object.")},
3212 {"compilest", (PyCFunction
)parser_compilest
, PUBLIC_METHOD_TYPE
,
3213 PyDoc_STR("Compiles an ST object into a code object.")},
3214 {"expr", (PyCFunction
)parser_expr
, PUBLIC_METHOD_TYPE
,
3215 PyDoc_STR("Creates an ST object from an expression.")},
3216 {"isexpr", (PyCFunction
)parser_isexpr
, PUBLIC_METHOD_TYPE
,
3217 PyDoc_STR("Determines if an ST object was created from an expression.")},
3218 {"issuite", (PyCFunction
)parser_issuite
, PUBLIC_METHOD_TYPE
,
3219 PyDoc_STR("Determines if an ST object was created from a suite.")},
3220 {"suite", (PyCFunction
)parser_suite
, PUBLIC_METHOD_TYPE
,
3221 PyDoc_STR("Creates an ST object from a suite.")},
3222 {"sequence2ast", (PyCFunction
)parser_tuple2st
, PUBLIC_METHOD_TYPE
,
3223 PyDoc_STR("Creates an ST object from a tree representation.")},
3224 {"sequence2st", (PyCFunction
)parser_tuple2st
, PUBLIC_METHOD_TYPE
,
3225 PyDoc_STR("Creates an ST object from a tree representation.")},
3226 {"st2tuple", (PyCFunction
)parser_st2tuple
, PUBLIC_METHOD_TYPE
,
3227 PyDoc_STR("Creates a tuple-tree representation of an ST.")},
3228 {"st2list", (PyCFunction
)parser_st2list
, PUBLIC_METHOD_TYPE
,
3229 PyDoc_STR("Creates a list-tree representation of an ST.")},
3230 {"tuple2ast", (PyCFunction
)parser_tuple2st
, PUBLIC_METHOD_TYPE
,
3231 PyDoc_STR("Creates an ST object from a tree representation.")},
3232 {"tuple2st", (PyCFunction
)parser_tuple2st
, PUBLIC_METHOD_TYPE
,
3233 PyDoc_STR("Creates an ST object from a tree representation.")},
3235 /* private stuff: support pickle module */
3236 {"_pickler", (PyCFunction
)parser__pickler
, METH_VARARGS
,
3237 PyDoc_STR("Returns the pickle magic to allow ST objects to be pickled.")},
3239 {NULL
, NULL
, 0, NULL
}
3243 PyMODINIT_FUNC
initparser(void); /* supply a prototype */
3248 PyObject
*module
, *copyreg
;
3250 Py_TYPE(&PyST_Type
) = &PyType_Type
;
3251 module
= Py_InitModule("parser", parser_functions
);
3255 if (parser_error
== 0)
3256 parser_error
= PyErr_NewException("parser.ParserError", NULL
, NULL
);
3258 if (parser_error
== 0)
3259 /* caller will check PyErr_Occurred() */
3261 /* CAUTION: The code next used to skip bumping the refcount on
3262 * parser_error. That's a disaster if initparser() gets called more
3263 * than once. By incref'ing, we ensure that each module dict that
3264 * gets created owns its reference to the shared parser_error object,
3265 * and the file static parser_error vrbl owns a reference too.
3267 Py_INCREF(parser_error
);
3268 if (PyModule_AddObject(module
, "ParserError", parser_error
) != 0)
3271 Py_INCREF(&PyST_Type
);
3272 PyModule_AddObject(module
, "ASTType", (PyObject
*)&PyST_Type
);
3273 Py_INCREF(&PyST_Type
);
3274 PyModule_AddObject(module
, "STType", (PyObject
*)&PyST_Type
);
3276 PyModule_AddStringConstant(module
, "__copyright__",
3277 parser_copyright_string
);
3278 PyModule_AddStringConstant(module
, "__doc__",
3280 PyModule_AddStringConstant(module
, "__version__",
3281 parser_version_string
);
3283 /* Register to support pickling.
3284 * If this fails, the import of this module will fail because an
3285 * exception will be raised here; should we clear the exception?
3287 copyreg
= PyImport_ImportModuleNoBlock("copy_reg");
3288 if (copyreg
!= NULL
) {
3289 PyObject
*func
, *pickler
;
3291 func
= PyObject_GetAttrString(copyreg
, "pickle");
3292 pickle_constructor
= PyObject_GetAttrString(module
, "sequence2st");
3293 pickler
= PyObject_GetAttrString(module
, "_pickler");
3294 Py_XINCREF(pickle_constructor
);
3295 if ((func
!= NULL
) && (pickle_constructor
!= NULL
)
3296 && (pickler
!= NULL
)) {
3299 res
= PyObject_CallFunctionObjArgs(func
, &PyST_Type
, pickler
,
3300 pickle_constructor
, NULL
);
3304 Py_XDECREF(pickle_constructor
);
3305 Py_XDECREF(pickler
);