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
) (int 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? */
83 if (ISNONTERMINAL(TYPE(n
))) {
88 v
= mkseq(1 + NCH(n
) + (TYPE(n
) == encoding_decl
));
91 w
= PyInt_FromLong(TYPE(n
));
94 return ((PyObject
*) NULL
);
96 (void) addelem(v
, 0, w
);
97 for (i
= 0; i
< NCH(n
); i
++) {
98 w
= node2tuple(CHILD(n
, i
), mkseq
, addelem
, lineno
);
101 return ((PyObject
*) NULL
);
103 (void) addelem(v
, i
+1, w
);
106 if (TYPE(n
) == encoding_decl
)
107 (void) addelem(v
, i
+1, PyString_FromString(STR(n
)));
110 else if (ISTERMINAL(TYPE(n
))) {
111 PyObject
*result
= mkseq(2 + lineno
);
112 if (result
!= NULL
) {
113 (void) addelem(result
, 0, PyInt_FromLong(TYPE(n
)));
114 (void) addelem(result
, 1, PyString_FromString(STR(n
)));
116 (void) addelem(result
, 2, PyInt_FromLong(n
->n_lineno
));
121 PyErr_SetString(PyExc_SystemError
,
122 "unrecognized parse tree node type");
123 return ((PyObject
*) NULL
);
127 * End of material copyrighted by Stichting Mathematisch Centrum.
132 /* There are two types of intermediate objects we're interested in:
133 * 'eval' and 'exec' types. These constants can be used in the st_type
134 * field of the object type to identify which any given object represents.
135 * These should probably go in an external header to allow other extensions
136 * to use them, but then, we really should be using C++ too. ;-)
143 /* These are the internal objects and definitions required to implement the
144 * ST type. Most of the internal names are more reminiscent of the 'old'
145 * naming style, but the code uses the new naming convention.
153 PyObject_HEAD
/* standard object header */
154 node
* st_node
; /* the node* returned by the parser */
155 int st_type
; /* EXPR or SUITE ? */
159 static void parser_free(PyST_Object
*st
);
160 static int parser_compare(PyST_Object
*left
, PyST_Object
*right
);
161 static PyObject
*parser_getattr(PyObject
*self
, const char *name
);
165 PyTypeObject PyST_Type
= {
166 PyObject_HEAD_INIT(NULL
)
168 "parser.st", /* tp_name */
169 (int) sizeof(PyST_Object
), /* tp_basicsize */
171 (destructor
)parser_free
, /* tp_dealloc */
173 parser_getattr
, /* tp_getattr */
175 (cmpfunc
)parser_compare
, /* tp_compare */
177 0, /* tp_as_number */
178 0, /* tp_as_sequence */
179 0, /* tp_as_mapping */
186 /* Functions to access object as input/output buffer */
187 0, /* tp_as_buffer */
189 Py_TPFLAGS_DEFAULT
, /* tp_flags */
192 "Intermediate representation of a Python parse tree."
197 parser_compare_nodes(node
*left
, node
*right
)
201 if (TYPE(left
) < TYPE(right
))
204 if (TYPE(right
) < TYPE(left
))
207 if (ISTERMINAL(TYPE(left
)))
208 return (strcmp(STR(left
), STR(right
)));
210 if (NCH(left
) < NCH(right
))
213 if (NCH(right
) < NCH(left
))
216 for (j
= 0; j
< NCH(left
); ++j
) {
217 int v
= parser_compare_nodes(CHILD(left
, j
), CHILD(right
, j
));
226 /* int parser_compare(PyST_Object* left, PyST_Object* right)
228 * Comparison function used by the Python operators ==, !=, <, >, <=, >=
229 * This really just wraps a call to parser_compare_nodes() with some easy
230 * checks and protection code.
234 parser_compare(PyST_Object
*left
, PyST_Object
*right
)
239 if ((left
== 0) || (right
== 0))
242 return (parser_compare_nodes(left
->st_node
, right
->st_node
));
246 /* parser_newstobject(node* st)
248 * Allocates a new Python object representing an ST. This is simply the
249 * 'wrapper' object that holds a node* and allows it to be passed around in
254 parser_newstobject(node
*st
, int type
)
256 PyST_Object
* o
= PyObject_New(PyST_Object
, &PyST_Type
);
265 return ((PyObject
*)o
);
269 /* void parser_free(PyST_Object* st)
271 * This is called by a del statement that reduces the reference count to 0.
275 parser_free(PyST_Object
*st
)
277 PyNode_Free(st
->st_node
);
282 /* parser_st2tuple(PyObject* self, PyObject* args, PyObject* kw)
284 * This provides conversion from a node* to a tuple object that can be
285 * returned to the Python-level caller. The ST object is not modified.
289 parser_st2tuple(PyST_Object
*self
, PyObject
*args
, PyObject
*kw
)
291 PyObject
*line_option
= 0;
295 static const char *keywords
[] = {"ast", "line_info", NULL
};
298 ok
= PyArg_ParseTupleAndKeywords(args
, kw
, "O!|O:st2tuple", keywords
,
299 &PyST_Type
, &self
, &line_option
);
302 ok
= PyArg_ParseTupleAndKeywords(args
, kw
, "|O:totuple", &keywords
[1],
306 if (line_option
!= NULL
) {
307 lineno
= (PyObject_IsTrue(line_option
) != 0) ? 1 : 0;
310 * Convert ST into a tuple representation. Use Guido's function,
311 * since it's known to work already.
313 res
= node2tuple(((PyST_Object
*)self
)->st_node
,
314 PyTuple_New
, PyTuple_SetItem
, lineno
);
320 /* parser_st2list(PyObject* self, PyObject* args, PyObject* kw)
322 * This provides conversion from a node* to a list object that can be
323 * returned to the Python-level caller. The ST object is not modified.
327 parser_st2list(PyST_Object
*self
, PyObject
*args
, PyObject
*kw
)
329 PyObject
*line_option
= 0;
333 static const char *keywords
[] = {"ast", "line_info", NULL
};
336 ok
= PyArg_ParseTupleAndKeywords(args
, kw
, "O!|O:st2list", keywords
,
337 &PyST_Type
, &self
, &line_option
);
339 ok
= PyArg_ParseTupleAndKeywords(args
, kw
, "|O:tolist", &keywords
[1],
343 if (line_option
!= 0) {
344 lineno
= PyObject_IsTrue(line_option
) ? 1 : 0;
347 * Convert ST into a tuple representation. Use Guido's function,
348 * since it's known to work already.
350 res
= node2tuple(self
->st_node
,
351 PyList_New
, PyList_SetItem
, lineno
);
357 /* parser_compilest(PyObject* self, PyObject* args)
359 * This function creates code objects from the parse tree represented by
360 * the passed-in data object. An optional file name is passed in as well.
364 parser_compilest(PyST_Object
*self
, PyObject
*args
, PyObject
*kw
)
367 char* str
= "<syntax-tree>";
370 static const char *keywords
[] = {"ast", "filename", NULL
};
373 ok
= PyArg_ParseTupleAndKeywords(args
, kw
, "O!|s:compilest", keywords
,
374 &PyST_Type
, &self
, &str
);
376 ok
= PyArg_ParseTupleAndKeywords(args
, kw
, "|s:compile", &keywords
[1],
380 res
= (PyObject
*)PyNode_Compile(self
->st_node
, str
);
386 /* PyObject* parser_isexpr(PyObject* self, PyObject* args)
387 * PyObject* parser_issuite(PyObject* self, PyObject* args)
389 * Checks the passed-in ST object to determine if it is an expression or
390 * a statement suite, respectively. The return is a Python truth value.
394 parser_isexpr(PyST_Object
*self
, PyObject
*args
, PyObject
*kw
)
399 static const char *keywords
[] = {"ast", NULL
};
402 ok
= PyArg_ParseTupleAndKeywords(args
, kw
, "O!:isexpr", keywords
,
405 ok
= PyArg_ParseTupleAndKeywords(args
, kw
, ":isexpr", &keywords
[1]);
408 /* Check to see if the ST represents an expression or not. */
409 res
= (self
->st_type
== PyST_EXPR
) ? Py_True
: Py_False
;
417 parser_issuite(PyST_Object
*self
, PyObject
*args
, PyObject
*kw
)
422 static const char *keywords
[] = {"ast", NULL
};
425 ok
= PyArg_ParseTupleAndKeywords(args
, kw
, "O!:issuite", keywords
,
428 ok
= PyArg_ParseTupleAndKeywords(args
, kw
, ":issuite", &keywords
[1]);
431 /* Check to see if the ST represents an expression or not. */
432 res
= (self
->st_type
== PyST_EXPR
) ? Py_False
: Py_True
;
439 #define PUBLIC_METHOD_TYPE (METH_VARARGS|METH_KEYWORDS)
443 {"compile", (PyCFunction
)parser_compilest
, PUBLIC_METHOD_TYPE
,
444 PyDoc_STR("Compile this ST object into a code object.")},
445 {"isexpr", (PyCFunction
)parser_isexpr
, PUBLIC_METHOD_TYPE
,
446 PyDoc_STR("Determines if this ST object was created from an expression.")},
447 {"issuite", (PyCFunction
)parser_issuite
, PUBLIC_METHOD_TYPE
,
448 PyDoc_STR("Determines if this ST object was created from a suite.")},
449 {"tolist", (PyCFunction
)parser_st2list
, PUBLIC_METHOD_TYPE
,
450 PyDoc_STR("Creates a list-tree representation of this ST.")},
451 {"totuple", (PyCFunction
)parser_st2tuple
, PUBLIC_METHOD_TYPE
,
452 PyDoc_STR("Creates a tuple-tree representation of this ST.")},
454 {NULL
, NULL
, 0, NULL
}
459 parser_getattr(PyObject
*self
, const char *name
)
461 return (Py_FindMethod(parser_methods
, self
, name
));
465 /* err_string(char* message)
467 * Sets the error string for an exception of type ParserError.
471 err_string(char *message
)
473 PyErr_SetString(parser_error
, message
);
477 /* PyObject* parser_do_parse(PyObject* args, int type)
479 * Internal function to actually execute the parse and return the result if
480 * successful or set an exception if not.
484 parser_do_parse(PyObject
*args
, PyObject
*kw
, char *argspec
, int type
)
489 static const char *keywords
[] = {"source", NULL
};
491 if (PyArg_ParseTupleAndKeywords(args
, kw
, argspec
, keywords
, &string
)) {
492 node
* n
= PyParser_SimpleParseString(string
,
494 ? eval_input
: file_input
);
497 res
= parser_newstobject(n
, type
);
503 /* PyObject* parser_expr(PyObject* self, PyObject* args)
504 * PyObject* parser_suite(PyObject* self, PyObject* args)
506 * External interfaces to the parser itself. Which is called determines if
507 * the parser attempts to recognize an expression ('eval' form) or statement
508 * suite ('exec' form). The real work is done by parser_do_parse() above.
512 parser_expr(PyST_Object
*self
, PyObject
*args
, PyObject
*kw
)
514 NOTE(ARGUNUSED(self
))
515 return (parser_do_parse(args
, kw
, "s:expr", PyST_EXPR
));
520 parser_suite(PyST_Object
*self
, PyObject
*args
, PyObject
*kw
)
522 NOTE(ARGUNUSED(self
))
523 return (parser_do_parse(args
, kw
, "s:suite", PyST_SUITE
));
528 /* This is the messy part of the code. Conversion from a tuple to an ST
529 * object requires that the input tuple be valid without having to rely on
530 * catching an exception from the compiler. This is done to allow the
531 * compiler itself to remain fast, since most of its input will come from
532 * the parser directly, and therefore be known to be syntactically correct.
533 * This validation is done to ensure that we don't core dump the compile
534 * phase, returning an exception instead.
536 * Two aspects can be broken out in this code: creating a node tree from
537 * the tuple passed in, and verifying that it is indeed valid. It may be
538 * advantageous to expand the number of ST types to include funcdefs and
539 * lambdadefs to take advantage of the optimizer, recognizing those STs
540 * here. They are not necessary, and not quite as useful in a raw form.
541 * For now, let's get expressions and suites working reliably.
545 static node
* build_node_tree(PyObject
*tuple
);
546 static int validate_expr_tree(node
*tree
);
547 static int validate_file_input(node
*tree
);
548 static int validate_encoding_decl(node
*tree
);
550 /* PyObject* parser_tuple2st(PyObject* self, PyObject* args)
552 * This is the public function, called from the Python code. It receives a
553 * single tuple object from the caller, and creates an ST object if the
554 * tuple can be validated. It does this by checking the first code of the
555 * tuple, and, if acceptable, builds the internal representation. If this
556 * step succeeds, the internal representation is validated as fully as
557 * possible with the various validate_*() routines defined below.
559 * This function must be changed if support is to be added for PyST_FRAGMENT
564 parser_tuple2st(PyST_Object
*self
, PyObject
*args
, PyObject
*kw
)
566 NOTE(ARGUNUSED(self
))
571 static const char *keywords
[] = {"sequence", NULL
};
573 if (!PyArg_ParseTupleAndKeywords(args
, kw
, "O:sequence2st", keywords
,
576 if (!PySequence_Check(tuple
)) {
577 PyErr_SetString(PyExc_ValueError
,
578 "sequence2st() requires a single sequence argument");
582 * Convert the tree to the internal form before checking it.
584 tree
= build_node_tree(tuple
);
586 int start_sym
= TYPE(tree
);
587 if (start_sym
== eval_input
) {
588 /* Might be an eval form. */
589 if (validate_expr_tree(tree
))
590 st
= parser_newstobject(tree
, PyST_EXPR
);
594 else if (start_sym
== file_input
) {
595 /* This looks like an exec form so far. */
596 if (validate_file_input(tree
))
597 st
= parser_newstobject(tree
, PyST_SUITE
);
601 else if (start_sym
== encoding_decl
) {
602 /* This looks like an encoding_decl so far. */
603 if (validate_encoding_decl(tree
))
604 st
= parser_newstobject(tree
, PyST_SUITE
);
609 /* This is a fragment, at best. */
611 err_string("parse tree does not use a valid start symbol");
614 /* Make sure we throw an exception on all errors. We should never
615 * get this, but we'd do well to be sure something is done.
617 if (st
== NULL
&& !PyErr_Occurred())
618 err_string("unspecified ST error occurred");
624 /* node* build_node_children()
626 * Iterate across the children of the current non-terminal node and build
627 * their structures. If successful, return the root of this portion of
628 * the tree, otherwise, 0. Any required exception will be specified already,
629 * and no memory will have been deallocated.
633 build_node_children(PyObject
*tuple
, node
*root
, int *line_num
)
635 int len
= PyObject_Size(tuple
);
638 for (i
= 1; i
< len
; ++i
) {
639 /* elem must always be a sequence, however simple */
640 PyObject
* elem
= PySequence_GetItem(tuple
, i
);
641 int ok
= elem
!= NULL
;
646 ok
= PySequence_Check(elem
);
648 PyObject
*temp
= PySequence_GetItem(elem
, 0);
652 ok
= PyInt_Check(temp
);
654 type
= PyInt_AS_LONG(temp
);
659 PyErr_SetObject(parser_error
,
660 Py_BuildValue("os", elem
,
661 "Illegal node construct."));
665 if (ISTERMINAL(type
)) {
666 int len
= PyObject_Size(elem
);
669 if ((len
!= 2) && (len
!= 3)) {
670 err_string("terminal nodes must have 2 or 3 entries");
673 temp
= PySequence_GetItem(elem
, 1);
676 if (!PyString_Check(temp
)) {
677 PyErr_Format(parser_error
,
678 "second item in terminal node must be a string,"
680 temp
->ob_type
->tp_name
);
685 PyObject
*o
= PySequence_GetItem(elem
, 2);
688 *line_num
= PyInt_AS_LONG(o
);
690 PyErr_Format(parser_error
,
691 "third item in terminal node must be an"
692 " integer, found %s",
693 temp
->ob_type
->tp_name
);
701 len
= PyString_GET_SIZE(temp
) + 1;
702 strn
= (char *)PyMem_MALLOC(len
);
704 (void) memcpy(strn
, PyString_AS_STRING(temp
), len
);
707 else if (!ISNONTERMINAL(type
)) {
709 * It has to be one or the other; this is an error.
710 * Throw an exception.
712 PyErr_SetObject(parser_error
,
713 Py_BuildValue("os", elem
, "unknown node type."));
717 err
= PyNode_AddChild(root
, type
, strn
, *line_num
);
718 if (err
== E_NOMEM
) {
720 return (node
*) PyErr_NoMemory();
722 if (err
== E_OVERFLOW
) {
724 PyErr_SetString(PyExc_ValueError
,
725 "unsupported number of child nodes");
729 if (ISNONTERMINAL(type
)) {
730 node
* new_child
= CHILD(root
, i
- 1);
732 if (new_child
!= build_node_children(elem
, new_child
, line_num
)) {
737 else if (type
== NEWLINE
) { /* It's true: we increment the */
738 ++(*line_num
); /* line number *after* the newline! */
747 build_node_tree(PyObject
*tuple
)
750 PyObject
*temp
= PySequence_GetItem(tuple
, 0);
754 num
= PyInt_AsLong(temp
);
756 if (ISTERMINAL(num
)) {
758 * The tuple is simple, but it doesn't start with a start symbol.
759 * Throw an exception now and be done with it.
761 tuple
= Py_BuildValue("os", tuple
,
762 "Illegal syntax-tree; cannot start with terminal symbol.");
763 PyErr_SetObject(parser_error
, tuple
);
765 else if (ISNONTERMINAL(num
)) {
767 * Not efficient, but that can be handled later.
770 PyObject
*encoding
= NULL
;
772 if (num
== encoding_decl
) {
773 encoding
= PySequence_GetItem(tuple
, 2);
774 /* tuple isn't borrowed anymore here, need to DECREF */
775 tuple
= PySequence_GetSlice(tuple
, 0, 2);
777 res
= PyNode_New(num
);
779 if (res
!= build_node_children(tuple
, res
, &line_num
)) {
783 if (res
&& encoding
) {
785 len
= PyString_GET_SIZE(encoding
) + 1;
786 res
->n_str
= (char *)PyMem_MALLOC(len
);
787 if (res
->n_str
!= NULL
)
788 (void) memcpy(res
->n_str
, PyString_AS_STRING(encoding
), len
);
795 /* The tuple is illegal -- if the number is neither TERMINAL nor
796 * NONTERMINAL, we can't use it. Not sure the implementation
797 * allows this condition, but the API doesn't preclude it.
799 PyErr_SetObject(parser_error
,
800 Py_BuildValue("os", tuple
,
801 "Illegal component tuple."));
808 * Validation routines used within the validation section:
810 static int validate_terminal(node
*terminal
, int type
, char *string
);
812 #define validate_ampersand(ch) validate_terminal(ch, AMPER, "&")
813 #define validate_circumflex(ch) validate_terminal(ch, CIRCUMFLEX, "^")
814 #define validate_colon(ch) validate_terminal(ch, COLON, ":")
815 #define validate_comma(ch) validate_terminal(ch, COMMA, ",")
816 #define validate_dedent(ch) validate_terminal(ch, DEDENT, "")
817 #define validate_equal(ch) validate_terminal(ch, EQUAL, "=")
818 #define validate_indent(ch) validate_terminal(ch, INDENT, (char*)NULL)
819 #define validate_lparen(ch) validate_terminal(ch, LPAR, "(")
820 #define validate_newline(ch) validate_terminal(ch, NEWLINE, (char*)NULL)
821 #define validate_rparen(ch) validate_terminal(ch, RPAR, ")")
822 #define validate_semi(ch) validate_terminal(ch, SEMI, ";")
823 #define validate_star(ch) validate_terminal(ch, STAR, "*")
824 #define validate_vbar(ch) validate_terminal(ch, VBAR, "|")
825 #define validate_doublestar(ch) validate_terminal(ch, DOUBLESTAR, "**")
826 #define validate_dot(ch) validate_terminal(ch, DOT, ".")
827 #define validate_at(ch) validate_terminal(ch, AT, "@")
828 #define validate_name(ch, str) validate_terminal(ch, NAME, str)
830 #define VALIDATER(n) static int validate_##n(node *tree)
832 VALIDATER(node
); VALIDATER(small_stmt
);
833 VALIDATER(class); VALIDATER(node
);
834 VALIDATER(parameters
); VALIDATER(suite
);
835 VALIDATER(testlist
); VALIDATER(varargslist
);
836 VALIDATER(fpdef
); VALIDATER(fplist
);
837 VALIDATER(stmt
); VALIDATER(simple_stmt
);
838 VALIDATER(expr_stmt
); VALIDATER(power
);
839 VALIDATER(print_stmt
); VALIDATER(del_stmt
);
840 VALIDATER(return_stmt
); VALIDATER(list_iter
);
841 VALIDATER(raise_stmt
); VALIDATER(import_stmt
);
842 VALIDATER(import_name
); VALIDATER(import_from
);
843 VALIDATER(global_stmt
); VALIDATER(list_if
);
844 VALIDATER(assert_stmt
); VALIDATER(list_for
);
845 VALIDATER(exec_stmt
); VALIDATER(compound_stmt
);
846 VALIDATER(while); VALIDATER(for);
847 VALIDATER(try); VALIDATER(except_clause
);
848 VALIDATER(test
); VALIDATER(and_test
);
849 VALIDATER(not_test
); VALIDATER(comparison
);
850 VALIDATER(comp_op
); VALIDATER(expr
);
851 VALIDATER(xor_expr
); VALIDATER(and_expr
);
852 VALIDATER(shift_expr
); VALIDATER(arith_expr
);
853 VALIDATER(term
); VALIDATER(factor
);
854 VALIDATER(atom
); VALIDATER(lambdef
);
855 VALIDATER(trailer
); VALIDATER(subscript
);
856 VALIDATER(subscriptlist
); VALIDATER(sliceop
);
857 VALIDATER(exprlist
); VALIDATER(dictmaker
);
858 VALIDATER(arglist
); VALIDATER(argument
);
859 VALIDATER(listmaker
); VALIDATER(yield_stmt
);
860 VALIDATER(testlist1
); VALIDATER(gen_for
);
861 VALIDATER(gen_iter
); VALIDATER(gen_if
);
862 VALIDATER(testlist_gexp
); VALIDATER(yield_expr
);
863 VALIDATER(yield_or_testlist
);
867 #define is_even(n) (((n) & 1) == 0)
868 #define is_odd(n) (((n) & 1) == 1)
872 validate_ntype(node
*n
, int t
)
875 PyErr_Format(parser_error
, "Expected node type %d, got %d.",
883 /* Verifies that the number of child nodes is exactly 'num', raising
884 * an exception if it isn't. The exception message does not indicate
885 * the exact number of nodes, allowing this to be used to raise the
886 * "right" exception when the wrong number of nodes is present in a
887 * specific variant of a statement's syntax. This is commonly used
891 validate_numnodes(node
*n
, int num
, const char *const name
)
894 PyErr_Format(parser_error
,
895 "Illegal number of children for %s node.", name
);
903 validate_terminal(node
*terminal
, int type
, char *string
)
905 int res
= (validate_ntype(terminal
, type
)
906 && ((string
== 0) || (strcmp(string
, STR(terminal
)) == 0)));
908 if (!res
&& !PyErr_Occurred()) {
909 PyErr_Format(parser_error
,
910 "Illegal terminal: expected \"%s\"", string
);
919 validate_repeating_list(node
*tree
, int ntype
, int (*vfunc
)(node
*),
920 const char *const name
)
923 int res
= (nch
&& validate_ntype(tree
, ntype
)
924 && vfunc(CHILD(tree
, 0)));
926 if (!res
&& !PyErr_Occurred())
927 (void) validate_numnodes(tree
, 1, name
);
930 res
= validate_comma(CHILD(tree
, --nch
));
931 if (res
&& nch
> 1) {
933 for ( ; res
&& pos
< nch
; pos
+= 2)
934 res
= (validate_comma(CHILD(tree
, pos
))
935 && vfunc(CHILD(tree
, pos
+ 1)));
945 * 'class' NAME ['(' testlist ')'] ':' suite
948 validate_class(node
*tree
)
951 int res
= (validate_ntype(tree
, classdef
) &&
952 ((nch
== 4) || (nch
== 6) || (nch
== 7)));
955 res
= (validate_name(CHILD(tree
, 0), "class")
956 && validate_ntype(CHILD(tree
, 1), NAME
)
957 && validate_colon(CHILD(tree
, nch
- 2))
958 && validate_suite(CHILD(tree
, nch
- 1)));
961 (void) validate_numnodes(tree
, 4, "class");
966 res
= ((validate_lparen(CHILD(tree
, 2)) &&
967 validate_testlist(CHILD(tree
, 3)) &&
968 validate_rparen(CHILD(tree
, 4))));
971 res
= (validate_lparen(CHILD(tree
,2)) &&
972 validate_rparen(CHILD(tree
,3)));
980 * 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
983 validate_if(node
*tree
)
986 int res
= (validate_ntype(tree
, if_stmt
)
988 && validate_name(CHILD(tree
, 0), "if")
989 && validate_test(CHILD(tree
, 1))
990 && validate_colon(CHILD(tree
, 2))
991 && validate_suite(CHILD(tree
, 3)));
993 if (res
&& ((nch
% 4) == 3)) {
994 /* ... 'else' ':' suite */
995 res
= (validate_name(CHILD(tree
, nch
- 3), "else")
996 && validate_colon(CHILD(tree
, nch
- 2))
997 && validate_suite(CHILD(tree
, nch
- 1)));
1000 else if (!res
&& !PyErr_Occurred())
1001 (void) validate_numnodes(tree
, 4, "if");
1003 /* Will catch the case for nch < 4 */
1004 res
= validate_numnodes(tree
, 0, "if");
1005 else if (res
&& (nch
> 4)) {
1006 /* ... ('elif' test ':' suite)+ ... */
1008 while ((j
< nch
) && res
) {
1009 res
= (validate_name(CHILD(tree
, j
), "elif")
1010 && validate_colon(CHILD(tree
, j
+ 2))
1011 && validate_test(CHILD(tree
, j
+ 1))
1012 && validate_suite(CHILD(tree
, j
+ 3)));
1021 * '(' [varargslist] ')'
1025 validate_parameters(node
*tree
)
1027 int nch
= NCH(tree
);
1028 int res
= validate_ntype(tree
, parameters
) && ((nch
== 2) || (nch
== 3));
1031 res
= (validate_lparen(CHILD(tree
, 0))
1032 && validate_rparen(CHILD(tree
, nch
- 1)));
1033 if (res
&& (nch
== 3))
1034 res
= validate_varargslist(CHILD(tree
, 1));
1037 (void) validate_numnodes(tree
, 2, "parameters");
1047 * | NEWLINE INDENT stmt+ DEDENT
1050 validate_suite(node
*tree
)
1052 int nch
= NCH(tree
);
1053 int res
= (validate_ntype(tree
, suite
) && ((nch
== 1) || (nch
>= 4)));
1055 if (res
&& (nch
== 1))
1056 res
= validate_simple_stmt(CHILD(tree
, 0));
1058 /* NEWLINE INDENT stmt+ DEDENT */
1059 res
= (validate_newline(CHILD(tree
, 0))
1060 && validate_indent(CHILD(tree
, 1))
1061 && validate_stmt(CHILD(tree
, 2))
1062 && validate_dedent(CHILD(tree
, nch
- 1)));
1064 if (res
&& (nch
> 4)) {
1066 --nch
; /* forget the DEDENT */
1067 for ( ; res
&& (i
< nch
); ++i
)
1068 res
= validate_stmt(CHILD(tree
, i
));
1071 res
= validate_numnodes(tree
, 4, "suite");
1078 validate_testlist(node
*tree
)
1080 return (validate_repeating_list(tree
, testlist
,
1081 validate_test
, "testlist"));
1086 validate_testlist1(node
*tree
)
1088 return (validate_repeating_list(tree
, testlist1
,
1089 validate_test
, "testlist1"));
1094 validate_testlist_safe(node
*tree
)
1096 return (validate_repeating_list(tree
, testlist_safe
,
1097 validate_test
, "testlist_safe"));
1101 /* '*' NAME [',' '**' NAME] | '**' NAME
1104 validate_varargslist_trailer(node
*tree
, int start
)
1106 int nch
= NCH(tree
);
1111 err_string("expected variable argument trailer for varargslist");
1114 sym
= TYPE(CHILD(tree
, start
));
1117 * ('*' NAME [',' '**' NAME]
1120 res
= validate_name(CHILD(tree
, start
+1), NULL
);
1121 else if (nch
-start
== 5)
1122 res
= (validate_name(CHILD(tree
, start
+1), NULL
)
1123 && validate_comma(CHILD(tree
, start
+2))
1124 && validate_doublestar(CHILD(tree
, start
+3))
1125 && validate_name(CHILD(tree
, start
+4), NULL
));
1127 else if (sym
== DOUBLESTAR
) {
1132 res
= validate_name(CHILD(tree
, start
+1), NULL
);
1135 err_string("illegal variable argument trailer for varargslist");
1140 /* validate_varargslist()
1143 * (fpdef ['=' test] ',')*
1144 * ('*' NAME [',' '**' NAME]
1146 * | fpdef ['=' test] (',' fpdef ['=' test])* [',']
1150 validate_varargslist(node
*tree
)
1152 int nch
= NCH(tree
);
1153 int res
= validate_ntype(tree
, varargslist
) && (nch
!= 0);
1159 err_string("varargslist missing child nodes");
1162 sym
= TYPE(CHILD(tree
, 0));
1163 if (sym
== STAR
|| sym
== DOUBLESTAR
)
1164 /* whole thing matches:
1165 * '*' NAME [',' '**' NAME] | '**' NAME
1167 res
= validate_varargslist_trailer(tree
, 0);
1168 else if (sym
== fpdef
) {
1171 sym
= TYPE(CHILD(tree
, nch
-1));
1174 * (fpdef ['=' test] ',')+
1175 * ('*' NAME [',' '**' NAME]
1178 /* skip over (fpdef ['=' test] ',')+ */
1179 while (res
&& (i
+2 <= nch
)) {
1180 res
= validate_fpdef(CHILD(tree
, i
));
1182 if (res
&& TYPE(CHILD(tree
, i
)) == EQUAL
&& (i
+2 <= nch
)) {
1183 res
= (validate_equal(CHILD(tree
, i
))
1184 && validate_test(CHILD(tree
, i
+1)));
1188 if (res
&& i
< nch
) {
1189 res
= validate_comma(CHILD(tree
, i
));
1192 && (TYPE(CHILD(tree
, i
)) == DOUBLESTAR
1193 || TYPE(CHILD(tree
, i
)) == STAR
))
1197 /* ... '*' NAME [',' '**' NAME] | '**' NAME
1201 res
= validate_varargslist_trailer(tree
, i
);
1205 * fpdef ['=' test] (',' fpdef ['=' test])* [',']
1207 /* strip trailing comma node */
1209 res
= validate_comma(CHILD(tree
, nch
-1));
1215 * fpdef ['=' test] (',' fpdef ['=' test])*
1217 res
= validate_fpdef(CHILD(tree
, 0));
1219 if (res
&& (i
+2 <= nch
) && TYPE(CHILD(tree
, i
)) == EQUAL
) {
1220 res
= (validate_equal(CHILD(tree
, i
))
1221 && validate_test(CHILD(tree
, i
+1)));
1225 * ... (',' fpdef ['=' test])*
1228 while (res
&& (nch
- i
) >= 2) {
1229 res
= (validate_comma(CHILD(tree
, i
))
1230 && validate_fpdef(CHILD(tree
, i
+1)));
1232 if (res
&& (nch
- i
) >= 2 && TYPE(CHILD(tree
, i
)) == EQUAL
) {
1233 res
= (validate_equal(CHILD(tree
, i
))
1234 && validate_test(CHILD(tree
, i
+1)));
1238 if (res
&& nch
- i
!= 0) {
1240 err_string("illegal formation for varargslist");
1248 /* list_iter: list_for | list_if
1251 validate_list_iter(node
*tree
)
1253 int res
= (validate_ntype(tree
, list_iter
)
1254 && validate_numnodes(tree
, 1, "list_iter"));
1255 if (res
&& TYPE(CHILD(tree
, 0)) == list_for
)
1256 res
= validate_list_for(CHILD(tree
, 0));
1258 res
= validate_list_if(CHILD(tree
, 0));
1263 /* gen_iter: gen_for | gen_if
1266 validate_gen_iter(node
*tree
)
1268 int res
= (validate_ntype(tree
, gen_iter
)
1269 && validate_numnodes(tree
, 1, "gen_iter"));
1270 if (res
&& TYPE(CHILD(tree
, 0)) == gen_for
)
1271 res
= validate_gen_for(CHILD(tree
, 0));
1273 res
= validate_gen_if(CHILD(tree
, 0));
1278 /* list_for: 'for' exprlist 'in' testlist [list_iter]
1281 validate_list_for(node
*tree
)
1283 int nch
= NCH(tree
);
1287 res
= validate_list_iter(CHILD(tree
, 4));
1289 res
= validate_numnodes(tree
, 4, "list_for");
1292 res
= (validate_name(CHILD(tree
, 0), "for")
1293 && validate_exprlist(CHILD(tree
, 1))
1294 && validate_name(CHILD(tree
, 2), "in")
1295 && validate_testlist_safe(CHILD(tree
, 3)));
1300 /* gen_for: 'for' exprlist 'in' test [gen_iter]
1303 validate_gen_for(node
*tree
)
1305 int nch
= NCH(tree
);
1309 res
= validate_gen_iter(CHILD(tree
, 4));
1311 res
= validate_numnodes(tree
, 4, "gen_for");
1314 res
= (validate_name(CHILD(tree
, 0), "for")
1315 && validate_exprlist(CHILD(tree
, 1))
1316 && validate_name(CHILD(tree
, 2), "in")
1317 && validate_test(CHILD(tree
, 3)));
1322 /* list_if: 'if' test [list_iter]
1325 validate_list_if(node
*tree
)
1327 int nch
= NCH(tree
);
1331 res
= validate_list_iter(CHILD(tree
, 2));
1333 res
= validate_numnodes(tree
, 2, "list_if");
1336 res
= (validate_name(CHILD(tree
, 0), "if")
1337 && validate_test(CHILD(tree
, 1)));
1342 /* gen_if: 'if' test [gen_iter]
1345 validate_gen_if(node
*tree
)
1347 int nch
= NCH(tree
);
1351 res
= validate_gen_iter(CHILD(tree
, 2));
1353 res
= validate_numnodes(tree
, 2, "gen_if");
1356 res
= (validate_name(CHILD(tree
, 0), "if")
1357 && validate_test(CHILD(tree
, 1)));
1369 validate_fpdef(node
*tree
)
1371 int nch
= NCH(tree
);
1372 int res
= validate_ntype(tree
, fpdef
);
1376 res
= validate_ntype(CHILD(tree
, 0), NAME
);
1378 res
= (validate_lparen(CHILD(tree
, 0))
1379 && validate_fplist(CHILD(tree
, 1))
1380 && validate_rparen(CHILD(tree
, 2)));
1382 res
= validate_numnodes(tree
, 1, "fpdef");
1389 validate_fplist(node
*tree
)
1391 return (validate_repeating_list(tree
, fplist
,
1392 validate_fpdef
, "fplist"));
1396 /* simple_stmt | compound_stmt
1400 validate_stmt(node
*tree
)
1402 int res
= (validate_ntype(tree
, stmt
)
1403 && validate_numnodes(tree
, 1, "stmt"));
1406 tree
= CHILD(tree
, 0);
1408 if (TYPE(tree
) == simple_stmt
)
1409 res
= validate_simple_stmt(tree
);
1411 res
= validate_compound_stmt(tree
);
1417 /* small_stmt (';' small_stmt)* [';'] NEWLINE
1421 validate_simple_stmt(node
*tree
)
1423 int nch
= NCH(tree
);
1424 int res
= (validate_ntype(tree
, simple_stmt
)
1426 && validate_small_stmt(CHILD(tree
, 0))
1427 && validate_newline(CHILD(tree
, nch
- 1)));
1430 res
= validate_numnodes(tree
, 2, "simple_stmt");
1431 --nch
; /* forget the NEWLINE */
1432 if (res
&& is_even(nch
))
1433 res
= validate_semi(CHILD(tree
, --nch
));
1434 if (res
&& (nch
> 2)) {
1437 for (i
= 1; res
&& (i
< nch
); i
+= 2)
1438 res
= (validate_semi(CHILD(tree
, i
))
1439 && validate_small_stmt(CHILD(tree
, i
+ 1)));
1446 validate_small_stmt(node
*tree
)
1448 int nch
= NCH(tree
);
1449 int res
= validate_numnodes(tree
, 1, "small_stmt");
1452 int ntype
= TYPE(CHILD(tree
, 0));
1454 if ( (ntype
== expr_stmt
)
1455 || (ntype
== print_stmt
)
1456 || (ntype
== del_stmt
)
1457 || (ntype
== pass_stmt
)
1458 || (ntype
== flow_stmt
)
1459 || (ntype
== import_stmt
)
1460 || (ntype
== global_stmt
)
1461 || (ntype
== assert_stmt
)
1462 || (ntype
== exec_stmt
))
1463 res
= validate_node(CHILD(tree
, 0));
1466 err_string("illegal small_stmt child type");
1469 else if (nch
== 1) {
1471 PyErr_Format(parser_error
,
1472 "Unrecognized child node of small_stmt: %d.",
1473 TYPE(CHILD(tree
, 0)));
1480 * if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
1483 validate_compound_stmt(node
*tree
)
1485 int res
= (validate_ntype(tree
, compound_stmt
)
1486 && validate_numnodes(tree
, 1, "compound_stmt"));
1492 tree
= CHILD(tree
, 0);
1494 if ( (ntype
== if_stmt
)
1495 || (ntype
== while_stmt
)
1496 || (ntype
== for_stmt
)
1497 || (ntype
== try_stmt
)
1498 || (ntype
== funcdef
)
1499 || (ntype
== classdef
))
1500 res
= validate_node(tree
);
1503 PyErr_Format(parser_error
,
1504 "Illegal compound statement type: %d.", TYPE(tree
));
1511 validate_yield_or_testlist(node
*tree
)
1513 if (TYPE(tree
) == yield_expr
)
1514 return validate_yield_expr(tree
);
1516 return validate_testlist(tree
);
1520 validate_expr_stmt(node
*tree
)
1523 int nch
= NCH(tree
);
1524 int res
= (validate_ntype(tree
, expr_stmt
)
1526 && validate_testlist(CHILD(tree
, 0)));
1529 && TYPE(CHILD(tree
, 1)) == augassign
) {
1530 res
= validate_numnodes(CHILD(tree
, 1), 1, "augassign")
1531 && validate_yield_or_testlist(CHILD(tree
, 2));
1534 char *s
= STR(CHILD(CHILD(tree
, 1), 0));
1536 res
= (strcmp(s
, "+=") == 0
1537 || strcmp(s
, "-=") == 0
1538 || strcmp(s
, "*=") == 0
1539 || strcmp(s
, "/=") == 0
1540 || strcmp(s
, "//=") == 0
1541 || strcmp(s
, "%=") == 0
1542 || strcmp(s
, "&=") == 0
1543 || strcmp(s
, "|=") == 0
1544 || strcmp(s
, "^=") == 0
1545 || strcmp(s
, "<<=") == 0
1546 || strcmp(s
, ">>=") == 0
1547 || strcmp(s
, "**=") == 0);
1549 err_string("illegal augmmented assignment operator");
1553 for (j
= 1; res
&& (j
< nch
); j
+= 2)
1554 res
= validate_equal(CHILD(tree
, j
))
1555 && validate_yield_or_testlist(CHILD(tree
, j
+ 1));
1563 * 'print' ( [ test (',' test)* [','] ]
1564 * | '>>' test [ (',' test)+ [','] ] )
1567 validate_print_stmt(node
*tree
)
1569 int nch
= NCH(tree
);
1570 int res
= (validate_ntype(tree
, print_stmt
)
1572 && validate_name(CHILD(tree
, 0), "print"));
1574 if (res
&& nch
> 1) {
1575 int sym
= TYPE(CHILD(tree
, 1));
1577 int allow_trailing_comma
= 1;
1580 res
= validate_test(CHILD(tree
, i
++));
1583 res
= validate_numnodes(tree
, 3, "print_stmt");
1585 res
= (validate_ntype(CHILD(tree
, i
), RIGHTSHIFT
)
1586 && validate_test(CHILD(tree
, i
+1)));
1588 allow_trailing_comma
= 0;
1592 /* ... (',' test)* [','] */
1593 while (res
&& i
+2 <= nch
) {
1594 res
= (validate_comma(CHILD(tree
, i
))
1595 && validate_test(CHILD(tree
, i
+1)));
1596 allow_trailing_comma
= 1;
1599 if (res
&& !allow_trailing_comma
)
1600 res
= validate_numnodes(tree
, i
, "print_stmt");
1601 else if (res
&& i
< nch
)
1602 res
= validate_comma(CHILD(tree
, i
));
1610 validate_del_stmt(node
*tree
)
1612 return (validate_numnodes(tree
, 2, "del_stmt")
1613 && validate_name(CHILD(tree
, 0), "del")
1614 && validate_exprlist(CHILD(tree
, 1)));
1619 validate_return_stmt(node
*tree
)
1621 int nch
= NCH(tree
);
1622 int res
= (validate_ntype(tree
, return_stmt
)
1623 && ((nch
== 1) || (nch
== 2))
1624 && validate_name(CHILD(tree
, 0), "return"));
1626 if (res
&& (nch
== 2))
1627 res
= validate_testlist(CHILD(tree
, 1));
1634 validate_raise_stmt(node
*tree
)
1636 int nch
= NCH(tree
);
1637 int res
= (validate_ntype(tree
, raise_stmt
)
1638 && ((nch
== 1) || (nch
== 2) || (nch
== 4) || (nch
== 6)));
1641 res
= validate_name(CHILD(tree
, 0), "raise");
1642 if (res
&& (nch
>= 2))
1643 res
= validate_test(CHILD(tree
, 1));
1644 if (res
&& nch
> 2) {
1645 res
= (validate_comma(CHILD(tree
, 2))
1646 && validate_test(CHILD(tree
, 3)));
1647 if (res
&& (nch
> 4))
1648 res
= (validate_comma(CHILD(tree
, 4))
1649 && validate_test(CHILD(tree
, 5)));
1653 (void) validate_numnodes(tree
, 2, "raise");
1654 if (res
&& (nch
== 4))
1655 res
= (validate_comma(CHILD(tree
, 2))
1656 && validate_test(CHILD(tree
, 3)));
1662 /* yield_expr: 'yield' [testlist]
1665 validate_yield_expr(node
*tree
)
1667 int nch
= NCH(tree
);
1668 int res
= (validate_ntype(tree
, yield_expr
)
1669 && ((nch
== 1) || (nch
== 2))
1670 && validate_name(CHILD(tree
, 0), "yield"));
1672 if (res
&& (nch
== 2))
1673 res
= validate_testlist(CHILD(tree
, 1));
1679 /* yield_stmt: yield_expr
1682 validate_yield_stmt(node
*tree
)
1684 return (validate_ntype(tree
, yield_stmt
)
1685 && validate_numnodes(tree
, 1, "yield_stmt")
1686 && validate_yield_expr(CHILD(tree
, 0)));
1691 validate_import_as_name(node
*tree
)
1693 int nch
= NCH(tree
);
1694 int ok
= validate_ntype(tree
, import_as_name
);
1698 ok
= validate_name(CHILD(tree
, 0), NULL
);
1700 ok
= (validate_name(CHILD(tree
, 0), NULL
)
1701 && validate_name(CHILD(tree
, 1), "as")
1702 && validate_name(CHILD(tree
, 2), NULL
));
1704 ok
= validate_numnodes(tree
, 3, "import_as_name");
1710 /* dotted_name: NAME ("." NAME)*
1713 validate_dotted_name(node
*tree
)
1715 int nch
= NCH(tree
);
1716 int res
= (validate_ntype(tree
, dotted_name
)
1718 && validate_name(CHILD(tree
, 0), NULL
));
1721 for (i
= 1; res
&& (i
< nch
); i
+= 2) {
1722 res
= (validate_dot(CHILD(tree
, i
))
1723 && validate_name(CHILD(tree
, i
+1), NULL
));
1729 /* dotted_as_name: dotted_name [NAME NAME]
1732 validate_dotted_as_name(node
*tree
)
1734 int nch
= NCH(tree
);
1735 int res
= validate_ntype(tree
, dotted_as_name
);
1739 res
= validate_dotted_name(CHILD(tree
, 0));
1741 res
= (validate_dotted_name(CHILD(tree
, 0))
1742 && validate_name(CHILD(tree
, 1), "as")
1743 && validate_name(CHILD(tree
, 2), NULL
));
1746 err_string("illegal number of children for dotted_as_name");
1753 /* dotted_as_name (',' dotted_as_name)* */
1755 validate_dotted_as_names(node
*tree
)
1757 int nch
= NCH(tree
);
1758 int res
= is_odd(nch
) && validate_dotted_as_name(CHILD(tree
, 0));
1761 for (i
= 1; res
&& (i
< nch
); i
+= 2)
1762 res
= (validate_comma(CHILD(tree
, i
))
1763 && validate_dotted_as_name(CHILD(tree
, i
+ 1)));
1768 /* import_as_name (',' import_as_name)* [','] */
1770 validate_import_as_names(node
*tree
)
1772 int nch
= NCH(tree
);
1773 int res
= validate_import_as_name(CHILD(tree
, 0));
1776 for (i
= 1; res
&& (i
+ 1 < nch
); i
+= 2)
1777 res
= (validate_comma(CHILD(tree
, i
))
1778 && validate_import_as_name(CHILD(tree
, i
+ 1)));
1783 /* 'import' dotted_as_names */
1785 validate_import_name(node
*tree
)
1787 return (validate_ntype(tree
, import_name
)
1788 && validate_numnodes(tree
, 2, "import_name")
1789 && validate_name(CHILD(tree
, 0), "import")
1790 && validate_dotted_as_names(CHILD(tree
, 1)));
1794 /* 'from' dotted_name 'import' ('*' | '(' import_as_names ')' |
1798 validate_import_from(node
*tree
)
1800 int nch
= NCH(tree
);
1801 int res
= validate_ntype(tree
, import_from
)
1803 && validate_name(CHILD(tree
, 0), "from")
1804 && validate_dotted_name(CHILD(tree
, 1))
1805 && validate_name(CHILD(tree
, 2), "import");
1807 if (res
&& TYPE(CHILD(tree
, 3)) == LPAR
)
1809 && validate_lparen(CHILD(tree
, 3))
1810 && validate_import_as_names(CHILD(tree
, 4))
1811 && validate_rparen(CHILD(tree
, 5)));
1812 else if (res
&& TYPE(CHILD(tree
, 3)) != STAR
)
1813 res
= validate_import_as_names(CHILD(tree
, 3));
1818 /* import_stmt: import_name | import_from */
1820 validate_import_stmt(node
*tree
)
1822 int nch
= NCH(tree
);
1823 int res
= validate_numnodes(tree
, 1, "import_stmt");
1826 int ntype
= TYPE(CHILD(tree
, 0));
1828 if (ntype
== import_name
|| ntype
== import_from
)
1829 res
= validate_node(CHILD(tree
, 0));
1832 err_string("illegal import_stmt child type");
1835 else if (nch
== 1) {
1837 PyErr_Format(parser_error
,
1838 "Unrecognized child node of import_stmt: %d.",
1839 TYPE(CHILD(tree
, 0)));
1848 validate_global_stmt(node
*tree
)
1851 int nch
= NCH(tree
);
1852 int res
= (validate_ntype(tree
, global_stmt
)
1853 && is_even(nch
) && (nch
>= 2));
1855 if (!res
&& !PyErr_Occurred())
1856 err_string("illegal global statement");
1859 res
= (validate_name(CHILD(tree
, 0), "global")
1860 && validate_ntype(CHILD(tree
, 1), NAME
));
1861 for (j
= 2; res
&& (j
< nch
); j
+= 2)
1862 res
= (validate_comma(CHILD(tree
, j
))
1863 && validate_ntype(CHILD(tree
, j
+ 1), NAME
));
1871 * 'exec' expr ['in' test [',' test]]
1874 validate_exec_stmt(node
*tree
)
1876 int nch
= NCH(tree
);
1877 int res
= (validate_ntype(tree
, exec_stmt
)
1878 && ((nch
== 2) || (nch
== 4) || (nch
== 6))
1879 && validate_name(CHILD(tree
, 0), "exec")
1880 && validate_expr(CHILD(tree
, 1)));
1882 if (!res
&& !PyErr_Occurred())
1883 err_string("illegal exec statement");
1884 if (res
&& (nch
> 2))
1885 res
= (validate_name(CHILD(tree
, 2), "in")
1886 && validate_test(CHILD(tree
, 3)));
1887 if (res
&& (nch
== 6))
1888 res
= (validate_comma(CHILD(tree
, 4))
1889 && validate_test(CHILD(tree
, 5)));
1897 * 'assert' test [',' test]
1900 validate_assert_stmt(node
*tree
)
1902 int nch
= NCH(tree
);
1903 int res
= (validate_ntype(tree
, assert_stmt
)
1904 && ((nch
== 2) || (nch
== 4))
1905 && (validate_name(CHILD(tree
, 0), "assert"))
1906 && validate_test(CHILD(tree
, 1)));
1908 if (!res
&& !PyErr_Occurred())
1909 err_string("illegal assert statement");
1910 if (res
&& (nch
> 2))
1911 res
= (validate_comma(CHILD(tree
, 2))
1912 && validate_test(CHILD(tree
, 3)));
1919 validate_while(node
*tree
)
1921 int nch
= NCH(tree
);
1922 int res
= (validate_ntype(tree
, while_stmt
)
1923 && ((nch
== 4) || (nch
== 7))
1924 && validate_name(CHILD(tree
, 0), "while")
1925 && validate_test(CHILD(tree
, 1))
1926 && validate_colon(CHILD(tree
, 2))
1927 && validate_suite(CHILD(tree
, 3)));
1929 if (res
&& (nch
== 7))
1930 res
= (validate_name(CHILD(tree
, 4), "else")
1931 && validate_colon(CHILD(tree
, 5))
1932 && validate_suite(CHILD(tree
, 6)));
1939 validate_for(node
*tree
)
1941 int nch
= NCH(tree
);
1942 int res
= (validate_ntype(tree
, for_stmt
)
1943 && ((nch
== 6) || (nch
== 9))
1944 && validate_name(CHILD(tree
, 0), "for")
1945 && validate_exprlist(CHILD(tree
, 1))
1946 && validate_name(CHILD(tree
, 2), "in")
1947 && validate_testlist(CHILD(tree
, 3))
1948 && validate_colon(CHILD(tree
, 4))
1949 && validate_suite(CHILD(tree
, 5)));
1951 if (res
&& (nch
== 9))
1952 res
= (validate_name(CHILD(tree
, 6), "else")
1953 && validate_colon(CHILD(tree
, 7))
1954 && validate_suite(CHILD(tree
, 8)));
1961 * 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
1962 * | 'try' ':' suite 'finally' ':' suite
1966 validate_try(node
*tree
)
1968 int nch
= NCH(tree
);
1970 int res
= (validate_ntype(tree
, try_stmt
)
1971 && (nch
>= 6) && ((nch
% 3) == 0));
1974 res
= (validate_name(CHILD(tree
, 0), "try")
1975 && validate_colon(CHILD(tree
, 1))
1976 && validate_suite(CHILD(tree
, 2))
1977 && validate_colon(CHILD(tree
, nch
- 2))
1978 && validate_suite(CHILD(tree
, nch
- 1)));
1979 else if (!PyErr_Occurred()) {
1980 const char* name
= "except";
1981 if (TYPE(CHILD(tree
, nch
- 3)) != except_clause
)
1982 name
= STR(CHILD(tree
, nch
- 3));
1984 PyErr_Format(parser_error
,
1985 "Illegal number of children for try/%s node.", name
);
1987 /* Skip past except_clause sections: */
1988 while (res
&& (TYPE(CHILD(tree
, pos
)) == except_clause
)) {
1989 res
= (validate_except_clause(CHILD(tree
, pos
))
1990 && validate_colon(CHILD(tree
, pos
+ 1))
1991 && validate_suite(CHILD(tree
, pos
+ 2)));
1994 if (res
&& (pos
< nch
)) {
1995 res
= validate_ntype(CHILD(tree
, pos
), NAME
);
1996 if (res
&& (strcmp(STR(CHILD(tree
, pos
)), "finally") == 0))
1997 res
= (validate_numnodes(tree
, 6, "try/finally")
1998 && validate_colon(CHILD(tree
, 4))
1999 && validate_suite(CHILD(tree
, 5)));
2001 if (nch
== (pos
+ 3)) {
2002 res
= ((strcmp(STR(CHILD(tree
, pos
)), "except") == 0)
2003 || (strcmp(STR(CHILD(tree
, pos
)), "else") == 0));
2005 err_string("illegal trailing triple in try statement");
2007 else if (nch
== (pos
+ 6)) {
2008 res
= (validate_name(CHILD(tree
, pos
), "except")
2009 && validate_colon(CHILD(tree
, pos
+ 1))
2010 && validate_suite(CHILD(tree
, pos
+ 2))
2011 && validate_name(CHILD(tree
, pos
+ 3), "else"));
2014 res
= validate_numnodes(tree
, pos
+ 3, "try/except");
2022 validate_except_clause(node
*tree
)
2024 int nch
= NCH(tree
);
2025 int res
= (validate_ntype(tree
, except_clause
)
2026 && ((nch
== 1) || (nch
== 2) || (nch
== 4))
2027 && validate_name(CHILD(tree
, 0), "except"));
2029 if (res
&& (nch
> 1))
2030 res
= validate_test(CHILD(tree
, 1));
2031 if (res
&& (nch
== 4))
2032 res
= (validate_comma(CHILD(tree
, 2))
2033 && validate_test(CHILD(tree
, 3)));
2040 validate_test(node
*tree
)
2042 int nch
= NCH(tree
);
2043 int res
= validate_ntype(tree
, test
) && is_odd(nch
);
2045 if (res
&& (TYPE(CHILD(tree
, 0)) == lambdef
))
2047 && validate_lambdef(CHILD(tree
, 0)));
2050 res
= validate_and_test(CHILD(tree
, 0));
2051 for (pos
= 1; res
&& (pos
< nch
); pos
+= 2)
2052 res
= (validate_name(CHILD(tree
, pos
), "or")
2053 && validate_and_test(CHILD(tree
, pos
+ 1)));
2060 validate_and_test(node
*tree
)
2063 int nch
= NCH(tree
);
2064 int res
= (validate_ntype(tree
, and_test
)
2066 && validate_not_test(CHILD(tree
, 0)));
2068 for (pos
= 1; res
&& (pos
< nch
); pos
+= 2)
2069 res
= (validate_name(CHILD(tree
, pos
), "and")
2070 && validate_not_test(CHILD(tree
, 0)));
2077 validate_not_test(node
*tree
)
2079 int nch
= NCH(tree
);
2080 int res
= validate_ntype(tree
, not_test
) && ((nch
== 1) || (nch
== 2));
2084 res
= (validate_name(CHILD(tree
, 0), "not")
2085 && validate_not_test(CHILD(tree
, 1)));
2087 res
= validate_comparison(CHILD(tree
, 0));
2094 validate_comparison(node
*tree
)
2097 int nch
= NCH(tree
);
2098 int res
= (validate_ntype(tree
, comparison
)
2100 && validate_expr(CHILD(tree
, 0)));
2102 for (pos
= 1; res
&& (pos
< nch
); pos
+= 2)
2103 res
= (validate_comp_op(CHILD(tree
, pos
))
2104 && validate_expr(CHILD(tree
, pos
+ 1)));
2111 validate_comp_op(node
*tree
)
2114 int nch
= NCH(tree
);
2116 if (!validate_ntype(tree
, comp_op
))
2120 * Only child will be a terminal with a well-defined symbolic name
2121 * or a NAME with a string of either 'is' or 'in'
2123 tree
= CHILD(tree
, 0);
2124 switch (TYPE(tree
)) {
2135 res
= ((strcmp(STR(tree
), "in") == 0)
2136 || (strcmp(STR(tree
), "is") == 0));
2138 PyErr_Format(parser_error
,
2139 "illegal operator '%s'", STR(tree
));
2143 err_string("illegal comparison operator type");
2147 else if ((res
= validate_numnodes(tree
, 2, "comp_op")) != 0) {
2148 res
= (validate_ntype(CHILD(tree
, 0), NAME
)
2149 && validate_ntype(CHILD(tree
, 1), NAME
)
2150 && (((strcmp(STR(CHILD(tree
, 0)), "is") == 0)
2151 && (strcmp(STR(CHILD(tree
, 1)), "not") == 0))
2152 || ((strcmp(STR(CHILD(tree
, 0)), "not") == 0)
2153 && (strcmp(STR(CHILD(tree
, 1)), "in") == 0))));
2154 if (!res
&& !PyErr_Occurred())
2155 err_string("unknown comparison operator");
2162 validate_expr(node
*tree
)
2165 int nch
= NCH(tree
);
2166 int res
= (validate_ntype(tree
, expr
)
2168 && validate_xor_expr(CHILD(tree
, 0)));
2170 for (j
= 2; res
&& (j
< nch
); j
+= 2)
2171 res
= (validate_xor_expr(CHILD(tree
, j
))
2172 && validate_vbar(CHILD(tree
, j
- 1)));
2179 validate_xor_expr(node
*tree
)
2182 int nch
= NCH(tree
);
2183 int res
= (validate_ntype(tree
, xor_expr
)
2185 && validate_and_expr(CHILD(tree
, 0)));
2187 for (j
= 2; res
&& (j
< nch
); j
+= 2)
2188 res
= (validate_circumflex(CHILD(tree
, j
- 1))
2189 && validate_and_expr(CHILD(tree
, j
)));
2196 validate_and_expr(node
*tree
)
2199 int nch
= NCH(tree
);
2200 int res
= (validate_ntype(tree
, and_expr
)
2202 && validate_shift_expr(CHILD(tree
, 0)));
2204 for (pos
= 1; res
&& (pos
< nch
); pos
+= 2)
2205 res
= (validate_ampersand(CHILD(tree
, pos
))
2206 && validate_shift_expr(CHILD(tree
, pos
+ 1)));
2213 validate_chain_two_ops(node
*tree
, int (*termvalid
)(node
*), int op1
, int op2
)
2216 int nch
= NCH(tree
);
2217 int res
= (is_odd(nch
)
2218 && (*termvalid
)(CHILD(tree
, 0)));
2220 for ( ; res
&& (pos
< nch
); pos
+= 2) {
2221 if (TYPE(CHILD(tree
, pos
)) != op1
)
2222 res
= validate_ntype(CHILD(tree
, pos
), op2
);
2224 res
= (*termvalid
)(CHILD(tree
, pos
+ 1));
2231 validate_shift_expr(node
*tree
)
2233 return (validate_ntype(tree
, shift_expr
)
2234 && validate_chain_two_ops(tree
, validate_arith_expr
,
2235 LEFTSHIFT
, RIGHTSHIFT
));
2240 validate_arith_expr(node
*tree
)
2242 return (validate_ntype(tree
, arith_expr
)
2243 && validate_chain_two_ops(tree
, validate_term
, PLUS
, MINUS
));
2248 validate_term(node
*tree
)
2251 int nch
= NCH(tree
);
2252 int res
= (validate_ntype(tree
, term
)
2254 && validate_factor(CHILD(tree
, 0)));
2256 for ( ; res
&& (pos
< nch
); pos
+= 2)
2257 res
= (((TYPE(CHILD(tree
, pos
)) == STAR
)
2258 || (TYPE(CHILD(tree
, pos
)) == SLASH
)
2259 || (TYPE(CHILD(tree
, pos
)) == DOUBLESLASH
)
2260 || (TYPE(CHILD(tree
, pos
)) == PERCENT
))
2261 && validate_factor(CHILD(tree
, pos
+ 1)));
2269 * factor: ('+'|'-'|'~') factor | power
2272 validate_factor(node
*tree
)
2274 int nch
= NCH(tree
);
2275 int res
= (validate_ntype(tree
, factor
)
2277 && ((TYPE(CHILD(tree
, 0)) == PLUS
)
2278 || (TYPE(CHILD(tree
, 0)) == MINUS
)
2279 || (TYPE(CHILD(tree
, 0)) == TILDE
))
2280 && validate_factor(CHILD(tree
, 1)))
2282 && validate_power(CHILD(tree
, 0)))));
2289 * power: atom trailer* ('**' factor)*
2292 validate_power(node
*tree
)
2295 int nch
= NCH(tree
);
2296 int res
= (validate_ntype(tree
, power
) && (nch
>= 1)
2297 && validate_atom(CHILD(tree
, 0)));
2299 while (res
&& (pos
< nch
) && (TYPE(CHILD(tree
, pos
)) == trailer
))
2300 res
= validate_trailer(CHILD(tree
, pos
++));
2301 if (res
&& (pos
< nch
)) {
2302 if (!is_even(nch
- pos
)) {
2303 err_string("illegal number of nodes for 'power'");
2306 for ( ; res
&& (pos
< (nch
- 1)); pos
+= 2)
2307 res
= (validate_doublestar(CHILD(tree
, pos
))
2308 && validate_factor(CHILD(tree
, pos
+ 1)));
2315 validate_atom(node
*tree
)
2318 int nch
= NCH(tree
);
2319 int res
= validate_ntype(tree
, atom
);
2322 res
= validate_numnodes(tree
, nch
+1, "atom");
2324 switch (TYPE(CHILD(tree
, 0))) {
2327 && (validate_rparen(CHILD(tree
, nch
- 1))));
2329 if (res
&& (nch
== 3)) {
2330 if (TYPE(CHILD(tree
, 1))==yield_expr
)
2331 res
= validate_yield_expr(CHILD(tree
, 1));
2333 res
= validate_testlist_gexp(CHILD(tree
, 1));
2338 res
= validate_ntype(CHILD(tree
, 1), RSQB
);
2340 res
= (validate_listmaker(CHILD(tree
, 1))
2341 && validate_ntype(CHILD(tree
, 2), RSQB
));
2344 err_string("illegal list display atom");
2349 && validate_ntype(CHILD(tree
, nch
- 1), RBRACE
));
2351 if (res
&& (nch
== 3))
2352 res
= validate_dictmaker(CHILD(tree
, 1));
2356 && validate_testlist1(CHILD(tree
, 1))
2357 && validate_ntype(CHILD(tree
, 2), BACKQUOTE
));
2364 for (pos
= 1; res
&& (pos
< nch
); ++pos
)
2365 res
= validate_ntype(CHILD(tree
, pos
), STRING
);
2377 * test ( list_for | (',' test)* [','] )
2380 validate_listmaker(node
*tree
)
2382 int nch
= NCH(tree
);
2386 err_string("missing child nodes of listmaker");
2388 ok
= validate_test(CHILD(tree
, 0));
2391 * list_for | (',' test)* [',']
2393 if (nch
== 2 && TYPE(CHILD(tree
, 1)) == list_for
)
2394 ok
= validate_list_for(CHILD(tree
, 1));
2396 /* (',' test)* [','] */
2398 while (ok
&& nch
- i
>= 2) {
2399 ok
= (validate_comma(CHILD(tree
, i
))
2400 && validate_test(CHILD(tree
, i
+1)));
2403 if (ok
&& i
== nch
-1)
2404 ok
= validate_comma(CHILD(tree
, i
));
2405 else if (i
!= nch
) {
2407 err_string("illegal trailing nodes for listmaker");
2414 * test ( gen_for | (',' test)* [','] )
2417 validate_testlist_gexp(node
*tree
)
2419 int nch
= NCH(tree
);
2423 err_string("missing child nodes of testlist_gexp");
2425 ok
= validate_test(CHILD(tree
, 0));
2429 * gen_for | (',' test)* [',']
2431 if (nch
== 2 && TYPE(CHILD(tree
, 1)) == gen_for
)
2432 ok
= validate_gen_for(CHILD(tree
, 1));
2434 /* (',' test)* [','] */
2436 while (ok
&& nch
- i
>= 2) {
2437 ok
= (validate_comma(CHILD(tree
, i
))
2438 && validate_test(CHILD(tree
, i
+1)));
2441 if (ok
&& i
== nch
-1)
2442 ok
= validate_comma(CHILD(tree
, i
));
2443 else if (i
!= nch
) {
2445 err_string("illegal trailing nodes for testlist_gexp");
2452 * '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
2455 validate_decorator(node
*tree
)
2458 int nch
= NCH(tree
);
2459 ok
= (validate_ntype(tree
, decorator
) &&
2460 (nch
== 3 || nch
== 5 || nch
== 6) &&
2461 validate_at(CHILD(tree
, 0)) &&
2462 validate_dotted_name(CHILD(tree
, 1)) &&
2463 validate_newline(RCHILD(tree
, -1)));
2465 if (ok
&& nch
!= 3) {
2466 ok
= (validate_lparen(CHILD(tree
, 2)) &&
2467 validate_rparen(RCHILD(tree
, -2)));
2470 ok
= validate_arglist(CHILD(tree
, 3));
2480 validate_decorators(node
*tree
)
2484 ok
= validate_ntype(tree
, decorators
) && nch
>= 1;
2486 for (i
= 0; ok
&& i
< nch
; ++i
)
2487 ok
= validate_decorator(CHILD(tree
, i
));
2495 * [decorators] 'def' NAME parameters ':' suite
2498 validate_funcdef(node
*tree
)
2500 int nch
= NCH(tree
);
2501 int ok
= (validate_ntype(tree
, funcdef
)
2502 && ((nch
== 5) || (nch
== 6))
2503 && validate_name(RCHILD(tree
, -5), "def")
2504 && validate_ntype(RCHILD(tree
, -4), NAME
)
2505 && validate_colon(RCHILD(tree
, -2))
2506 && validate_parameters(RCHILD(tree
, -3))
2507 && validate_suite(RCHILD(tree
, -1)));
2509 if (ok
&& (nch
== 6))
2510 ok
= validate_decorators(CHILD(tree
, 0));
2517 validate_lambdef(node
*tree
)
2519 int nch
= NCH(tree
);
2520 int res
= (validate_ntype(tree
, lambdef
)
2521 && ((nch
== 3) || (nch
== 4))
2522 && validate_name(CHILD(tree
, 0), "lambda")
2523 && validate_colon(CHILD(tree
, nch
- 2))
2524 && validate_test(CHILD(tree
, nch
- 1)));
2526 if (res
&& (nch
== 4))
2527 res
= validate_varargslist(CHILD(tree
, 1));
2528 else if (!res
&& !PyErr_Occurred())
2529 (void) validate_numnodes(tree
, 3, "lambdef");
2537 * (argument ',')* (argument [','] | '*' test [',' '**' test] | '**' test)
2540 validate_arglist(node
*tree
)
2542 int nch
= NCH(tree
);
2547 /* raise the right error from having an invalid number of children */
2548 return validate_numnodes(tree
, nch
+ 1, "arglist");
2551 for (i
=0; i
<nch
; i
++) {
2552 if (TYPE(CHILD(tree
, i
)) == argument
) {
2553 node
*ch
= CHILD(tree
, i
);
2554 if (NCH(ch
) == 2 && TYPE(CHILD(ch
, 1)) == gen_for
) {
2555 err_string("need '(', ')' for generator expression");
2562 while (ok
&& nch
-i
>= 2) {
2563 /* skip leading (argument ',') */
2564 ok
= (validate_argument(CHILD(tree
, i
))
2565 && validate_comma(CHILD(tree
, i
+1)));
2574 * argument | '*' test [',' '**' test] | '**' test
2576 int sym
= TYPE(CHILD(tree
, i
));
2578 if (sym
== argument
) {
2579 ok
= validate_argument(CHILD(tree
, i
));
2580 if (ok
&& i
+1 != nch
) {
2581 err_string("illegal arglist specification"
2582 " (extra stuff on end)");
2586 else if (sym
== STAR
) {
2587 ok
= validate_star(CHILD(tree
, i
));
2588 if (ok
&& (nch
-i
== 2))
2589 ok
= validate_test(CHILD(tree
, i
+1));
2590 else if (ok
&& (nch
-i
== 5))
2591 ok
= (validate_test(CHILD(tree
, i
+1))
2592 && validate_comma(CHILD(tree
, i
+2))
2593 && validate_doublestar(CHILD(tree
, i
+3))
2594 && validate_test(CHILD(tree
, i
+4)));
2596 err_string("illegal use of '*' in arglist");
2600 else if (sym
== DOUBLESTAR
) {
2602 ok
= (validate_doublestar(CHILD(tree
, i
))
2603 && validate_test(CHILD(tree
, i
+1)));
2605 err_string("illegal use of '**' in arglist");
2610 err_string("illegal arglist specification");
2621 * [test '='] test [gen_for]
2624 validate_argument(node
*tree
)
2626 int nch
= NCH(tree
);
2627 int res
= (validate_ntype(tree
, argument
)
2628 && ((nch
== 1) || (nch
== 2) || (nch
== 3))
2629 && validate_test(CHILD(tree
, 0)));
2631 if (res
&& (nch
== 2))
2632 res
= validate_gen_for(CHILD(tree
, 1));
2633 else if (res
&& (nch
== 3))
2634 res
= (validate_equal(CHILD(tree
, 1))
2635 && validate_test(CHILD(tree
, 2)));
2644 * '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
2647 validate_trailer(node
*tree
)
2649 int nch
= NCH(tree
);
2650 int res
= validate_ntype(tree
, trailer
) && ((nch
== 2) || (nch
== 3));
2653 switch (TYPE(CHILD(tree
, 0))) {
2655 res
= validate_rparen(CHILD(tree
, nch
- 1));
2656 if (res
&& (nch
== 3))
2657 res
= validate_arglist(CHILD(tree
, 1));
2660 res
= (validate_numnodes(tree
, 3, "trailer")
2661 && validate_subscriptlist(CHILD(tree
, 1))
2662 && validate_ntype(CHILD(tree
, 2), RSQB
));
2665 res
= (validate_numnodes(tree
, 2, "trailer")
2666 && validate_ntype(CHILD(tree
, 1), NAME
));
2674 (void) validate_numnodes(tree
, 2, "trailer");
2682 * subscript (',' subscript)* [',']
2685 validate_subscriptlist(node
*tree
)
2687 return (validate_repeating_list(tree
, subscriptlist
,
2688 validate_subscript
, "subscriptlist"));
2694 * '.' '.' '.' | test | [test] ':' [test] [sliceop]
2697 validate_subscript(node
*tree
)
2700 int nch
= NCH(tree
);
2701 int res
= validate_ntype(tree
, subscript
) && (nch
>= 1) && (nch
<= 4);
2704 if (!PyErr_Occurred())
2705 err_string("invalid number of arguments for subscript node");
2708 if (TYPE(CHILD(tree
, 0)) == DOT
)
2709 /* take care of ('.' '.' '.') possibility */
2710 return (validate_numnodes(tree
, 3, "subscript")
2711 && validate_dot(CHILD(tree
, 0))
2712 && validate_dot(CHILD(tree
, 1))
2713 && validate_dot(CHILD(tree
, 2)));
2715 if (TYPE(CHILD(tree
, 0)) == test
)
2716 res
= validate_test(CHILD(tree
, 0));
2718 res
= validate_colon(CHILD(tree
, 0));
2721 /* Must be [test] ':' [test] [sliceop],
2722 * but at least one of the optional components will
2723 * be present, but we don't know which yet.
2725 if ((TYPE(CHILD(tree
, 0)) != COLON
) || (nch
== 4)) {
2726 res
= validate_test(CHILD(tree
, 0));
2730 res
= validate_colon(CHILD(tree
, offset
));
2732 int rem
= nch
- ++offset
;
2734 if (TYPE(CHILD(tree
, offset
)) == test
) {
2735 res
= validate_test(CHILD(tree
, offset
));
2740 res
= validate_sliceop(CHILD(tree
, offset
));
2748 validate_sliceop(node
*tree
)
2750 int nch
= NCH(tree
);
2751 int res
= ((nch
== 1) || validate_numnodes(tree
, 2, "sliceop"))
2752 && validate_ntype(tree
, sliceop
);
2753 if (!res
&& !PyErr_Occurred()) {
2754 res
= validate_numnodes(tree
, 1, "sliceop");
2757 res
= validate_colon(CHILD(tree
, 0));
2758 if (res
&& (nch
== 2))
2759 res
= validate_test(CHILD(tree
, 1));
2766 validate_exprlist(node
*tree
)
2768 return (validate_repeating_list(tree
, exprlist
,
2769 validate_expr
, "exprlist"));
2774 validate_dictmaker(node
*tree
)
2776 int nch
= NCH(tree
);
2777 int res
= (validate_ntype(tree
, dictmaker
)
2779 && validate_test(CHILD(tree
, 0))
2780 && validate_colon(CHILD(tree
, 1))
2781 && validate_test(CHILD(tree
, 2)));
2783 if (res
&& ((nch
% 4) == 0))
2784 res
= validate_comma(CHILD(tree
, --nch
));
2786 res
= ((nch
% 4) == 3);
2788 if (res
&& (nch
> 3)) {
2790 /* ( ',' test ':' test )* */
2791 while (res
&& (pos
< nch
)) {
2792 res
= (validate_comma(CHILD(tree
, pos
))
2793 && validate_test(CHILD(tree
, pos
+ 1))
2794 && validate_colon(CHILD(tree
, pos
+ 2))
2795 && validate_test(CHILD(tree
, pos
+ 3)));
2804 validate_eval_input(node
*tree
)
2807 int nch
= NCH(tree
);
2808 int res
= (validate_ntype(tree
, eval_input
)
2810 && validate_testlist(CHILD(tree
, 0))
2811 && validate_ntype(CHILD(tree
, nch
- 1), ENDMARKER
));
2813 for (pos
= 1; res
&& (pos
< (nch
- 1)); ++pos
)
2814 res
= validate_ntype(CHILD(tree
, pos
), NEWLINE
);
2821 validate_node(node
*tree
)
2823 int nch
= 0; /* num. children on current node */
2824 int res
= 1; /* result value */
2825 node
* next
= 0; /* node to process after this one */
2827 while (res
&& (tree
!= 0)) {
2830 switch (TYPE(tree
)) {
2835 res
= validate_funcdef(tree
);
2838 res
= validate_class(tree
);
2841 * "Trivial" parse tree nodes.
2842 * (Why did I call these trivial?)
2845 res
= validate_stmt(tree
);
2849 * expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt
2850 * | import_stmt | global_stmt | exec_stmt | assert_stmt
2852 res
= validate_small_stmt(tree
);
2855 res
= (validate_numnodes(tree
, 1, "flow_stmt")
2856 && ((TYPE(CHILD(tree
, 0)) == break_stmt
)
2857 || (TYPE(CHILD(tree
, 0)) == continue_stmt
)
2858 || (TYPE(CHILD(tree
, 0)) == yield_stmt
)
2859 || (TYPE(CHILD(tree
, 0)) == return_stmt
)
2860 || (TYPE(CHILD(tree
, 0)) == raise_stmt
)));
2862 next
= CHILD(tree
, 0);
2864 err_string("illegal flow_stmt type");
2867 res
= validate_yield_stmt(tree
);
2870 * Compound statements.
2873 res
= validate_simple_stmt(tree
);
2876 res
= validate_compound_stmt(tree
);
2879 * Fundamental statements.
2882 res
= validate_expr_stmt(tree
);
2885 res
= validate_print_stmt(tree
);
2888 res
= validate_del_stmt(tree
);
2891 res
= (validate_numnodes(tree
, 1, "pass")
2892 && validate_name(CHILD(tree
, 0), "pass"));
2895 res
= (validate_numnodes(tree
, 1, "break")
2896 && validate_name(CHILD(tree
, 0), "break"));
2899 res
= (validate_numnodes(tree
, 1, "continue")
2900 && validate_name(CHILD(tree
, 0), "continue"));
2903 res
= validate_return_stmt(tree
);
2906 res
= validate_raise_stmt(tree
);
2909 res
= validate_import_stmt(tree
);
2912 res
= validate_import_name(tree
);
2915 res
= validate_import_from(tree
);
2918 res
= validate_global_stmt(tree
);
2921 res
= validate_exec_stmt(tree
);
2924 res
= validate_assert_stmt(tree
);
2927 res
= validate_if(tree
);
2930 res
= validate_while(tree
);
2933 res
= validate_for(tree
);
2936 res
= validate_try(tree
);
2939 res
= validate_suite(tree
);
2945 res
= validate_testlist(tree
);
2948 res
= validate_yield_expr(tree
);
2951 res
= validate_testlist1(tree
);
2954 res
= validate_test(tree
);
2957 res
= validate_and_test(tree
);
2960 res
= validate_not_test(tree
);
2963 res
= validate_comparison(tree
);
2966 res
= validate_exprlist(tree
);
2969 res
= validate_comp_op(tree
);
2972 res
= validate_expr(tree
);
2975 res
= validate_xor_expr(tree
);
2978 res
= validate_and_expr(tree
);
2981 res
= validate_shift_expr(tree
);
2984 res
= validate_arith_expr(tree
);
2987 res
= validate_term(tree
);
2990 res
= validate_factor(tree
);
2993 res
= validate_power(tree
);
2996 res
= validate_atom(tree
);
3000 /* Hopefully never reached! */
3001 err_string("unrecognized node type");
3012 validate_expr_tree(node
*tree
)
3014 int res
= validate_eval_input(tree
);
3016 if (!res
&& !PyErr_Occurred())
3017 err_string("could not validate expression tuple");
3024 * (NEWLINE | stmt)* ENDMARKER
3027 validate_file_input(node
*tree
)
3030 int nch
= NCH(tree
) - 1;
3031 int res
= ((nch
>= 0)
3032 && validate_ntype(CHILD(tree
, nch
), ENDMARKER
));
3034 for (j
= 0; res
&& (j
< nch
); ++j
) {
3035 if (TYPE(CHILD(tree
, j
)) == stmt
)
3036 res
= validate_stmt(CHILD(tree
, j
));
3038 res
= validate_newline(CHILD(tree
, j
));
3040 /* This stays in to prevent any internal failures from getting to the
3041 * user. Hopefully, this won't be needed. If a user reports getting
3042 * this, we have some debugging to do.
3044 if (!res
&& !PyErr_Occurred())
3045 err_string("VALIDATION FAILURE: report this to the maintainer!");
3051 validate_encoding_decl(node
*tree
)
3053 int nch
= NCH(tree
);
3054 int res
= ((nch
== 1)
3055 && validate_file_input(CHILD(tree
, 0)));
3057 if (!res
&& !PyErr_Occurred())
3058 err_string("Error Parsing encoding_decl");
3064 pickle_constructor
= NULL
;
3068 parser__pickler(PyObject
*self
, PyObject
*args
)
3070 NOTE(ARGUNUSED(self
))
3071 PyObject
*result
= NULL
;
3072 PyObject
*st
= NULL
;
3073 PyObject
*empty_dict
= NULL
;
3075 if (PyArg_ParseTuple(args
, "O!:_pickler", &PyST_Type
, &st
)) {
3079 if ((empty_dict
= PyDict_New()) == NULL
)
3081 if ((newargs
= Py_BuildValue("Oi", st
, 1)) == NULL
)
3083 tuple
= parser_st2tuple((PyST_Object
*)NULL
, newargs
, empty_dict
);
3084 if (tuple
!= NULL
) {
3085 result
= Py_BuildValue("O(O)", pickle_constructor
, tuple
);
3088 Py_DECREF(empty_dict
);
3092 Py_XDECREF(empty_dict
);
3098 /* Functions exported by this module. Most of this should probably
3099 * be converted into an ST object with methods, but that is better
3100 * done directly in Python, allowing subclasses to be created directly.
3101 * We'd really have to write a wrapper around it all anyway to allow
3104 static PyMethodDef parser_functions
[] = {
3105 {"ast2tuple", (PyCFunction
)parser_st2tuple
, PUBLIC_METHOD_TYPE
,
3106 PyDoc_STR("Creates a tuple-tree representation of an ST.")},
3107 {"ast2list", (PyCFunction
)parser_st2list
, PUBLIC_METHOD_TYPE
,
3108 PyDoc_STR("Creates a list-tree representation of an ST.")},
3109 {"compileast", (PyCFunction
)parser_compilest
, PUBLIC_METHOD_TYPE
,
3110 PyDoc_STR("Compiles an ST object into a code object.")},
3111 {"compilest", (PyCFunction
)parser_compilest
, PUBLIC_METHOD_TYPE
,
3112 PyDoc_STR("Compiles an ST object into a code object.")},
3113 {"expr", (PyCFunction
)parser_expr
, PUBLIC_METHOD_TYPE
,
3114 PyDoc_STR("Creates an ST object from an expression.")},
3115 {"isexpr", (PyCFunction
)parser_isexpr
, PUBLIC_METHOD_TYPE
,
3116 PyDoc_STR("Determines if an ST object was created from an expression.")},
3117 {"issuite", (PyCFunction
)parser_issuite
, PUBLIC_METHOD_TYPE
,
3118 PyDoc_STR("Determines if an ST object was created from a suite.")},
3119 {"suite", (PyCFunction
)parser_suite
, PUBLIC_METHOD_TYPE
,
3120 PyDoc_STR("Creates an ST object from a suite.")},
3121 {"sequence2ast", (PyCFunction
)parser_tuple2st
, PUBLIC_METHOD_TYPE
,
3122 PyDoc_STR("Creates an ST object from a tree representation.")},
3123 {"sequence2st", (PyCFunction
)parser_tuple2st
, PUBLIC_METHOD_TYPE
,
3124 PyDoc_STR("Creates an ST object from a tree representation.")},
3125 {"st2tuple", (PyCFunction
)parser_st2tuple
, PUBLIC_METHOD_TYPE
,
3126 PyDoc_STR("Creates a tuple-tree representation of an ST.")},
3127 {"st2list", (PyCFunction
)parser_st2list
, PUBLIC_METHOD_TYPE
,
3128 PyDoc_STR("Creates a list-tree representation of an ST.")},
3129 {"tuple2ast", (PyCFunction
)parser_tuple2st
, PUBLIC_METHOD_TYPE
,
3130 PyDoc_STR("Creates an ST object from a tree representation.")},
3131 {"tuple2st", (PyCFunction
)parser_tuple2st
, PUBLIC_METHOD_TYPE
,
3132 PyDoc_STR("Creates an ST object from a tree representation.")},
3134 /* private stuff: support pickle module */
3135 {"_pickler", (PyCFunction
)parser__pickler
, METH_VARARGS
,
3136 PyDoc_STR("Returns the pickle magic to allow ST objects to be pickled.")},
3138 {NULL
, NULL
, 0, NULL
}
3142 PyMODINIT_FUNC
initparser(void); /* supply a prototype */
3147 PyObject
*module
, *copyreg
;
3149 PyST_Type
.ob_type
= &PyType_Type
;
3150 module
= Py_InitModule("parser", parser_functions
);
3152 if (parser_error
== 0)
3153 parser_error
= PyErr_NewException("parser.ParserError", NULL
, NULL
);
3155 if (parser_error
== 0)
3156 /* caller will check PyErr_Occurred() */
3158 /* CAUTION: The code next used to skip bumping the refcount on
3159 * parser_error. That's a disaster if initparser() gets called more
3160 * than once. By incref'ing, we ensure that each module dict that
3161 * gets created owns its reference to the shared parser_error object,
3162 * and the file static parser_error vrbl owns a reference too.
3164 Py_INCREF(parser_error
);
3165 if (PyModule_AddObject(module
, "ParserError", parser_error
) != 0)
3168 Py_INCREF(&PyST_Type
);
3169 PyModule_AddObject(module
, "ASTType", (PyObject
*)&PyST_Type
);
3170 Py_INCREF(&PyST_Type
);
3171 PyModule_AddObject(module
, "STType", (PyObject
*)&PyST_Type
);
3173 PyModule_AddStringConstant(module
, "__copyright__",
3174 parser_copyright_string
);
3175 PyModule_AddStringConstant(module
, "__doc__",
3177 PyModule_AddStringConstant(module
, "__version__",
3178 parser_version_string
);
3180 /* Register to support pickling.
3181 * If this fails, the import of this module will fail because an
3182 * exception will be raised here; should we clear the exception?
3184 copyreg
= PyImport_ImportModule("copy_reg");
3185 if (copyreg
!= NULL
) {
3186 PyObject
*func
, *pickler
;
3188 func
= PyObject_GetAttrString(copyreg
, "pickle");
3189 pickle_constructor
= PyObject_GetAttrString(module
, "sequence2st");
3190 pickler
= PyObject_GetAttrString(module
, "_pickler");
3191 Py_XINCREF(pickle_constructor
);
3192 if ((func
!= NULL
) && (pickle_constructor
!= NULL
)
3193 && (pickler
!= NULL
)) {
3196 res
= PyObject_CallFunction(func
, "OOO", &PyST_Type
, pickler
,
3197 pickle_constructor
);
3201 Py_XDECREF(pickle_constructor
);
3202 Py_XDECREF(pickler
);