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? */
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
, 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 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 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 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 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 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
, 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 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 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 Py_ssize_t len
= PyObject_Size(tuple
);
639 for (i
= 1; i
< len
; ++i
) {
640 /* elem must always be a sequence, however simple */
641 PyObject
* elem
= PySequence_GetItem(tuple
, i
);
642 int ok
= elem
!= NULL
;
647 ok
= PySequence_Check(elem
);
649 PyObject
*temp
= PySequence_GetItem(elem
, 0);
653 ok
= PyInt_Check(temp
);
655 type
= PyInt_AS_LONG(temp
);
660 PyObject
*err
= Py_BuildValue("os", elem
,
661 "Illegal node construct.");
662 PyErr_SetObject(parser_error
, err
);
667 if (ISTERMINAL(type
)) {
668 Py_ssize_t len
= PyObject_Size(elem
);
671 if ((len
!= 2) && (len
!= 3)) {
672 err_string("terminal nodes must have 2 or 3 entries");
675 temp
= PySequence_GetItem(elem
, 1);
678 if (!PyString_Check(temp
)) {
679 PyErr_Format(parser_error
,
680 "second item in terminal node must be a string,"
682 temp
->ob_type
->tp_name
);
687 PyObject
*o
= PySequence_GetItem(elem
, 2);
690 *line_num
= PyInt_AS_LONG(o
);
692 PyErr_Format(parser_error
,
693 "third item in terminal node must be an"
694 " integer, found %s",
695 temp
->ob_type
->tp_name
);
703 len
= PyString_GET_SIZE(temp
) + 1;
704 strn
= (char *)PyObject_MALLOC(len
);
706 (void) memcpy(strn
, PyString_AS_STRING(temp
), len
);
709 else if (!ISNONTERMINAL(type
)) {
711 * It has to be one or the other; this is an error.
712 * Throw an exception.
714 PyObject
*err
= Py_BuildValue("os", elem
, "unknown node type.");
715 PyErr_SetObject(parser_error
, err
);
720 err
= PyNode_AddChild(root
, type
, strn
, *line_num
, 0);
721 if (err
== E_NOMEM
) {
723 return (node
*) PyErr_NoMemory();
725 if (err
== E_OVERFLOW
) {
727 PyErr_SetString(PyExc_ValueError
,
728 "unsupported number of child nodes");
732 if (ISNONTERMINAL(type
)) {
733 node
* new_child
= CHILD(root
, i
- 1);
735 if (new_child
!= build_node_children(elem
, new_child
, line_num
)) {
740 else if (type
== NEWLINE
) { /* It's true: we increment the */
741 ++(*line_num
); /* line number *after* the newline! */
750 build_node_tree(PyObject
*tuple
)
753 PyObject
*temp
= PySequence_GetItem(tuple
, 0);
757 num
= PyInt_AsLong(temp
);
759 if (ISTERMINAL(num
)) {
761 * The tuple is simple, but it doesn't start with a start symbol.
762 * Throw an exception now and be done with it.
764 tuple
= Py_BuildValue("os", tuple
,
765 "Illegal syntax-tree; cannot start with terminal symbol.");
766 PyErr_SetObject(parser_error
, tuple
);
769 else if (ISNONTERMINAL(num
)) {
771 * Not efficient, but that can be handled later.
774 PyObject
*encoding
= NULL
;
776 if (num
== encoding_decl
) {
777 encoding
= PySequence_GetItem(tuple
, 2);
778 /* tuple isn't borrowed anymore here, need to DECREF */
779 tuple
= PySequence_GetSlice(tuple
, 0, 2);
781 res
= PyNode_New(num
);
783 if (res
!= build_node_children(tuple
, res
, &line_num
)) {
787 if (res
&& encoding
) {
789 len
= PyString_GET_SIZE(encoding
) + 1;
790 res
->n_str
= (char *)PyObject_MALLOC(len
);
791 if (res
->n_str
!= NULL
)
792 (void) memcpy(res
->n_str
, PyString_AS_STRING(encoding
), len
);
799 /* The tuple is illegal -- if the number is neither TERMINAL nor
800 * NONTERMINAL, we can't use it. Not sure the implementation
801 * allows this condition, but the API doesn't preclude it.
803 PyObject
*err
= Py_BuildValue("os", tuple
,
804 "Illegal component tuple.");
805 PyErr_SetObject(parser_error
, err
);
814 * Validation routines used within the validation section:
816 static int validate_terminal(node
*terminal
, int type
, char *string
);
818 #define validate_ampersand(ch) validate_terminal(ch, AMPER, "&")
819 #define validate_circumflex(ch) validate_terminal(ch, CIRCUMFLEX, "^")
820 #define validate_colon(ch) validate_terminal(ch, COLON, ":")
821 #define validate_comma(ch) validate_terminal(ch, COMMA, ",")
822 #define validate_dedent(ch) validate_terminal(ch, DEDENT, "")
823 #define validate_equal(ch) validate_terminal(ch, EQUAL, "=")
824 #define validate_indent(ch) validate_terminal(ch, INDENT, (char*)NULL)
825 #define validate_lparen(ch) validate_terminal(ch, LPAR, "(")
826 #define validate_newline(ch) validate_terminal(ch, NEWLINE, (char*)NULL)
827 #define validate_rparen(ch) validate_terminal(ch, RPAR, ")")
828 #define validate_semi(ch) validate_terminal(ch, SEMI, ";")
829 #define validate_star(ch) validate_terminal(ch, STAR, "*")
830 #define validate_vbar(ch) validate_terminal(ch, VBAR, "|")
831 #define validate_doublestar(ch) validate_terminal(ch, DOUBLESTAR, "**")
832 #define validate_dot(ch) validate_terminal(ch, DOT, ".")
833 #define validate_at(ch) validate_terminal(ch, AT, "@")
834 #define validate_name(ch, str) validate_terminal(ch, NAME, str)
836 #define VALIDATER(n) static int validate_##n(node *tree)
838 VALIDATER(node
); VALIDATER(small_stmt
);
839 VALIDATER(class); VALIDATER(node
);
840 VALIDATER(parameters
); VALIDATER(suite
);
841 VALIDATER(testlist
); VALIDATER(varargslist
);
842 VALIDATER(fpdef
); VALIDATER(fplist
);
843 VALIDATER(stmt
); VALIDATER(simple_stmt
);
844 VALIDATER(expr_stmt
); VALIDATER(power
);
845 VALIDATER(print_stmt
); VALIDATER(del_stmt
);
846 VALIDATER(return_stmt
); VALIDATER(list_iter
);
847 VALIDATER(raise_stmt
); VALIDATER(import_stmt
);
848 VALIDATER(import_name
); VALIDATER(import_from
);
849 VALIDATER(global_stmt
); VALIDATER(list_if
);
850 VALIDATER(assert_stmt
); VALIDATER(list_for
);
851 VALIDATER(exec_stmt
); VALIDATER(compound_stmt
);
852 VALIDATER(while); VALIDATER(for);
853 VALIDATER(try); VALIDATER(except_clause
);
854 VALIDATER(test
); VALIDATER(and_test
);
855 VALIDATER(not_test
); VALIDATER(comparison
);
856 VALIDATER(comp_op
); VALIDATER(expr
);
857 VALIDATER(xor_expr
); VALIDATER(and_expr
);
858 VALIDATER(shift_expr
); VALIDATER(arith_expr
);
859 VALIDATER(term
); VALIDATER(factor
);
860 VALIDATER(atom
); VALIDATER(lambdef
);
861 VALIDATER(trailer
); VALIDATER(subscript
);
862 VALIDATER(subscriptlist
); VALIDATER(sliceop
);
863 VALIDATER(exprlist
); VALIDATER(dictmaker
);
864 VALIDATER(arglist
); VALIDATER(argument
);
865 VALIDATER(listmaker
); VALIDATER(yield_stmt
);
866 VALIDATER(testlist1
); VALIDATER(gen_for
);
867 VALIDATER(gen_iter
); VALIDATER(gen_if
);
868 VALIDATER(testlist_gexp
); VALIDATER(yield_expr
);
869 VALIDATER(yield_or_testlist
); VALIDATER(or_test
);
870 VALIDATER(old_test
); VALIDATER(old_lambdef
);
874 #define is_even(n) (((n) & 1) == 0)
875 #define is_odd(n) (((n) & 1) == 1)
879 validate_ntype(node
*n
, int t
)
882 PyErr_Format(parser_error
, "Expected node type %d, got %d.",
890 /* Verifies that the number of child nodes is exactly 'num', raising
891 * an exception if it isn't. The exception message does not indicate
892 * the exact number of nodes, allowing this to be used to raise the
893 * "right" exception when the wrong number of nodes is present in a
894 * specific variant of a statement's syntax. This is commonly used
898 validate_numnodes(node
*n
, int num
, const char *const name
)
901 PyErr_Format(parser_error
,
902 "Illegal number of children for %s node.", name
);
910 validate_terminal(node
*terminal
, int type
, char *string
)
912 int res
= (validate_ntype(terminal
, type
)
913 && ((string
== 0) || (strcmp(string
, STR(terminal
)) == 0)));
915 if (!res
&& !PyErr_Occurred()) {
916 PyErr_Format(parser_error
,
917 "Illegal terminal: expected \"%s\"", string
);
926 validate_repeating_list(node
*tree
, int ntype
, int (*vfunc
)(node
*),
927 const char *const name
)
930 int res
= (nch
&& validate_ntype(tree
, ntype
)
931 && vfunc(CHILD(tree
, 0)));
933 if (!res
&& !PyErr_Occurred())
934 (void) validate_numnodes(tree
, 1, name
);
937 res
= validate_comma(CHILD(tree
, --nch
));
938 if (res
&& nch
> 1) {
940 for ( ; res
&& pos
< nch
; pos
+= 2)
941 res
= (validate_comma(CHILD(tree
, pos
))
942 && vfunc(CHILD(tree
, pos
+ 1)));
952 * 'class' NAME ['(' testlist ')'] ':' suite
955 validate_class(node
*tree
)
958 int res
= (validate_ntype(tree
, classdef
) &&
959 ((nch
== 4) || (nch
== 6) || (nch
== 7)));
962 res
= (validate_name(CHILD(tree
, 0), "class")
963 && validate_ntype(CHILD(tree
, 1), NAME
)
964 && validate_colon(CHILD(tree
, nch
- 2))
965 && validate_suite(CHILD(tree
, nch
- 1)));
968 (void) validate_numnodes(tree
, 4, "class");
973 res
= ((validate_lparen(CHILD(tree
, 2)) &&
974 validate_testlist(CHILD(tree
, 3)) &&
975 validate_rparen(CHILD(tree
, 4))));
978 res
= (validate_lparen(CHILD(tree
,2)) &&
979 validate_rparen(CHILD(tree
,3)));
987 * 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
990 validate_if(node
*tree
)
993 int res
= (validate_ntype(tree
, if_stmt
)
995 && validate_name(CHILD(tree
, 0), "if")
996 && validate_test(CHILD(tree
, 1))
997 && validate_colon(CHILD(tree
, 2))
998 && validate_suite(CHILD(tree
, 3)));
1000 if (res
&& ((nch
% 4) == 3)) {
1001 /* ... 'else' ':' suite */
1002 res
= (validate_name(CHILD(tree
, nch
- 3), "else")
1003 && validate_colon(CHILD(tree
, nch
- 2))
1004 && validate_suite(CHILD(tree
, nch
- 1)));
1007 else if (!res
&& !PyErr_Occurred())
1008 (void) validate_numnodes(tree
, 4, "if");
1010 /* Will catch the case for nch < 4 */
1011 res
= validate_numnodes(tree
, 0, "if");
1012 else if (res
&& (nch
> 4)) {
1013 /* ... ('elif' test ':' suite)+ ... */
1015 while ((j
< nch
) && res
) {
1016 res
= (validate_name(CHILD(tree
, j
), "elif")
1017 && validate_colon(CHILD(tree
, j
+ 2))
1018 && validate_test(CHILD(tree
, j
+ 1))
1019 && validate_suite(CHILD(tree
, j
+ 3)));
1028 * '(' [varargslist] ')'
1032 validate_parameters(node
*tree
)
1034 int nch
= NCH(tree
);
1035 int res
= validate_ntype(tree
, parameters
) && ((nch
== 2) || (nch
== 3));
1038 res
= (validate_lparen(CHILD(tree
, 0))
1039 && validate_rparen(CHILD(tree
, nch
- 1)));
1040 if (res
&& (nch
== 3))
1041 res
= validate_varargslist(CHILD(tree
, 1));
1044 (void) validate_numnodes(tree
, 2, "parameters");
1054 * | NEWLINE INDENT stmt+ DEDENT
1057 validate_suite(node
*tree
)
1059 int nch
= NCH(tree
);
1060 int res
= (validate_ntype(tree
, suite
) && ((nch
== 1) || (nch
>= 4)));
1062 if (res
&& (nch
== 1))
1063 res
= validate_simple_stmt(CHILD(tree
, 0));
1065 /* NEWLINE INDENT stmt+ DEDENT */
1066 res
= (validate_newline(CHILD(tree
, 0))
1067 && validate_indent(CHILD(tree
, 1))
1068 && validate_stmt(CHILD(tree
, 2))
1069 && validate_dedent(CHILD(tree
, nch
- 1)));
1071 if (res
&& (nch
> 4)) {
1073 --nch
; /* forget the DEDENT */
1074 for ( ; res
&& (i
< nch
); ++i
)
1075 res
= validate_stmt(CHILD(tree
, i
));
1078 res
= validate_numnodes(tree
, 4, "suite");
1085 validate_testlist(node
*tree
)
1087 return (validate_repeating_list(tree
, testlist
,
1088 validate_test
, "testlist"));
1093 validate_testlist1(node
*tree
)
1095 return (validate_repeating_list(tree
, testlist1
,
1096 validate_test
, "testlist1"));
1101 validate_testlist_safe(node
*tree
)
1103 return (validate_repeating_list(tree
, testlist_safe
,
1104 validate_old_test
, "testlist_safe"));
1108 /* '*' NAME [',' '**' NAME] | '**' NAME
1111 validate_varargslist_trailer(node
*tree
, int start
)
1113 int nch
= NCH(tree
);
1118 err_string("expected variable argument trailer for varargslist");
1121 sym
= TYPE(CHILD(tree
, start
));
1124 * ('*' NAME [',' '**' NAME]
1127 res
= validate_name(CHILD(tree
, start
+1), NULL
);
1128 else if (nch
-start
== 5)
1129 res
= (validate_name(CHILD(tree
, start
+1), NULL
)
1130 && validate_comma(CHILD(tree
, start
+2))
1131 && validate_doublestar(CHILD(tree
, start
+3))
1132 && validate_name(CHILD(tree
, start
+4), NULL
));
1134 else if (sym
== DOUBLESTAR
) {
1139 res
= validate_name(CHILD(tree
, start
+1), NULL
);
1142 err_string("illegal variable argument trailer for varargslist");
1147 /* validate_varargslist()
1150 * (fpdef ['=' test] ',')*
1151 * ('*' NAME [',' '**' NAME]
1153 * | fpdef ['=' test] (',' fpdef ['=' test])* [',']
1157 validate_varargslist(node
*tree
)
1159 int nch
= NCH(tree
);
1160 int res
= validate_ntype(tree
, varargslist
) && (nch
!= 0);
1166 err_string("varargslist missing child nodes");
1169 sym
= TYPE(CHILD(tree
, 0));
1170 if (sym
== STAR
|| sym
== DOUBLESTAR
)
1171 /* whole thing matches:
1172 * '*' NAME [',' '**' NAME] | '**' NAME
1174 res
= validate_varargslist_trailer(tree
, 0);
1175 else if (sym
== fpdef
) {
1178 sym
= TYPE(CHILD(tree
, nch
-1));
1181 * (fpdef ['=' test] ',')+
1182 * ('*' NAME [',' '**' NAME]
1185 /* skip over (fpdef ['=' test] ',')+ */
1186 while (res
&& (i
+2 <= nch
)) {
1187 res
= validate_fpdef(CHILD(tree
, i
));
1189 if (res
&& TYPE(CHILD(tree
, i
)) == EQUAL
&& (i
+2 <= nch
)) {
1190 res
= (validate_equal(CHILD(tree
, i
))
1191 && validate_test(CHILD(tree
, i
+1)));
1195 if (res
&& i
< nch
) {
1196 res
= validate_comma(CHILD(tree
, i
));
1199 && (TYPE(CHILD(tree
, i
)) == DOUBLESTAR
1200 || TYPE(CHILD(tree
, i
)) == STAR
))
1204 /* ... '*' NAME [',' '**' NAME] | '**' NAME
1208 res
= validate_varargslist_trailer(tree
, i
);
1212 * fpdef ['=' test] (',' fpdef ['=' test])* [',']
1214 /* strip trailing comma node */
1216 res
= validate_comma(CHILD(tree
, nch
-1));
1222 * fpdef ['=' test] (',' fpdef ['=' test])*
1224 res
= validate_fpdef(CHILD(tree
, 0));
1226 if (res
&& (i
+2 <= nch
) && TYPE(CHILD(tree
, i
)) == EQUAL
) {
1227 res
= (validate_equal(CHILD(tree
, i
))
1228 && validate_test(CHILD(tree
, i
+1)));
1232 * ... (',' fpdef ['=' test])*
1235 while (res
&& (nch
- i
) >= 2) {
1236 res
= (validate_comma(CHILD(tree
, i
))
1237 && validate_fpdef(CHILD(tree
, i
+1)));
1239 if (res
&& (nch
- i
) >= 2 && TYPE(CHILD(tree
, i
)) == EQUAL
) {
1240 res
= (validate_equal(CHILD(tree
, i
))
1241 && validate_test(CHILD(tree
, i
+1)));
1245 if (res
&& nch
- i
!= 0) {
1247 err_string("illegal formation for varargslist");
1255 /* list_iter: list_for | list_if
1258 validate_list_iter(node
*tree
)
1260 int res
= (validate_ntype(tree
, list_iter
)
1261 && validate_numnodes(tree
, 1, "list_iter"));
1262 if (res
&& TYPE(CHILD(tree
, 0)) == list_for
)
1263 res
= validate_list_for(CHILD(tree
, 0));
1265 res
= validate_list_if(CHILD(tree
, 0));
1270 /* gen_iter: gen_for | gen_if
1273 validate_gen_iter(node
*tree
)
1275 int res
= (validate_ntype(tree
, gen_iter
)
1276 && validate_numnodes(tree
, 1, "gen_iter"));
1277 if (res
&& TYPE(CHILD(tree
, 0)) == gen_for
)
1278 res
= validate_gen_for(CHILD(tree
, 0));
1280 res
= validate_gen_if(CHILD(tree
, 0));
1285 /* list_for: 'for' exprlist 'in' testlist [list_iter]
1288 validate_list_for(node
*tree
)
1290 int nch
= NCH(tree
);
1294 res
= validate_list_iter(CHILD(tree
, 4));
1296 res
= validate_numnodes(tree
, 4, "list_for");
1299 res
= (validate_name(CHILD(tree
, 0), "for")
1300 && validate_exprlist(CHILD(tree
, 1))
1301 && validate_name(CHILD(tree
, 2), "in")
1302 && validate_testlist_safe(CHILD(tree
, 3)));
1307 /* gen_for: 'for' exprlist 'in' test [gen_iter]
1310 validate_gen_for(node
*tree
)
1312 int nch
= NCH(tree
);
1316 res
= validate_gen_iter(CHILD(tree
, 4));
1318 res
= validate_numnodes(tree
, 4, "gen_for");
1321 res
= (validate_name(CHILD(tree
, 0), "for")
1322 && validate_exprlist(CHILD(tree
, 1))
1323 && validate_name(CHILD(tree
, 2), "in")
1324 && validate_or_test(CHILD(tree
, 3)));
1329 /* list_if: 'if' old_test [list_iter]
1332 validate_list_if(node
*tree
)
1334 int nch
= NCH(tree
);
1338 res
= validate_list_iter(CHILD(tree
, 2));
1340 res
= validate_numnodes(tree
, 2, "list_if");
1343 res
= (validate_name(CHILD(tree
, 0), "if")
1344 && validate_old_test(CHILD(tree
, 1)));
1349 /* gen_if: 'if' old_test [gen_iter]
1352 validate_gen_if(node
*tree
)
1354 int nch
= NCH(tree
);
1358 res
= validate_gen_iter(CHILD(tree
, 2));
1360 res
= validate_numnodes(tree
, 2, "gen_if");
1363 res
= (validate_name(CHILD(tree
, 0), "if")
1364 && validate_old_test(CHILD(tree
, 1)));
1376 validate_fpdef(node
*tree
)
1378 int nch
= NCH(tree
);
1379 int res
= validate_ntype(tree
, fpdef
);
1383 res
= validate_ntype(CHILD(tree
, 0), NAME
);
1385 res
= (validate_lparen(CHILD(tree
, 0))
1386 && validate_fplist(CHILD(tree
, 1))
1387 && validate_rparen(CHILD(tree
, 2)));
1389 res
= validate_numnodes(tree
, 1, "fpdef");
1396 validate_fplist(node
*tree
)
1398 return (validate_repeating_list(tree
, fplist
,
1399 validate_fpdef
, "fplist"));
1403 /* simple_stmt | compound_stmt
1407 validate_stmt(node
*tree
)
1409 int res
= (validate_ntype(tree
, stmt
)
1410 && validate_numnodes(tree
, 1, "stmt"));
1413 tree
= CHILD(tree
, 0);
1415 if (TYPE(tree
) == simple_stmt
)
1416 res
= validate_simple_stmt(tree
);
1418 res
= validate_compound_stmt(tree
);
1424 /* small_stmt (';' small_stmt)* [';'] NEWLINE
1428 validate_simple_stmt(node
*tree
)
1430 int nch
= NCH(tree
);
1431 int res
= (validate_ntype(tree
, simple_stmt
)
1433 && validate_small_stmt(CHILD(tree
, 0))
1434 && validate_newline(CHILD(tree
, nch
- 1)));
1437 res
= validate_numnodes(tree
, 2, "simple_stmt");
1438 --nch
; /* forget the NEWLINE */
1439 if (res
&& is_even(nch
))
1440 res
= validate_semi(CHILD(tree
, --nch
));
1441 if (res
&& (nch
> 2)) {
1444 for (i
= 1; res
&& (i
< nch
); i
+= 2)
1445 res
= (validate_semi(CHILD(tree
, i
))
1446 && validate_small_stmt(CHILD(tree
, i
+ 1)));
1453 validate_small_stmt(node
*tree
)
1455 int nch
= NCH(tree
);
1456 int res
= validate_numnodes(tree
, 1, "small_stmt");
1459 int ntype
= TYPE(CHILD(tree
, 0));
1461 if ( (ntype
== expr_stmt
)
1462 || (ntype
== print_stmt
)
1463 || (ntype
== del_stmt
)
1464 || (ntype
== pass_stmt
)
1465 || (ntype
== flow_stmt
)
1466 || (ntype
== import_stmt
)
1467 || (ntype
== global_stmt
)
1468 || (ntype
== assert_stmt
)
1469 || (ntype
== exec_stmt
))
1470 res
= validate_node(CHILD(tree
, 0));
1473 err_string("illegal small_stmt child type");
1476 else if (nch
== 1) {
1478 PyErr_Format(parser_error
,
1479 "Unrecognized child node of small_stmt: %d.",
1480 TYPE(CHILD(tree
, 0)));
1487 * if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
1490 validate_compound_stmt(node
*tree
)
1492 int res
= (validate_ntype(tree
, compound_stmt
)
1493 && validate_numnodes(tree
, 1, "compound_stmt"));
1499 tree
= CHILD(tree
, 0);
1501 if ( (ntype
== if_stmt
)
1502 || (ntype
== while_stmt
)
1503 || (ntype
== for_stmt
)
1504 || (ntype
== try_stmt
)
1505 || (ntype
== funcdef
)
1506 || (ntype
== classdef
))
1507 res
= validate_node(tree
);
1510 PyErr_Format(parser_error
,
1511 "Illegal compound statement type: %d.", TYPE(tree
));
1518 validate_yield_or_testlist(node
*tree
)
1520 if (TYPE(tree
) == yield_expr
)
1521 return validate_yield_expr(tree
);
1523 return validate_testlist(tree
);
1527 validate_expr_stmt(node
*tree
)
1530 int nch
= NCH(tree
);
1531 int res
= (validate_ntype(tree
, expr_stmt
)
1533 && validate_testlist(CHILD(tree
, 0)));
1536 && TYPE(CHILD(tree
, 1)) == augassign
) {
1537 res
= validate_numnodes(CHILD(tree
, 1), 1, "augassign")
1538 && validate_yield_or_testlist(CHILD(tree
, 2));
1541 char *s
= STR(CHILD(CHILD(tree
, 1), 0));
1543 res
= (strcmp(s
, "+=") == 0
1544 || strcmp(s
, "-=") == 0
1545 || strcmp(s
, "*=") == 0
1546 || strcmp(s
, "/=") == 0
1547 || strcmp(s
, "//=") == 0
1548 || strcmp(s
, "%=") == 0
1549 || strcmp(s
, "&=") == 0
1550 || strcmp(s
, "|=") == 0
1551 || strcmp(s
, "^=") == 0
1552 || strcmp(s
, "<<=") == 0
1553 || strcmp(s
, ">>=") == 0
1554 || strcmp(s
, "**=") == 0);
1556 err_string("illegal augmmented assignment operator");
1560 for (j
= 1; res
&& (j
< nch
); j
+= 2)
1561 res
= validate_equal(CHILD(tree
, j
))
1562 && validate_yield_or_testlist(CHILD(tree
, j
+ 1));
1570 * 'print' ( [ test (',' test)* [','] ]
1571 * | '>>' test [ (',' test)+ [','] ] )
1574 validate_print_stmt(node
*tree
)
1576 int nch
= NCH(tree
);
1577 int res
= (validate_ntype(tree
, print_stmt
)
1579 && validate_name(CHILD(tree
, 0), "print"));
1581 if (res
&& nch
> 1) {
1582 int sym
= TYPE(CHILD(tree
, 1));
1584 int allow_trailing_comma
= 1;
1587 res
= validate_test(CHILD(tree
, i
++));
1590 res
= validate_numnodes(tree
, 3, "print_stmt");
1592 res
= (validate_ntype(CHILD(tree
, i
), RIGHTSHIFT
)
1593 && validate_test(CHILD(tree
, i
+1)));
1595 allow_trailing_comma
= 0;
1599 /* ... (',' test)* [','] */
1600 while (res
&& i
+2 <= nch
) {
1601 res
= (validate_comma(CHILD(tree
, i
))
1602 && validate_test(CHILD(tree
, i
+1)));
1603 allow_trailing_comma
= 1;
1606 if (res
&& !allow_trailing_comma
)
1607 res
= validate_numnodes(tree
, i
, "print_stmt");
1608 else if (res
&& i
< nch
)
1609 res
= validate_comma(CHILD(tree
, i
));
1617 validate_del_stmt(node
*tree
)
1619 return (validate_numnodes(tree
, 2, "del_stmt")
1620 && validate_name(CHILD(tree
, 0), "del")
1621 && validate_exprlist(CHILD(tree
, 1)));
1626 validate_return_stmt(node
*tree
)
1628 int nch
= NCH(tree
);
1629 int res
= (validate_ntype(tree
, return_stmt
)
1630 && ((nch
== 1) || (nch
== 2))
1631 && validate_name(CHILD(tree
, 0), "return"));
1633 if (res
&& (nch
== 2))
1634 res
= validate_testlist(CHILD(tree
, 1));
1641 validate_raise_stmt(node
*tree
)
1643 int nch
= NCH(tree
);
1644 int res
= (validate_ntype(tree
, raise_stmt
)
1645 && ((nch
== 1) || (nch
== 2) || (nch
== 4) || (nch
== 6)));
1648 res
= validate_name(CHILD(tree
, 0), "raise");
1649 if (res
&& (nch
>= 2))
1650 res
= validate_test(CHILD(tree
, 1));
1651 if (res
&& nch
> 2) {
1652 res
= (validate_comma(CHILD(tree
, 2))
1653 && validate_test(CHILD(tree
, 3)));
1654 if (res
&& (nch
> 4))
1655 res
= (validate_comma(CHILD(tree
, 4))
1656 && validate_test(CHILD(tree
, 5)));
1660 (void) validate_numnodes(tree
, 2, "raise");
1661 if (res
&& (nch
== 4))
1662 res
= (validate_comma(CHILD(tree
, 2))
1663 && validate_test(CHILD(tree
, 3)));
1669 /* yield_expr: 'yield' [testlist]
1672 validate_yield_expr(node
*tree
)
1674 int nch
= NCH(tree
);
1675 int res
= (validate_ntype(tree
, yield_expr
)
1676 && ((nch
== 1) || (nch
== 2))
1677 && validate_name(CHILD(tree
, 0), "yield"));
1679 if (res
&& (nch
== 2))
1680 res
= validate_testlist(CHILD(tree
, 1));
1686 /* yield_stmt: yield_expr
1689 validate_yield_stmt(node
*tree
)
1691 return (validate_ntype(tree
, yield_stmt
)
1692 && validate_numnodes(tree
, 1, "yield_stmt")
1693 && validate_yield_expr(CHILD(tree
, 0)));
1698 validate_import_as_name(node
*tree
)
1700 int nch
= NCH(tree
);
1701 int ok
= validate_ntype(tree
, import_as_name
);
1705 ok
= validate_name(CHILD(tree
, 0), NULL
);
1707 ok
= (validate_name(CHILD(tree
, 0), NULL
)
1708 && validate_name(CHILD(tree
, 1), "as")
1709 && validate_name(CHILD(tree
, 2), NULL
));
1711 ok
= validate_numnodes(tree
, 3, "import_as_name");
1717 /* dotted_name: NAME ("." NAME)*
1720 validate_dotted_name(node
*tree
)
1722 int nch
= NCH(tree
);
1723 int res
= (validate_ntype(tree
, dotted_name
)
1725 && validate_name(CHILD(tree
, 0), NULL
));
1728 for (i
= 1; res
&& (i
< nch
); i
+= 2) {
1729 res
= (validate_dot(CHILD(tree
, i
))
1730 && validate_name(CHILD(tree
, i
+1), NULL
));
1736 /* dotted_as_name: dotted_name [NAME NAME]
1739 validate_dotted_as_name(node
*tree
)
1741 int nch
= NCH(tree
);
1742 int res
= validate_ntype(tree
, dotted_as_name
);
1746 res
= validate_dotted_name(CHILD(tree
, 0));
1748 res
= (validate_dotted_name(CHILD(tree
, 0))
1749 && validate_name(CHILD(tree
, 1), "as")
1750 && validate_name(CHILD(tree
, 2), NULL
));
1753 err_string("illegal number of children for dotted_as_name");
1760 /* dotted_as_name (',' dotted_as_name)* */
1762 validate_dotted_as_names(node
*tree
)
1764 int nch
= NCH(tree
);
1765 int res
= is_odd(nch
) && validate_dotted_as_name(CHILD(tree
, 0));
1768 for (i
= 1; res
&& (i
< nch
); i
+= 2)
1769 res
= (validate_comma(CHILD(tree
, i
))
1770 && validate_dotted_as_name(CHILD(tree
, i
+ 1)));
1775 /* import_as_name (',' import_as_name)* [','] */
1777 validate_import_as_names(node
*tree
)
1779 int nch
= NCH(tree
);
1780 int res
= validate_import_as_name(CHILD(tree
, 0));
1783 for (i
= 1; res
&& (i
+ 1 < nch
); i
+= 2)
1784 res
= (validate_comma(CHILD(tree
, i
))
1785 && validate_import_as_name(CHILD(tree
, i
+ 1)));
1790 /* 'import' dotted_as_names */
1792 validate_import_name(node
*tree
)
1794 return (validate_ntype(tree
, import_name
)
1795 && validate_numnodes(tree
, 2, "import_name")
1796 && validate_name(CHILD(tree
, 0), "import")
1797 && validate_dotted_as_names(CHILD(tree
, 1)));
1800 /* Helper function to count the number of leading dots in
1801 * 'from ...module import name'
1804 count_from_dots(node
*tree
)
1807 for (i
= 0; i
< NCH(tree
); i
++)
1808 if (TYPE(CHILD(tree
, i
)) != DOT
)
1813 /* 'from' ('.'* dotted_name | '.') 'import' ('*' | '(' import_as_names ')' |
1817 validate_import_from(node
*tree
)
1819 int nch
= NCH(tree
);
1820 int ndots
= count_from_dots(tree
);
1821 int havename
= (TYPE(CHILD(tree
, ndots
+ 1)) == dotted_name
);
1822 int offset
= ndots
+ havename
;
1823 int res
= validate_ntype(tree
, import_from
)
1824 && (nch
>= 4 + ndots
)
1825 && validate_name(CHILD(tree
, 0), "from")
1826 && (!havename
|| validate_dotted_name(CHILD(tree
, ndots
+ 1)))
1827 && validate_name(CHILD(tree
, offset
+ 1), "import");
1829 if (res
&& TYPE(CHILD(tree
, offset
+ 2)) == LPAR
)
1830 res
= ((nch
== offset
+ 5)
1831 && validate_lparen(CHILD(tree
, offset
+ 2))
1832 && validate_import_as_names(CHILD(tree
, offset
+ 3))
1833 && validate_rparen(CHILD(tree
, offset
+ 4)));
1834 else if (res
&& TYPE(CHILD(tree
, offset
+ 2)) != STAR
)
1835 res
= validate_import_as_names(CHILD(tree
, offset
+ 2));
1840 /* import_stmt: import_name | import_from */
1842 validate_import_stmt(node
*tree
)
1844 int nch
= NCH(tree
);
1845 int res
= validate_numnodes(tree
, 1, "import_stmt");
1848 int ntype
= TYPE(CHILD(tree
, 0));
1850 if (ntype
== import_name
|| ntype
== import_from
)
1851 res
= validate_node(CHILD(tree
, 0));
1854 err_string("illegal import_stmt child type");
1857 else if (nch
== 1) {
1859 PyErr_Format(parser_error
,
1860 "Unrecognized child node of import_stmt: %d.",
1861 TYPE(CHILD(tree
, 0)));
1870 validate_global_stmt(node
*tree
)
1873 int nch
= NCH(tree
);
1874 int res
= (validate_ntype(tree
, global_stmt
)
1875 && is_even(nch
) && (nch
>= 2));
1877 if (!res
&& !PyErr_Occurred())
1878 err_string("illegal global statement");
1881 res
= (validate_name(CHILD(tree
, 0), "global")
1882 && validate_ntype(CHILD(tree
, 1), NAME
));
1883 for (j
= 2; res
&& (j
< nch
); j
+= 2)
1884 res
= (validate_comma(CHILD(tree
, j
))
1885 && validate_ntype(CHILD(tree
, j
+ 1), NAME
));
1893 * 'exec' expr ['in' test [',' test]]
1896 validate_exec_stmt(node
*tree
)
1898 int nch
= NCH(tree
);
1899 int res
= (validate_ntype(tree
, exec_stmt
)
1900 && ((nch
== 2) || (nch
== 4) || (nch
== 6))
1901 && validate_name(CHILD(tree
, 0), "exec")
1902 && validate_expr(CHILD(tree
, 1)));
1904 if (!res
&& !PyErr_Occurred())
1905 err_string("illegal exec statement");
1906 if (res
&& (nch
> 2))
1907 res
= (validate_name(CHILD(tree
, 2), "in")
1908 && validate_test(CHILD(tree
, 3)));
1909 if (res
&& (nch
== 6))
1910 res
= (validate_comma(CHILD(tree
, 4))
1911 && validate_test(CHILD(tree
, 5)));
1919 * 'assert' test [',' test]
1922 validate_assert_stmt(node
*tree
)
1924 int nch
= NCH(tree
);
1925 int res
= (validate_ntype(tree
, assert_stmt
)
1926 && ((nch
== 2) || (nch
== 4))
1927 && (validate_name(CHILD(tree
, 0), "assert"))
1928 && validate_test(CHILD(tree
, 1)));
1930 if (!res
&& !PyErr_Occurred())
1931 err_string("illegal assert statement");
1932 if (res
&& (nch
> 2))
1933 res
= (validate_comma(CHILD(tree
, 2))
1934 && validate_test(CHILD(tree
, 3)));
1941 validate_while(node
*tree
)
1943 int nch
= NCH(tree
);
1944 int res
= (validate_ntype(tree
, while_stmt
)
1945 && ((nch
== 4) || (nch
== 7))
1946 && validate_name(CHILD(tree
, 0), "while")
1947 && validate_test(CHILD(tree
, 1))
1948 && validate_colon(CHILD(tree
, 2))
1949 && validate_suite(CHILD(tree
, 3)));
1951 if (res
&& (nch
== 7))
1952 res
= (validate_name(CHILD(tree
, 4), "else")
1953 && validate_colon(CHILD(tree
, 5))
1954 && validate_suite(CHILD(tree
, 6)));
1961 validate_for(node
*tree
)
1963 int nch
= NCH(tree
);
1964 int res
= (validate_ntype(tree
, for_stmt
)
1965 && ((nch
== 6) || (nch
== 9))
1966 && validate_name(CHILD(tree
, 0), "for")
1967 && validate_exprlist(CHILD(tree
, 1))
1968 && validate_name(CHILD(tree
, 2), "in")
1969 && validate_testlist(CHILD(tree
, 3))
1970 && validate_colon(CHILD(tree
, 4))
1971 && validate_suite(CHILD(tree
, 5)));
1973 if (res
&& (nch
== 9))
1974 res
= (validate_name(CHILD(tree
, 6), "else")
1975 && validate_colon(CHILD(tree
, 7))
1976 && validate_suite(CHILD(tree
, 8)));
1983 * 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
1984 * | 'try' ':' suite 'finally' ':' suite
1988 validate_try(node
*tree
)
1990 int nch
= NCH(tree
);
1992 int res
= (validate_ntype(tree
, try_stmt
)
1993 && (nch
>= 6) && ((nch
% 3) == 0));
1996 res
= (validate_name(CHILD(tree
, 0), "try")
1997 && validate_colon(CHILD(tree
, 1))
1998 && validate_suite(CHILD(tree
, 2))
1999 && validate_colon(CHILD(tree
, nch
- 2))
2000 && validate_suite(CHILD(tree
, nch
- 1)));
2001 else if (!PyErr_Occurred()) {
2002 const char* name
= "except";
2003 if (TYPE(CHILD(tree
, nch
- 3)) != except_clause
)
2004 name
= STR(CHILD(tree
, nch
- 3));
2006 PyErr_Format(parser_error
,
2007 "Illegal number of children for try/%s node.", name
);
2009 /* Skip past except_clause sections: */
2010 while (res
&& (TYPE(CHILD(tree
, pos
)) == except_clause
)) {
2011 res
= (validate_except_clause(CHILD(tree
, pos
))
2012 && validate_colon(CHILD(tree
, pos
+ 1))
2013 && validate_suite(CHILD(tree
, pos
+ 2)));
2016 if (res
&& (pos
< nch
)) {
2017 res
= validate_ntype(CHILD(tree
, pos
), NAME
);
2018 if (res
&& (strcmp(STR(CHILD(tree
, pos
)), "finally") == 0))
2019 res
= (validate_numnodes(tree
, 6, "try/finally")
2020 && validate_colon(CHILD(tree
, 4))
2021 && validate_suite(CHILD(tree
, 5)));
2023 if (nch
== (pos
+ 3)) {
2024 res
= ((strcmp(STR(CHILD(tree
, pos
)), "except") == 0)
2025 || (strcmp(STR(CHILD(tree
, pos
)), "else") == 0));
2027 err_string("illegal trailing triple in try statement");
2029 else if (nch
== (pos
+ 6)) {
2030 res
= (validate_name(CHILD(tree
, pos
), "except")
2031 && validate_colon(CHILD(tree
, pos
+ 1))
2032 && validate_suite(CHILD(tree
, pos
+ 2))
2033 && validate_name(CHILD(tree
, pos
+ 3), "else"));
2036 res
= validate_numnodes(tree
, pos
+ 3, "try/except");
2044 validate_except_clause(node
*tree
)
2046 int nch
= NCH(tree
);
2047 int res
= (validate_ntype(tree
, except_clause
)
2048 && ((nch
== 1) || (nch
== 2) || (nch
== 4))
2049 && validate_name(CHILD(tree
, 0), "except"));
2051 if (res
&& (nch
> 1))
2052 res
= validate_test(CHILD(tree
, 1));
2053 if (res
&& (nch
== 4))
2054 res
= (validate_comma(CHILD(tree
, 2))
2055 && validate_test(CHILD(tree
, 3)));
2062 validate_test(node
*tree
)
2064 int nch
= NCH(tree
);
2065 int res
= validate_ntype(tree
, test
) && is_odd(nch
);
2067 if (res
&& (TYPE(CHILD(tree
, 0)) == lambdef
))
2069 && validate_lambdef(CHILD(tree
, 0)));
2071 res
= validate_or_test(CHILD(tree
, 0));
2072 res
= (res
&& (nch
== 1 || (nch
== 5 &&
2073 validate_name(CHILD(tree
, 1), "if") &&
2074 validate_or_test(CHILD(tree
, 2)) &&
2075 validate_name(CHILD(tree
, 3), "else") &&
2076 validate_test(CHILD(tree
, 4)))));
2082 validate_old_test(node
*tree
)
2084 int nch
= NCH(tree
);
2085 int res
= validate_ntype(tree
, old_test
) && (nch
== 1);
2087 if (res
&& (TYPE(CHILD(tree
, 0)) == old_lambdef
))
2088 res
= (validate_old_lambdef(CHILD(tree
, 0)));
2090 res
= (validate_or_test(CHILD(tree
, 0)));
2096 validate_or_test(node
*tree
)
2098 int nch
= NCH(tree
);
2099 int res
= validate_ntype(tree
, or_test
) && is_odd(nch
);
2103 res
= validate_and_test(CHILD(tree
, 0));
2104 for (pos
= 1; res
&& (pos
< nch
); pos
+= 2)
2105 res
= (validate_name(CHILD(tree
, pos
), "or")
2106 && validate_and_test(CHILD(tree
, pos
+ 1)));
2113 validate_and_test(node
*tree
)
2116 int nch
= NCH(tree
);
2117 int res
= (validate_ntype(tree
, and_test
)
2119 && validate_not_test(CHILD(tree
, 0)));
2121 for (pos
= 1; res
&& (pos
< nch
); pos
+= 2)
2122 res
= (validate_name(CHILD(tree
, pos
), "and")
2123 && validate_not_test(CHILD(tree
, 0)));
2130 validate_not_test(node
*tree
)
2132 int nch
= NCH(tree
);
2133 int res
= validate_ntype(tree
, not_test
) && ((nch
== 1) || (nch
== 2));
2137 res
= (validate_name(CHILD(tree
, 0), "not")
2138 && validate_not_test(CHILD(tree
, 1)));
2140 res
= validate_comparison(CHILD(tree
, 0));
2147 validate_comparison(node
*tree
)
2150 int nch
= NCH(tree
);
2151 int res
= (validate_ntype(tree
, comparison
)
2153 && validate_expr(CHILD(tree
, 0)));
2155 for (pos
= 1; res
&& (pos
< nch
); pos
+= 2)
2156 res
= (validate_comp_op(CHILD(tree
, pos
))
2157 && validate_expr(CHILD(tree
, pos
+ 1)));
2164 validate_comp_op(node
*tree
)
2167 int nch
= NCH(tree
);
2169 if (!validate_ntype(tree
, comp_op
))
2173 * Only child will be a terminal with a well-defined symbolic name
2174 * or a NAME with a string of either 'is' or 'in'
2176 tree
= CHILD(tree
, 0);
2177 switch (TYPE(tree
)) {
2188 res
= ((strcmp(STR(tree
), "in") == 0)
2189 || (strcmp(STR(tree
), "is") == 0));
2191 PyErr_Format(parser_error
,
2192 "illegal operator '%s'", STR(tree
));
2196 err_string("illegal comparison operator type");
2200 else if ((res
= validate_numnodes(tree
, 2, "comp_op")) != 0) {
2201 res
= (validate_ntype(CHILD(tree
, 0), NAME
)
2202 && validate_ntype(CHILD(tree
, 1), NAME
)
2203 && (((strcmp(STR(CHILD(tree
, 0)), "is") == 0)
2204 && (strcmp(STR(CHILD(tree
, 1)), "not") == 0))
2205 || ((strcmp(STR(CHILD(tree
, 0)), "not") == 0)
2206 && (strcmp(STR(CHILD(tree
, 1)), "in") == 0))));
2207 if (!res
&& !PyErr_Occurred())
2208 err_string("unknown comparison operator");
2215 validate_expr(node
*tree
)
2218 int nch
= NCH(tree
);
2219 int res
= (validate_ntype(tree
, expr
)
2221 && validate_xor_expr(CHILD(tree
, 0)));
2223 for (j
= 2; res
&& (j
< nch
); j
+= 2)
2224 res
= (validate_xor_expr(CHILD(tree
, j
))
2225 && validate_vbar(CHILD(tree
, j
- 1)));
2232 validate_xor_expr(node
*tree
)
2235 int nch
= NCH(tree
);
2236 int res
= (validate_ntype(tree
, xor_expr
)
2238 && validate_and_expr(CHILD(tree
, 0)));
2240 for (j
= 2; res
&& (j
< nch
); j
+= 2)
2241 res
= (validate_circumflex(CHILD(tree
, j
- 1))
2242 && validate_and_expr(CHILD(tree
, j
)));
2249 validate_and_expr(node
*tree
)
2252 int nch
= NCH(tree
);
2253 int res
= (validate_ntype(tree
, and_expr
)
2255 && validate_shift_expr(CHILD(tree
, 0)));
2257 for (pos
= 1; res
&& (pos
< nch
); pos
+= 2)
2258 res
= (validate_ampersand(CHILD(tree
, pos
))
2259 && validate_shift_expr(CHILD(tree
, pos
+ 1)));
2266 validate_chain_two_ops(node
*tree
, int (*termvalid
)(node
*), int op1
, int op2
)
2269 int nch
= NCH(tree
);
2270 int res
= (is_odd(nch
)
2271 && (*termvalid
)(CHILD(tree
, 0)));
2273 for ( ; res
&& (pos
< nch
); pos
+= 2) {
2274 if (TYPE(CHILD(tree
, pos
)) != op1
)
2275 res
= validate_ntype(CHILD(tree
, pos
), op2
);
2277 res
= (*termvalid
)(CHILD(tree
, pos
+ 1));
2284 validate_shift_expr(node
*tree
)
2286 return (validate_ntype(tree
, shift_expr
)
2287 && validate_chain_two_ops(tree
, validate_arith_expr
,
2288 LEFTSHIFT
, RIGHTSHIFT
));
2293 validate_arith_expr(node
*tree
)
2295 return (validate_ntype(tree
, arith_expr
)
2296 && validate_chain_two_ops(tree
, validate_term
, PLUS
, MINUS
));
2301 validate_term(node
*tree
)
2304 int nch
= NCH(tree
);
2305 int res
= (validate_ntype(tree
, term
)
2307 && validate_factor(CHILD(tree
, 0)));
2309 for ( ; res
&& (pos
< nch
); pos
+= 2)
2310 res
= (((TYPE(CHILD(tree
, pos
)) == STAR
)
2311 || (TYPE(CHILD(tree
, pos
)) == SLASH
)
2312 || (TYPE(CHILD(tree
, pos
)) == DOUBLESLASH
)
2313 || (TYPE(CHILD(tree
, pos
)) == PERCENT
))
2314 && validate_factor(CHILD(tree
, pos
+ 1)));
2322 * factor: ('+'|'-'|'~') factor | power
2325 validate_factor(node
*tree
)
2327 int nch
= NCH(tree
);
2328 int res
= (validate_ntype(tree
, factor
)
2330 && ((TYPE(CHILD(tree
, 0)) == PLUS
)
2331 || (TYPE(CHILD(tree
, 0)) == MINUS
)
2332 || (TYPE(CHILD(tree
, 0)) == TILDE
))
2333 && validate_factor(CHILD(tree
, 1)))
2335 && validate_power(CHILD(tree
, 0)))));
2342 * power: atom trailer* ('**' factor)*
2345 validate_power(node
*tree
)
2348 int nch
= NCH(tree
);
2349 int res
= (validate_ntype(tree
, power
) && (nch
>= 1)
2350 && validate_atom(CHILD(tree
, 0)));
2352 while (res
&& (pos
< nch
) && (TYPE(CHILD(tree
, pos
)) == trailer
))
2353 res
= validate_trailer(CHILD(tree
, pos
++));
2354 if (res
&& (pos
< nch
)) {
2355 if (!is_even(nch
- pos
)) {
2356 err_string("illegal number of nodes for 'power'");
2359 for ( ; res
&& (pos
< (nch
- 1)); pos
+= 2)
2360 res
= (validate_doublestar(CHILD(tree
, pos
))
2361 && validate_factor(CHILD(tree
, pos
+ 1)));
2368 validate_atom(node
*tree
)
2371 int nch
= NCH(tree
);
2372 int res
= validate_ntype(tree
, atom
);
2375 res
= validate_numnodes(tree
, nch
+1, "atom");
2377 switch (TYPE(CHILD(tree
, 0))) {
2380 && (validate_rparen(CHILD(tree
, nch
- 1))));
2382 if (res
&& (nch
== 3)) {
2383 if (TYPE(CHILD(tree
, 1))==yield_expr
)
2384 res
= validate_yield_expr(CHILD(tree
, 1));
2386 res
= validate_testlist_gexp(CHILD(tree
, 1));
2391 res
= validate_ntype(CHILD(tree
, 1), RSQB
);
2393 res
= (validate_listmaker(CHILD(tree
, 1))
2394 && validate_ntype(CHILD(tree
, 2), RSQB
));
2397 err_string("illegal list display atom");
2402 && validate_ntype(CHILD(tree
, nch
- 1), RBRACE
));
2404 if (res
&& (nch
== 3))
2405 res
= validate_dictmaker(CHILD(tree
, 1));
2409 && validate_testlist1(CHILD(tree
, 1))
2410 && validate_ntype(CHILD(tree
, 2), BACKQUOTE
));
2417 for (pos
= 1; res
&& (pos
< nch
); ++pos
)
2418 res
= validate_ntype(CHILD(tree
, pos
), STRING
);
2430 * test ( list_for | (',' test)* [','] )
2433 validate_listmaker(node
*tree
)
2435 int nch
= NCH(tree
);
2439 err_string("missing child nodes of listmaker");
2441 ok
= validate_test(CHILD(tree
, 0));
2444 * list_for | (',' test)* [',']
2446 if (nch
== 2 && TYPE(CHILD(tree
, 1)) == list_for
)
2447 ok
= validate_list_for(CHILD(tree
, 1));
2449 /* (',' test)* [','] */
2451 while (ok
&& nch
- i
>= 2) {
2452 ok
= (validate_comma(CHILD(tree
, i
))
2453 && validate_test(CHILD(tree
, i
+1)));
2456 if (ok
&& i
== nch
-1)
2457 ok
= validate_comma(CHILD(tree
, i
));
2458 else if (i
!= nch
) {
2460 err_string("illegal trailing nodes for listmaker");
2467 * test ( gen_for | (',' test)* [','] )
2470 validate_testlist_gexp(node
*tree
)
2472 int nch
= NCH(tree
);
2476 err_string("missing child nodes of testlist_gexp");
2478 ok
= validate_test(CHILD(tree
, 0));
2482 * gen_for | (',' test)* [',']
2484 if (nch
== 2 && TYPE(CHILD(tree
, 1)) == gen_for
)
2485 ok
= validate_gen_for(CHILD(tree
, 1));
2487 /* (',' test)* [','] */
2489 while (ok
&& nch
- i
>= 2) {
2490 ok
= (validate_comma(CHILD(tree
, i
))
2491 && validate_test(CHILD(tree
, i
+1)));
2494 if (ok
&& i
== nch
-1)
2495 ok
= validate_comma(CHILD(tree
, i
));
2496 else if (i
!= nch
) {
2498 err_string("illegal trailing nodes for testlist_gexp");
2505 * '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
2508 validate_decorator(node
*tree
)
2511 int nch
= NCH(tree
);
2512 ok
= (validate_ntype(tree
, decorator
) &&
2513 (nch
== 3 || nch
== 5 || nch
== 6) &&
2514 validate_at(CHILD(tree
, 0)) &&
2515 validate_dotted_name(CHILD(tree
, 1)) &&
2516 validate_newline(RCHILD(tree
, -1)));
2518 if (ok
&& nch
!= 3) {
2519 ok
= (validate_lparen(CHILD(tree
, 2)) &&
2520 validate_rparen(RCHILD(tree
, -2)));
2523 ok
= validate_arglist(CHILD(tree
, 3));
2533 validate_decorators(node
*tree
)
2537 ok
= validate_ntype(tree
, decorators
) && nch
>= 1;
2539 for (i
= 0; ok
&& i
< nch
; ++i
)
2540 ok
= validate_decorator(CHILD(tree
, i
));
2548 * [decorators] 'def' NAME parameters ':' suite
2551 validate_funcdef(node
*tree
)
2553 int nch
= NCH(tree
);
2554 int ok
= (validate_ntype(tree
, funcdef
)
2555 && ((nch
== 5) || (nch
== 6))
2556 && validate_name(RCHILD(tree
, -5), "def")
2557 && validate_ntype(RCHILD(tree
, -4), NAME
)
2558 && validate_colon(RCHILD(tree
, -2))
2559 && validate_parameters(RCHILD(tree
, -3))
2560 && validate_suite(RCHILD(tree
, -1)));
2562 if (ok
&& (nch
== 6))
2563 ok
= validate_decorators(CHILD(tree
, 0));
2570 validate_lambdef(node
*tree
)
2572 int nch
= NCH(tree
);
2573 int res
= (validate_ntype(tree
, lambdef
)
2574 && ((nch
== 3) || (nch
== 4))
2575 && validate_name(CHILD(tree
, 0), "lambda")
2576 && validate_colon(CHILD(tree
, nch
- 2))
2577 && validate_test(CHILD(tree
, nch
- 1)));
2579 if (res
&& (nch
== 4))
2580 res
= validate_varargslist(CHILD(tree
, 1));
2581 else if (!res
&& !PyErr_Occurred())
2582 (void) validate_numnodes(tree
, 3, "lambdef");
2589 validate_old_lambdef(node
*tree
)
2591 int nch
= NCH(tree
);
2592 int res
= (validate_ntype(tree
, old_lambdef
)
2593 && ((nch
== 3) || (nch
== 4))
2594 && validate_name(CHILD(tree
, 0), "lambda")
2595 && validate_colon(CHILD(tree
, nch
- 2))
2596 && validate_test(CHILD(tree
, nch
- 1)));
2598 if (res
&& (nch
== 4))
2599 res
= validate_varargslist(CHILD(tree
, 1));
2600 else if (!res
&& !PyErr_Occurred())
2601 (void) validate_numnodes(tree
, 3, "old_lambdef");
2609 * (argument ',')* (argument [','] | '*' test [',' '**' test] | '**' test)
2612 validate_arglist(node
*tree
)
2614 int nch
= NCH(tree
);
2619 /* raise the right error from having an invalid number of children */
2620 return validate_numnodes(tree
, nch
+ 1, "arglist");
2623 for (i
=0; i
<nch
; i
++) {
2624 if (TYPE(CHILD(tree
, i
)) == argument
) {
2625 node
*ch
= CHILD(tree
, i
);
2626 if (NCH(ch
) == 2 && TYPE(CHILD(ch
, 1)) == gen_for
) {
2627 err_string("need '(', ')' for generator expression");
2634 while (ok
&& nch
-i
>= 2) {
2635 /* skip leading (argument ',') */
2636 ok
= (validate_argument(CHILD(tree
, i
))
2637 && validate_comma(CHILD(tree
, i
+1)));
2646 * argument | '*' test [',' '**' test] | '**' test
2648 int sym
= TYPE(CHILD(tree
, i
));
2650 if (sym
== argument
) {
2651 ok
= validate_argument(CHILD(tree
, i
));
2652 if (ok
&& i
+1 != nch
) {
2653 err_string("illegal arglist specification"
2654 " (extra stuff on end)");
2658 else if (sym
== STAR
) {
2659 ok
= validate_star(CHILD(tree
, i
));
2660 if (ok
&& (nch
-i
== 2))
2661 ok
= validate_test(CHILD(tree
, i
+1));
2662 else if (ok
&& (nch
-i
== 5))
2663 ok
= (validate_test(CHILD(tree
, i
+1))
2664 && validate_comma(CHILD(tree
, i
+2))
2665 && validate_doublestar(CHILD(tree
, i
+3))
2666 && validate_test(CHILD(tree
, i
+4)));
2668 err_string("illegal use of '*' in arglist");
2672 else if (sym
== DOUBLESTAR
) {
2674 ok
= (validate_doublestar(CHILD(tree
, i
))
2675 && validate_test(CHILD(tree
, i
+1)));
2677 err_string("illegal use of '**' in arglist");
2682 err_string("illegal arglist specification");
2693 * [test '='] test [gen_for]
2696 validate_argument(node
*tree
)
2698 int nch
= NCH(tree
);
2699 int res
= (validate_ntype(tree
, argument
)
2700 && ((nch
== 1) || (nch
== 2) || (nch
== 3))
2701 && validate_test(CHILD(tree
, 0)));
2703 if (res
&& (nch
== 2))
2704 res
= validate_gen_for(CHILD(tree
, 1));
2705 else if (res
&& (nch
== 3))
2706 res
= (validate_equal(CHILD(tree
, 1))
2707 && validate_test(CHILD(tree
, 2)));
2716 * '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
2719 validate_trailer(node
*tree
)
2721 int nch
= NCH(tree
);
2722 int res
= validate_ntype(tree
, trailer
) && ((nch
== 2) || (nch
== 3));
2725 switch (TYPE(CHILD(tree
, 0))) {
2727 res
= validate_rparen(CHILD(tree
, nch
- 1));
2728 if (res
&& (nch
== 3))
2729 res
= validate_arglist(CHILD(tree
, 1));
2732 res
= (validate_numnodes(tree
, 3, "trailer")
2733 && validate_subscriptlist(CHILD(tree
, 1))
2734 && validate_ntype(CHILD(tree
, 2), RSQB
));
2737 res
= (validate_numnodes(tree
, 2, "trailer")
2738 && validate_ntype(CHILD(tree
, 1), NAME
));
2746 (void) validate_numnodes(tree
, 2, "trailer");
2754 * subscript (',' subscript)* [',']
2757 validate_subscriptlist(node
*tree
)
2759 return (validate_repeating_list(tree
, subscriptlist
,
2760 validate_subscript
, "subscriptlist"));
2766 * '.' '.' '.' | test | [test] ':' [test] [sliceop]
2769 validate_subscript(node
*tree
)
2772 int nch
= NCH(tree
);
2773 int res
= validate_ntype(tree
, subscript
) && (nch
>= 1) && (nch
<= 4);
2776 if (!PyErr_Occurred())
2777 err_string("invalid number of arguments for subscript node");
2780 if (TYPE(CHILD(tree
, 0)) == DOT
)
2781 /* take care of ('.' '.' '.') possibility */
2782 return (validate_numnodes(tree
, 3, "subscript")
2783 && validate_dot(CHILD(tree
, 0))
2784 && validate_dot(CHILD(tree
, 1))
2785 && validate_dot(CHILD(tree
, 2)));
2787 if (TYPE(CHILD(tree
, 0)) == test
)
2788 res
= validate_test(CHILD(tree
, 0));
2790 res
= validate_colon(CHILD(tree
, 0));
2793 /* Must be [test] ':' [test] [sliceop],
2794 * but at least one of the optional components will
2795 * be present, but we don't know which yet.
2797 if ((TYPE(CHILD(tree
, 0)) != COLON
) || (nch
== 4)) {
2798 res
= validate_test(CHILD(tree
, 0));
2802 res
= validate_colon(CHILD(tree
, offset
));
2804 int rem
= nch
- ++offset
;
2806 if (TYPE(CHILD(tree
, offset
)) == test
) {
2807 res
= validate_test(CHILD(tree
, offset
));
2812 res
= validate_sliceop(CHILD(tree
, offset
));
2820 validate_sliceop(node
*tree
)
2822 int nch
= NCH(tree
);
2823 int res
= ((nch
== 1) || validate_numnodes(tree
, 2, "sliceop"))
2824 && validate_ntype(tree
, sliceop
);
2825 if (!res
&& !PyErr_Occurred()) {
2826 res
= validate_numnodes(tree
, 1, "sliceop");
2829 res
= validate_colon(CHILD(tree
, 0));
2830 if (res
&& (nch
== 2))
2831 res
= validate_test(CHILD(tree
, 1));
2838 validate_exprlist(node
*tree
)
2840 return (validate_repeating_list(tree
, exprlist
,
2841 validate_expr
, "exprlist"));
2846 validate_dictmaker(node
*tree
)
2848 int nch
= NCH(tree
);
2849 int res
= (validate_ntype(tree
, dictmaker
)
2851 && validate_test(CHILD(tree
, 0))
2852 && validate_colon(CHILD(tree
, 1))
2853 && validate_test(CHILD(tree
, 2)));
2855 if (res
&& ((nch
% 4) == 0))
2856 res
= validate_comma(CHILD(tree
, --nch
));
2858 res
= ((nch
% 4) == 3);
2860 if (res
&& (nch
> 3)) {
2862 /* ( ',' test ':' test )* */
2863 while (res
&& (pos
< nch
)) {
2864 res
= (validate_comma(CHILD(tree
, pos
))
2865 && validate_test(CHILD(tree
, pos
+ 1))
2866 && validate_colon(CHILD(tree
, pos
+ 2))
2867 && validate_test(CHILD(tree
, pos
+ 3)));
2876 validate_eval_input(node
*tree
)
2879 int nch
= NCH(tree
);
2880 int res
= (validate_ntype(tree
, eval_input
)
2882 && validate_testlist(CHILD(tree
, 0))
2883 && validate_ntype(CHILD(tree
, nch
- 1), ENDMARKER
));
2885 for (pos
= 1; res
&& (pos
< (nch
- 1)); ++pos
)
2886 res
= validate_ntype(CHILD(tree
, pos
), NEWLINE
);
2893 validate_node(node
*tree
)
2895 int nch
= 0; /* num. children on current node */
2896 int res
= 1; /* result value */
2897 node
* next
= 0; /* node to process after this one */
2899 while (res
&& (tree
!= 0)) {
2902 switch (TYPE(tree
)) {
2907 res
= validate_funcdef(tree
);
2910 res
= validate_class(tree
);
2913 * "Trivial" parse tree nodes.
2914 * (Why did I call these trivial?)
2917 res
= validate_stmt(tree
);
2921 * expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt
2922 * | import_stmt | global_stmt | exec_stmt | assert_stmt
2924 res
= validate_small_stmt(tree
);
2927 res
= (validate_numnodes(tree
, 1, "flow_stmt")
2928 && ((TYPE(CHILD(tree
, 0)) == break_stmt
)
2929 || (TYPE(CHILD(tree
, 0)) == continue_stmt
)
2930 || (TYPE(CHILD(tree
, 0)) == yield_stmt
)
2931 || (TYPE(CHILD(tree
, 0)) == return_stmt
)
2932 || (TYPE(CHILD(tree
, 0)) == raise_stmt
)));
2934 next
= CHILD(tree
, 0);
2936 err_string("illegal flow_stmt type");
2939 res
= validate_yield_stmt(tree
);
2942 * Compound statements.
2945 res
= validate_simple_stmt(tree
);
2948 res
= validate_compound_stmt(tree
);
2951 * Fundamental statements.
2954 res
= validate_expr_stmt(tree
);
2957 res
= validate_print_stmt(tree
);
2960 res
= validate_del_stmt(tree
);
2963 res
= (validate_numnodes(tree
, 1, "pass")
2964 && validate_name(CHILD(tree
, 0), "pass"));
2967 res
= (validate_numnodes(tree
, 1, "break")
2968 && validate_name(CHILD(tree
, 0), "break"));
2971 res
= (validate_numnodes(tree
, 1, "continue")
2972 && validate_name(CHILD(tree
, 0), "continue"));
2975 res
= validate_return_stmt(tree
);
2978 res
= validate_raise_stmt(tree
);
2981 res
= validate_import_stmt(tree
);
2984 res
= validate_import_name(tree
);
2987 res
= validate_import_from(tree
);
2990 res
= validate_global_stmt(tree
);
2993 res
= validate_exec_stmt(tree
);
2996 res
= validate_assert_stmt(tree
);
2999 res
= validate_if(tree
);
3002 res
= validate_while(tree
);
3005 res
= validate_for(tree
);
3008 res
= validate_try(tree
);
3011 res
= validate_suite(tree
);
3017 res
= validate_testlist(tree
);
3020 res
= validate_yield_expr(tree
);
3023 res
= validate_testlist1(tree
);
3026 res
= validate_test(tree
);
3029 res
= validate_and_test(tree
);
3032 res
= validate_not_test(tree
);
3035 res
= validate_comparison(tree
);
3038 res
= validate_exprlist(tree
);
3041 res
= validate_comp_op(tree
);
3044 res
= validate_expr(tree
);
3047 res
= validate_xor_expr(tree
);
3050 res
= validate_and_expr(tree
);
3053 res
= validate_shift_expr(tree
);
3056 res
= validate_arith_expr(tree
);
3059 res
= validate_term(tree
);
3062 res
= validate_factor(tree
);
3065 res
= validate_power(tree
);
3068 res
= validate_atom(tree
);
3072 /* Hopefully never reached! */
3073 err_string("unrecognized node type");
3084 validate_expr_tree(node
*tree
)
3086 int res
= validate_eval_input(tree
);
3088 if (!res
&& !PyErr_Occurred())
3089 err_string("could not validate expression tuple");
3096 * (NEWLINE | stmt)* ENDMARKER
3099 validate_file_input(node
*tree
)
3102 int nch
= NCH(tree
) - 1;
3103 int res
= ((nch
>= 0)
3104 && validate_ntype(CHILD(tree
, nch
), ENDMARKER
));
3106 for (j
= 0; res
&& (j
< nch
); ++j
) {
3107 if (TYPE(CHILD(tree
, j
)) == stmt
)
3108 res
= validate_stmt(CHILD(tree
, j
));
3110 res
= validate_newline(CHILD(tree
, j
));
3112 /* This stays in to prevent any internal failures from getting to the
3113 * user. Hopefully, this won't be needed. If a user reports getting
3114 * this, we have some debugging to do.
3116 if (!res
&& !PyErr_Occurred())
3117 err_string("VALIDATION FAILURE: report this to the maintainer!");
3123 validate_encoding_decl(node
*tree
)
3125 int nch
= NCH(tree
);
3126 int res
= ((nch
== 1)
3127 && validate_file_input(CHILD(tree
, 0)));
3129 if (!res
&& !PyErr_Occurred())
3130 err_string("Error Parsing encoding_decl");
3136 pickle_constructor
= NULL
;
3140 parser__pickler(PyObject
*self
, PyObject
*args
)
3142 NOTE(ARGUNUSED(self
))
3143 PyObject
*result
= NULL
;
3144 PyObject
*st
= NULL
;
3145 PyObject
*empty_dict
= NULL
;
3147 if (PyArg_ParseTuple(args
, "O!:_pickler", &PyST_Type
, &st
)) {
3151 if ((empty_dict
= PyDict_New()) == NULL
)
3153 if ((newargs
= Py_BuildValue("Oi", st
, 1)) == NULL
)
3155 tuple
= parser_st2tuple((PyST_Object
*)NULL
, newargs
, empty_dict
);
3156 if (tuple
!= NULL
) {
3157 result
= Py_BuildValue("O(O)", pickle_constructor
, tuple
);
3160 Py_DECREF(empty_dict
);
3164 Py_XDECREF(empty_dict
);
3170 /* Functions exported by this module. Most of this should probably
3171 * be converted into an ST object with methods, but that is better
3172 * done directly in Python, allowing subclasses to be created directly.
3173 * We'd really have to write a wrapper around it all anyway to allow
3176 static PyMethodDef parser_functions
[] = {
3177 {"ast2tuple", (PyCFunction
)parser_st2tuple
, PUBLIC_METHOD_TYPE
,
3178 PyDoc_STR("Creates a tuple-tree representation of an ST.")},
3179 {"ast2list", (PyCFunction
)parser_st2list
, PUBLIC_METHOD_TYPE
,
3180 PyDoc_STR("Creates a list-tree representation of an ST.")},
3181 {"compileast", (PyCFunction
)parser_compilest
, PUBLIC_METHOD_TYPE
,
3182 PyDoc_STR("Compiles an ST object into a code object.")},
3183 {"compilest", (PyCFunction
)parser_compilest
, PUBLIC_METHOD_TYPE
,
3184 PyDoc_STR("Compiles an ST object into a code object.")},
3185 {"expr", (PyCFunction
)parser_expr
, PUBLIC_METHOD_TYPE
,
3186 PyDoc_STR("Creates an ST object from an expression.")},
3187 {"isexpr", (PyCFunction
)parser_isexpr
, PUBLIC_METHOD_TYPE
,
3188 PyDoc_STR("Determines if an ST object was created from an expression.")},
3189 {"issuite", (PyCFunction
)parser_issuite
, PUBLIC_METHOD_TYPE
,
3190 PyDoc_STR("Determines if an ST object was created from a suite.")},
3191 {"suite", (PyCFunction
)parser_suite
, PUBLIC_METHOD_TYPE
,
3192 PyDoc_STR("Creates an ST object from a suite.")},
3193 {"sequence2ast", (PyCFunction
)parser_tuple2st
, PUBLIC_METHOD_TYPE
,
3194 PyDoc_STR("Creates an ST object from a tree representation.")},
3195 {"sequence2st", (PyCFunction
)parser_tuple2st
, PUBLIC_METHOD_TYPE
,
3196 PyDoc_STR("Creates an ST object from a tree representation.")},
3197 {"st2tuple", (PyCFunction
)parser_st2tuple
, PUBLIC_METHOD_TYPE
,
3198 PyDoc_STR("Creates a tuple-tree representation of an ST.")},
3199 {"st2list", (PyCFunction
)parser_st2list
, PUBLIC_METHOD_TYPE
,
3200 PyDoc_STR("Creates a list-tree representation of an ST.")},
3201 {"tuple2ast", (PyCFunction
)parser_tuple2st
, PUBLIC_METHOD_TYPE
,
3202 PyDoc_STR("Creates an ST object from a tree representation.")},
3203 {"tuple2st", (PyCFunction
)parser_tuple2st
, PUBLIC_METHOD_TYPE
,
3204 PyDoc_STR("Creates an ST object from a tree representation.")},
3206 /* private stuff: support pickle module */
3207 {"_pickler", (PyCFunction
)parser__pickler
, METH_VARARGS
,
3208 PyDoc_STR("Returns the pickle magic to allow ST objects to be pickled.")},
3210 {NULL
, NULL
, 0, NULL
}
3214 PyMODINIT_FUNC
initparser(void); /* supply a prototype */
3219 PyObject
*module
, *copyreg
;
3221 PyST_Type
.ob_type
= &PyType_Type
;
3222 module
= Py_InitModule("parser", parser_functions
);
3226 if (parser_error
== 0)
3227 parser_error
= PyErr_NewException("parser.ParserError", NULL
, NULL
);
3229 if (parser_error
== 0)
3230 /* caller will check PyErr_Occurred() */
3232 /* CAUTION: The code next used to skip bumping the refcount on
3233 * parser_error. That's a disaster if initparser() gets called more
3234 * than once. By incref'ing, we ensure that each module dict that
3235 * gets created owns its reference to the shared parser_error object,
3236 * and the file static parser_error vrbl owns a reference too.
3238 Py_INCREF(parser_error
);
3239 if (PyModule_AddObject(module
, "ParserError", parser_error
) != 0)
3242 Py_INCREF(&PyST_Type
);
3243 PyModule_AddObject(module
, "ASTType", (PyObject
*)&PyST_Type
);
3244 Py_INCREF(&PyST_Type
);
3245 PyModule_AddObject(module
, "STType", (PyObject
*)&PyST_Type
);
3247 PyModule_AddStringConstant(module
, "__copyright__",
3248 parser_copyright_string
);
3249 PyModule_AddStringConstant(module
, "__doc__",
3251 PyModule_AddStringConstant(module
, "__version__",
3252 parser_version_string
);
3254 /* Register to support pickling.
3255 * If this fails, the import of this module will fail because an
3256 * exception will be raised here; should we clear the exception?
3258 copyreg
= PyImport_ImportModule("copy_reg");
3259 if (copyreg
!= NULL
) {
3260 PyObject
*func
, *pickler
;
3262 func
= PyObject_GetAttrString(copyreg
, "pickle");
3263 pickle_constructor
= PyObject_GetAttrString(module
, "sequence2st");
3264 pickler
= PyObject_GetAttrString(module
, "_pickler");
3265 Py_XINCREF(pickle_constructor
);
3266 if ((func
!= NULL
) && (pickle_constructor
!= NULL
)
3267 && (pickler
!= NULL
)) {
3270 res
= PyObject_CallFunctionObjArgs(func
, &PyST_Type
, pickler
,
3271 pickle_constructor
, NULL
);
3275 Py_XDECREF(pickle_constructor
);
3276 Py_XDECREF(pickler
);