parsermodule.c 65.4 KB
Newer Older
1
/*  parsermodule.c
2
 *
Guido van Rossum's avatar
Guido van Rossum committed
3 4 5 6 7 8 9
 *  Copyright 1995-1996 by Fred L. Drake, Jr. and Virginia Polytechnic
 *  Institute and State University, Blacksburg, Virginia, USA.
 *  Portions copyright 1991-1995 by Stichting Mathematisch Centrum,
 *  Amsterdam, The Netherlands.  Copying is permitted under the terms
 *  associated with the main Python distribution, with the additional
 *  restriction that this additional notice be included and maintained
 *  on all distributed copies.
10
 *
Guido van Rossum's avatar
Guido van Rossum committed
11 12 13 14 15
 *  This module serves to replace the original parser module written
 *  by Guido.  The functionality is not matched precisely, but the
 *  original may be implemented on top of this.  This is desirable
 *  since the source of the text to be parsed is now divorced from
 *  this interface.
16
 *
Guido van Rossum's avatar
Guido van Rossum committed
17 18 19
 *  Unlike the prior interface, the ability to give a parse tree
 *  produced by Python code as a tuple to the compiler is enabled by
 *  this module.  See the documentation for more details.
20 21 22 23 24 25 26
 */

#include "Python.h"			/* general Python API		  */
#include "graminit.h"			/* symbols defined in the grammar */
#include "node.h"			/* internal parser structure	  */
#include "token.h"			/* token definitions		  */
					/* ISTERMINAL() / ISNONTERMINAL() */
27
#include "compile.h"			/* PyNode_Compile()		  */
28 29 30 31 32 33 34


/*  String constants used to initialize module attributes.
 *
 */
static char*
parser_copyright_string
35 36 37 38
= "Copyright 1995-1996 by Virginia Polytechnic Institute & State\n\
University, Blacksburg, Virginia, USA, and Fred L. Drake, Jr., Reston,\n\
Virginia, USA.  Portions copyright 1991-1995 by Stichting Mathematisch\n\
Centrum, Amsterdam, The Netherlands.";
39 40 41 42 43 44 45


static char*
parser_doc_string
= "This is an interface to Python's internal parser.";

static char*
Guido van Rossum's avatar
Guido van Rossum committed
46 47
parser_version_string = "0.4";

48

49 50 51 52
typedef PyObject* (*SeqMaker) Py_PROTO((int length));
typedef void (*SeqInserter) Py_PROTO((PyObject* sequence,
				      int index,
				      PyObject* element));
53

54
/*  The function below is copyrigthed by Stichting Mathematisch Centrum.  The
55 56 57 58
 *  original copyright statement is included below, and continues to apply
 *  in full to the function immediately following.  All other material is
 *  original, copyrighted by Fred L. Drake, Jr. and Virginia Polytechnic
 *  Institute and State University.  Changes were made to comply with the
59 60
 *  new naming conventions.  Added arguments to provide support for creating
 *  lists as well as tuples, and optionally including the line numbers.
61 62
 */

63
/***********************************************************
64 65
Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
The Netherlands.
66 67 68

                        All Rights Reserved

69 70
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
71
provided that the above copyright notice appear in all copies and that
72
both that copyright notice and this permission notice appear in
73
supporting documentation, and that the names of Stichting Mathematisch
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
Centrum or CWI or Corporation for National Research Initiatives or
CNRI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.

While CWI is the initial source for this software, a modified version
is made available by the Corporation for National Research Initiatives
(CNRI) at the Internet address ftp://ftp.python.org.

STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
91 92 93

******************************************************************/

94
static PyObject*
Guido van Rossum's avatar
Guido van Rossum committed
95 96 97 98 99 100
node2tuple(n, mkseq, addelem, lineno)
     node *n;				/* node to convert		 */
     SeqMaker mkseq;			/* create sequence		 */
     SeqInserter addelem;		/* func. to add elem. in seq.	 */
     int lineno;			/* include line numbers?	 */
{
101 102 103 104 105 106 107
    if (n == NULL) {
	Py_INCREF(Py_None);
	return Py_None;
    }
    if (ISNONTERMINAL(TYPE(n))) {
	int i;
	PyObject *v, *w;
Guido van Rossum's avatar
Guido van Rossum committed
108
	v = mkseq(1 + NCH(n));
109 110 111 112 113 114
	if (v == NULL)
	    return v;
	w = PyInt_FromLong(TYPE(n));
	if (w == NULL) {
	    Py_DECREF(v);
	    return NULL;
115
	}
Guido van Rossum's avatar
Guido van Rossum committed
116
	addelem(v, 0, w);
117
	for (i = 0; i < NCH(n); i++) {
Guido van Rossum's avatar
Guido van Rossum committed
118
	    w = node2tuple(CHILD(n, i), mkseq, addelem, lineno);
119 120
	    if (w == NULL) {
		Py_DECREF(v);
121
		return NULL;
122
	    }
Guido van Rossum's avatar
Guido van Rossum committed
123
	    addelem(v, i+1, w);
124
	}
Guido van Rossum's avatar
Guido van Rossum committed
125
	return (v);
126 127
    }
    else if (ISTERMINAL(TYPE(n))) {
Guido van Rossum's avatar
Guido van Rossum committed
128 129 130 131 132 133 134 135
	PyObject *result = mkseq(2 + lineno);
	if (result != NULL) {
	    addelem(result, 0, PyInt_FromLong(TYPE(n)));
	    addelem(result, 1, PyString_FromString(STR(n)));
	    if (lineno == 1)
		addelem(result, 2, PyInt_FromLong(n->n_lineno));
	}
	return (result);
136 137 138 139 140 141
    }
    else {
	PyErr_SetString(PyExc_SystemError,
			"unrecognized parse tree node type");
	return NULL;
    }
Guido van Rossum's avatar
Guido van Rossum committed
142
}   /* node2tuple() */
143 144 145 146 147 148 149 150 151 152 153 154
/*
 *  End of material copyrighted by Stichting Mathematisch Centrum.
 */



/*  There are two types of intermediate objects we're interested in:
 *  'eval' and 'exec' types.  These constants can be used in the ast_type
 *  field of the object type to identify which any given object represents.
 *  These should probably go in an external header to allow other extensions
 *  to use them, but then, we really should be using C++ too.  ;-)
 *
155 156
 *  The PyAST_FRAGMENT type is not currently supported.  Maybe not useful?
 *  Haven't decided yet.
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
 */

#define PyAST_EXPR	1
#define PyAST_SUITE	2
#define PyAST_FRAGMENT	3


/*  These are the internal objects and definitions required to implement the
 *  AST type.  Most of the internal names are more reminiscent of the 'old'
 *  naming style, but the code uses the new naming convention.
 */

static PyObject*
parser_error = 0;


typedef struct _PyAST_Object {
174

175 176 177 178 179 180 181
    PyObject_HEAD			/* standard object header	    */
    node* ast_node;			/* the node* returned by the parser */
    int	  ast_type;			/* EXPR or SUITE ?		    */

} PyAST_Object;


182 183 184
staticforward void parser_free Py_PROTO((PyAST_Object *ast));
staticforward int  parser_compare Py_PROTO((PyAST_Object *left,
					    PyAST_Object *right));
185 186 187 188 189


/* static */
PyTypeObject PyAST_Type = {

190
    PyObject_HEAD_INIT(NULL)
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    0,
    "ast",				/* tp_name		*/
    sizeof(PyAST_Object),		/* tp_basicsize		*/
    0,					/* tp_itemsize		*/
    (destructor)parser_free,		/* tp_dealloc		*/
    0,					/* tp_print		*/
    0,					/* tp_getattr		*/
    0,					/* tp_setattr		*/
    (cmpfunc)parser_compare,		/* tp_compare		*/
    0,					/* tp_repr		*/
    0,					/* tp_as_number		*/
    0,					/* tp_as_sequence	*/
    0,					/* tp_as_mapping	*/
    0,					/* tp_hash		*/
    0,					/* tp_call		*/
206 207 208 209 210 211 212 213 214 215 216 217
    0,					/* tp_str		*/
    0,					/* tp_getattro		*/
    0,					/* tp_setattro		*/

    /* Functions to access object as input/output buffer */
    0,					/* tp_as_buffer		*/

    /* Space for future expansion */
    0,					/* tp_xxx4		*/

    /* __doc__ */
    "Intermediate representation of a Python parse tree."
218 219 220 221 222 223

};  /* PyAST_Type */


static int
parser_compare_nodes(left, right)
224 225
     node *left;
     node *right;
Guido van Rossum's avatar
Guido van Rossum committed
226
{
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
    int j;

    if (TYPE(left) < TYPE(right))
	return (-1);

    if (TYPE(right) < TYPE(left))
	return (1);

    if (ISTERMINAL(TYPE(left)))
	return (strcmp(STR(left), STR(right)));

    if (NCH(left) < NCH(right))
	return (-1);

    if (NCH(right) < NCH(left))
	return (1);

    for (j = 0; j < NCH(left); ++j) {
	int v = parser_compare_nodes(CHILD(left, j), CHILD(right, j));

	if (v)
	    return (v);
    }
    return (0);

}   /* parser_compare_nodes() */


/*  int parser_compare(PyAST_Object* left, PyAST_Object* right)
 *
 *  Comparison function used by the Python operators ==, !=, <, >, <=, >=
 *  This really just wraps a call to parser_compare_nodes() with some easy
 *  checks and protection code.
 *
 */
static int
parser_compare(left, right)
264 265
     PyAST_Object *left;
     PyAST_Object *right;
Guido van Rossum's avatar
Guido van Rossum committed
266
{
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
    if (left == right)
	return (0);

    if ((left == 0) || (right == 0))
	return (-1);

    return (parser_compare_nodes(left->ast_node, right->ast_node));

}   /* parser_compare() */


/*  parser_newastobject(node* ast)
 *
 *  Allocates a new Python object representing an AST.  This is simply the
 *  'wrapper' object that holds a node* and allows it to be passed around in
 *  Python code.
 *
 */
static PyObject*
parser_newastobject(ast, type)
287 288
     node *ast;
     int type;
Guido van Rossum's avatar
Guido van Rossum committed
289
{
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
    PyAST_Object* o = PyObject_NEW(PyAST_Object, &PyAST_Type);

    if (o != 0) {
	o->ast_node = ast;
	o->ast_type = type;
    }
    return ((PyObject*)o);

}   /* parser_newastobject() */


/*  void parser_free(PyAST_Object* ast)
 *
 *  This is called by a del statement that reduces the reference count to 0.
 *
 */
static void
parser_free(ast)
308
     PyAST_Object *ast;
Guido van Rossum's avatar
Guido van Rossum committed
309
{
310 311 312 313 314 315 316 317 318 319 320 321 322 323
    PyNode_Free(ast->ast_node);
    PyMem_DEL(ast);

}   /* parser_free() */


/*  parser_ast2tuple(PyObject* self, PyObject* args)
 *
 *  This provides conversion from a node* to a tuple object that can be
 *  returned to the Python-level caller.  The AST object is not modified.
 *
 */
static PyObject*
parser_ast2tuple(self, args)
324 325
     PyObject *self;
     PyObject *args;
Guido van Rossum's avatar
Guido van Rossum committed
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
{
    PyObject *ast;
    PyObject *line_option = 0;
    PyObject *res = 0;

    if (PyArg_ParseTuple(args, "O!|O:ast2tuple", &PyAST_Type, &ast,
			 &line_option)) {
	int lineno = 0;
	if (line_option != 0) {
	    lineno = PyObject_IsTrue(line_option);
	    lineno = lineno ? 1 : 0;
	}
	/*
	 *  Convert AST into a tuple representation.  Use Guido's function,
	 *  since it's known to work already.
	 */
	res = node2tuple(((PyAST_Object*)ast)->ast_node,
			 PyTuple_New, PyTuple_SetItem, lineno);
    }
    return (res);

}   /* parser_ast2tuple() */
348

349

Guido van Rossum's avatar
Guido van Rossum committed
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
/*  parser_ast2tuple(PyObject* self, PyObject* args)
 *
 *  This provides conversion from a node* to a tuple object that can be
 *  returned to the Python-level caller.  The AST object is not modified.
 *
 */
static PyObject*
parser_ast2list(self, args)
     PyObject *self;
     PyObject *args;
{
    PyObject *ast;
    PyObject *line_option = 0;
    PyObject *res = 0;

    if (PyArg_ParseTuple(args, "O!|O:ast2list", &PyAST_Type, &ast,
			 &line_option)) {
	int lineno = 0;
	if (line_option != 0) {
	    lineno = PyObject_IsTrue(line_option);
	    lineno = lineno ? 1 : 0;
	}
372 373 374 375
	/*
	 *  Convert AST into a tuple representation.  Use Guido's function,
	 *  since it's known to work already.
	 */
Guido van Rossum's avatar
Guido van Rossum committed
376 377
	res = node2tuple(((PyAST_Object*)ast)->ast_node,
			 PyList_New, PyList_SetItem, lineno);
378 379 380
    }
    return (res);

Guido van Rossum's avatar
Guido van Rossum committed
381
}   /* parser_ast2list() */
382 383 384 385 386 387 388 389 390 391


/*  parser_compileast(PyObject* self, PyObject* args)
 *
 *  This function creates code objects from the parse tree represented by
 *  the passed-in data object.  An optional file name is passed in as well.
 *
 */
static PyObject*
parser_compileast(self, args)
392 393
     PyObject *self;
     PyObject *args;
Guido van Rossum's avatar
Guido van Rossum committed
394
{
395 396 397 398 399
    PyAST_Object* ast;
    PyObject*     res = 0;
    char*	  str = "<ast>";

    if (PyArg_ParseTuple(args, "O!|s", &PyAST_Type, &ast, &str))
400
	res = (PyObject*) PyNode_Compile(ast->ast_node, str);
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415

    return (res);

}   /* parser_compileast() */


/*  PyObject* parser_isexpr(PyObject* self, PyObject* args)
 *  PyObject* parser_issuite(PyObject* self, PyObject* args)
 *
 *  Checks the passed-in AST object to determine if it is an expression or
 *  a statement suite, respectively.  The return is a Python truth value.
 *
 */
static PyObject*
parser_isexpr(self, args)
416 417
     PyObject *self;
     PyObject *args;
Guido van Rossum's avatar
Guido van Rossum committed
418
{
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    PyAST_Object* ast;
    PyObject* res = 0;

    if (PyArg_ParseTuple(args, "O!:isexpr", &PyAST_Type, &ast)) {
	/*
	 *  Check to see if the AST represents an expression or not.
	 */
	res = (ast->ast_type == PyAST_EXPR) ? Py_True : Py_False;
	Py_INCREF(res);
    }
    return (res);

}   /* parser_isexpr() */


static PyObject*
parser_issuite(self, args)
436 437
     PyObject *self;
     PyObject *args;
Guido van Rossum's avatar
Guido van Rossum committed
438
{
439 440 441
    PyAST_Object* ast;
    PyObject* res = 0;

442
    if (PyArg_ParseTuple(args, "O!:issuite", &PyAST_Type, &ast)) {
443 444 445 446 447 448 449 450 451 452 453
	/*
	 *  Check to see if the AST represents an expression or not.
	 */
	res = (ast->ast_type == PyAST_EXPR) ? Py_False : Py_True;
	Py_INCREF(res);
    }
    return (res);

}   /* parser_issuite() */


454 455 456 457 458 459 460 461
/*  err_string(char* message)
 *
 *  Sets the error string for an exception of type ParserError.
 *
 */
static void
err_string(message)
     char *message;
Guido van Rossum's avatar
Guido van Rossum committed
462
{
463 464 465 466 467
    PyErr_SetString(parser_error, message);

}  /* err_string() */


468 469 470 471 472 473 474 475 476
/*  PyObject* parser_do_parse(PyObject* args, int type)
 *
 *  Internal function to actually execute the parse and return the result if
 *  successful, or set an exception if not.
 *
 */
static PyObject*
parser_do_parse(args, type)
     PyObject *args;
477
     int type;
Guido van Rossum's avatar
Guido van Rossum committed
478
{
479 480 481 482 483 484 485 486 487 488 489
    char*     string = 0;
    PyObject* res    = 0;

    if (PyArg_ParseTuple(args, "s", &string)) {
	node* n = PyParser_SimpleParseString(string,
					     (type == PyAST_EXPR)
					     ? eval_input : file_input);

	if (n != 0)
	    res = parser_newastobject(n, type);
	else
490
	    err_string("Could not parse string.");
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
    }
    return (res);

}  /* parser_do_parse() */


/*  PyObject* parser_expr(PyObject* self, PyObject* args)
 *  PyObject* parser_suite(PyObject* self, PyObject* args)
 *
 *  External interfaces to the parser itself.  Which is called determines if
 *  the parser attempts to recognize an expression ('eval' form) or statement
 *  suite ('exec' form).  The real work is done by parser_do_parse() above.
 *
 */
static PyObject*
parser_expr(self, args)
507 508
     PyObject *self;
     PyObject *args;
Guido van Rossum's avatar
Guido van Rossum committed
509
{
510 511 512 513 514 515 516
    return (parser_do_parse(args, PyAST_EXPR));

}   /* parser_expr() */


static PyObject*
parser_suite(self, args)
517 518
     PyObject *self;
     PyObject *args;
Guido van Rossum's avatar
Guido van Rossum committed
519
{
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
    return (parser_do_parse(args, PyAST_SUITE));

}   /* parser_suite() */



/*  This is the messy part of the code.  Conversion from a tuple to an AST
 *  object requires that the input tuple be valid without having to rely on
 *  catching an exception from the compiler.  This is done to allow the
 *  compiler itself to remain fast, since most of its input will come from
 *  the parser directly, and therefore be known to be syntactically correct.
 *  This validation is done to ensure that we don't core dump the compile
 *  phase, returning an exception instead.
 *
 *  Two aspects can be broken out in this code:  creating a node tree from
 *  the tuple passed in, and verifying that it is indeed valid.  It may be
 *  advantageous to expand the number of AST types to include funcdefs and
 *  lambdadefs to take advantage of the optimizer, recognizing those ASTs
 *  here.  They are not necessary, and not quite as useful in a raw form.
 *  For now, let's get expressions and suites working reliably.
 */


543 544 545
staticforward node* build_node_tree Py_PROTO((PyObject *tuple));
staticforward int   validate_expr_tree Py_PROTO((node *tree));
staticforward int   validate_file_input Py_PROTO((node *tree));
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562


/*  PyObject* parser_tuple2ast(PyObject* self, PyObject* args)
 *
 *  This is the public function, called from the Python code.  It receives a
 *  single tuple object from the caller, and creates an AST object if the
 *  tuple can be validated.  It does this by checking the first code of the
 *  tuple, and, if acceptable, builds the internal representation.  If this
 *  step succeeds, the internal representation is validated as fully as
 *  possible with the various validate_*() routines defined below.
 *
 *  This function must be changed if support is to be added for PyAST_FRAGMENT
 *  AST objects.
 *
 */
static PyObject*
parser_tuple2ast(self, args)
563 564
     PyObject *self;
     PyObject *args;
Guido van Rossum's avatar
Guido van Rossum committed
565 566 567 568 569
{
    PyObject *ast = 0;
    PyObject *tuple = 0;
    PyObject *temp = 0;
    int ok;
Guido van Rossum's avatar
Guido van Rossum committed
570
    int start_sym = 0;
571

Guido van Rossum's avatar
Guido van Rossum committed
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
    if (!PyArg_ParseTuple(args, "O:tuple2ast", &tuple))
	return (0);
    if (!PySequence_Check(tuple)) {
	PyErr_SetString(PyExc_ValueError,
			"tuple2ast() requires a single sequence argument");
	return (0);
    }
    /*
     *	This mess of tests is written this way so we can use the abstract
     *	object interface (AOI).  Unfortunately, the AOI increments reference
     *	counts, which requires that we store a pointer to retrieved object
     *	so we can DECREF it after the check.  But we really should accept
     *	lists as well as tuples at the very least.
     */
    ok = PyObject_Length(tuple) >= 2;
    if (ok) {
	temp = PySequence_GetItem(tuple, 0);
	ok = (temp != NULL) && PyInt_Check(temp);
	if (ok)
	    /* this is used after the initial checks: */
	    start_sym = PyInt_AsLong(temp);
	Py_XDECREF(temp);
    }
    if (ok) {
	temp = PySequence_GetItem(tuple, 1);
	ok = (temp != NULL) && PySequence_Check(temp);
	Py_XDECREF(temp);
    }
    if (ok) {
	temp = PySequence_GetItem(tuple, 1);
	ok = (temp != NULL) && PyObject_Length(temp) >= 2;
	if (ok) {
	    PyObject *temp2 = PySequence_GetItem(temp, 0);
	    if (temp2 != NULL) {
		ok = PyInt_Check(temp2);
		Py_DECREF(temp2);
	    }
609
	}
Guido van Rossum's avatar
Guido van Rossum committed
610 611 612 613 614 615 616 617 618 619 620 621 622 623
	Py_XDECREF(temp);
    }
    /* If we've failed at some point, get out of here. */
    if (!ok) {
	err_string("malformed sequence for tuple2ast()");
	return (0);
    }
    /*
     *  This might be a valid parse tree, but let's do a quick check
     *  before we jump the gun.
     */
    if (start_sym == eval_input) {
	/*  Might be an eval form.  */
	node* expression = build_node_tree(tuple);
624

Guido van Rossum's avatar
Guido van Rossum committed
625 626 627 628 629 630
	if ((expression != 0) && validate_expr_tree(expression))
	    ast = parser_newastobject(expression, PyAST_EXPR);
    }
    else if (start_sym == file_input) {
	/*  This looks like an exec form so far.  */
	node* suite_tree = build_node_tree(tuple);
631

Guido van Rossum's avatar
Guido van Rossum committed
632 633
	if ((suite_tree != 0) && validate_file_input(suite_tree))
	    ast = parser_newastobject(suite_tree, PyAST_SUITE);
634
    }
635
    else
Guido van Rossum's avatar
Guido van Rossum committed
636 637 638 639 640 641 642 643 644 645
	/*  This is a fragment, and is not yet supported.  Maybe they
	 *  will be if I find a use for them.
	 */
	err_string("Fragmentary parse trees not supported.");

    /*  Make sure we throw an exception on all errors.  We should never
     *  get this, but we'd do well to be sure something is done.
     */
    if ((ast == 0) && !PyErr_Occurred())
	err_string("Unspecified ast error occurred.");
646

647
    return (ast);
648

649 650 651 652 653
}   /* parser_tuple2ast() */


/*  int check_terminal_tuple()
 *
Guido van Rossum's avatar
Guido van Rossum committed
654 655 656
 *  Check a tuple to determine that it is indeed a valid terminal
 *  node.  The node is known to be required as a terminal, so we throw
 *  an exception if there is a failure.
657
 *
Guido van Rossum's avatar
Guido van Rossum committed
658 659 660 661 662 663 664 665
 *  The format of an acceptable terminal tuple is "(is[i])": the fact
 *  that elem is a tuple and the integer is a valid terminal symbol
 *  has been established before this function is called.  We must
 *  check the length of the tuple and the type of the second element
 *  and optional third element.  We do *NOT* check the actual text of
 *  the string element, which we could do in many cases.  This is done
 *  by the validate_*() functions which operate on the internal
 *  representation.
666 667
 */
static int
Guido van Rossum's avatar
Guido van Rossum committed
668
check_terminal_tuple(elem)
669
     PyObject *elem;
Guido van Rossum's avatar
Guido van Rossum committed
670 671 672 673
{
    int   len = PyObject_Length(elem);
    int   res = 1;
    char* str = "Illegal terminal symbol; bad node length.";
674

Guido van Rossum's avatar
Guido van Rossum committed
675 676 677
    if ((len == 2) || (len == 3)) {
	PyObject *temp = PySequence_GetItem(elem, 1);
	res = PyString_Check(temp);
678
	str = "Illegal terminal symbol; expected a string.";
Guido van Rossum's avatar
Guido van Rossum committed
679 680 681 682 683 684 685 686 687 688 689 690
	if (res && (len == 3)) {
	    PyObject* third = PySequence_GetItem(elem, 2);
	    res = PyInt_Check(third);
	    str = "Invalid third element of terminal node.";
	    Py_XDECREF(third);
	}
	Py_XDECREF(temp);
    }
    else {
	res = 0;
    }
    if (!res) {
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
	elem = Py_BuildValue("(os)", elem, str);
	PyErr_SetObject(parser_error, elem);
    }
    return (res);

}   /* check_terminal_tuple() */


/*  node* build_node_children()
 *
 *  Iterate across the children of the current non-terminal node and build
 *  their structures.  If successful, return the root of this portion of
 *  the tree, otherwise, 0.  Any required exception will be specified already,
 *  and no memory will have been deallocated.
 *
 */
static node*
build_node_children(tuple, root, line_num)
709 710 711
     PyObject *tuple;
     node *root;
     int *line_num;
Guido van Rossum's avatar
Guido van Rossum committed
712
{
713
    int len = PyObject_Length(tuple);
714 715 716 717
    int i;

    for (i = 1; i < len; ++i) {
	/* elem must always be a tuple, however simple */
718
	PyObject* elem = PySequence_GetItem(tuple, i);
Guido van Rossum's avatar
Guido van Rossum committed
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
	int ok = elem != NULL;
	long  type = 0;
	char *strn = 0;

	if (ok)
	    ok = PySequence_Check(elem);
	if (ok) {
	    PyObject *temp = PySequence_GetItem(elem, 0);
	    if (temp == NULL)
		ok = 0;
	    else {
		ok = PyInt_Check(temp);
		if (ok)
		    type = PyInt_AsLong(temp);
		Py_DECREF(temp);
	    }
	}
	if (!ok) {
737 738 739
	    PyErr_SetObject(parser_error,
			    Py_BuildValue("(os)", elem,
					  "Illegal node construct."));
Guido van Rossum's avatar
Guido van Rossum committed
740
	    Py_XDECREF(elem);
741 742 743
	    return (0);
	}
	if (ISTERMINAL(type)) {
Guido van Rossum's avatar
Guido van Rossum committed
744 745 746
	    if (check_terminal_tuple(elem)) {
		PyObject *temp = PySequence_GetItem(elem, 1);

747 748 749 750
		/* check_terminal_tuple() already verified it's a string */
		strn = (char *)malloc(PyString_GET_SIZE(temp) + 1);
		if (strn != NULL)
		    strcpy(strn, PyString_AS_STRING(temp));
Guido van Rossum's avatar
Guido van Rossum committed
751 752 753 754 755 756 757 758 759 760
		Py_XDECREF(temp);

		if (PyObject_Length(elem) == 3) {
		    PyObject* temp = PySequence_GetItem(elem, 2);
		    *line_num = PyInt_AsLong(temp);
		    Py_DECREF(temp);
		}
	    }
	    else {
		Py_XDECREF(elem);
761
		return (0);
Guido van Rossum's avatar
Guido van Rossum committed
762
	    }
763 764 765 766 767 768 769 770 771
	}
	else if (!ISNONTERMINAL(type)) {
	    /*
	     *  It has to be one or the other; this is an error.
	     *  Throw an exception.
	     */
	    PyErr_SetObject(parser_error,
			    Py_BuildValue("(os)", elem,
					  "Unknown node type."));
Guido van Rossum's avatar
Guido van Rossum committed
772
	    Py_XDECREF(elem);
773 774 775 776 777 778 779
	    return (0);
	}
	PyNode_AddChild(root, type, strn, *line_num);

	if (ISNONTERMINAL(type)) {
	    node* new_child = CHILD(root, i - 1);

Guido van Rossum's avatar
Guido van Rossum committed
780 781
	    if (new_child != build_node_children(elem, new_child, line_num)) {
		Py_XDECREF(elem);
782
		return (0);
Guido van Rossum's avatar
Guido van Rossum committed
783
	    }
784
	}
Guido van Rossum's avatar
Guido van Rossum committed
785
	else if (type == NEWLINE) {	/* It's true:  we increment the     */
786
	    ++(*line_num);		/* line number *after* the newline! */
Guido van Rossum's avatar
Guido van Rossum committed
787 788
	}
	Py_XDECREF(elem);
789 790 791 792 793 794 795 796
    }
    return (root);

}   /* build_node_children() */


static node*
build_node_tree(tuple)
797
     PyObject *tuple;
Guido van Rossum's avatar
Guido van Rossum committed
798
{
799
    node* res = 0;
Guido van Rossum's avatar
Guido van Rossum committed
800 801
    PyObject *temp = PySequence_GetItem(tuple, 0);
    long  num = -1;
802

Guido van Rossum's avatar
Guido van Rossum committed
803 804 805
    if (temp != NULL)
	num = PyInt_AsLong(temp);
    Py_XDECREF(temp);
806 807 808 809 810 811
    if (ISTERMINAL(num)) {
	/*
	 *  The tuple is simple, but it doesn't start with a start symbol.
	 *  Throw an exception now and be done with it.
	 */
	tuple = Py_BuildValue("(os)", tuple,
812
		    "Illegal ast tuple; cannot start with terminal symbol.");
813 814 815 816 817 818 819 820 821 822 823 824 825 826
	PyErr_SetObject(parser_error, tuple);
    }
    else if (ISNONTERMINAL(num)) {
	/*
	 *  Not efficient, but that can be handled later.
	 */
	int line_num = 0;

	res = PyNode_New(num);
	if (res != build_node_children(tuple, res, &line_num)) {
	    PyNode_Free(res);
	    res = 0;
	}
    }
827 828
    else
	/*  The tuple is illegal -- if the number is neither TERMINAL nor
829 830 831 832 833
	 *  NONTERMINAL, we can't use it.
	 */
	PyErr_SetObject(parser_error,
			Py_BuildValue("(os)", tuple,
				      "Illegal component tuple."));
834

835 836 837 838 839
    return (res);

}   /* build_node_tree() */


Guido van Rossum's avatar
Guido van Rossum committed
840
#ifdef HAVE_OLD_CPP
841
#define VALIDATER(n)    static int validate_/**/n Py_PROTO((node *tree))
Guido van Rossum's avatar
Guido van Rossum committed
842
#else
843
#define	VALIDATER(n)	static int validate_##n Py_PROTO((node *tree))
Guido van Rossum's avatar
Guido van Rossum committed
844
#endif
845 846 847 848 849


/*
 *  Validation routines used within the validation section:
 */
850 851
staticforward int validate_terminal Py_PROTO((node *terminal,
					      int type, char *string));
852 853 854 855 856 857 858

#define	validate_ampersand(ch)	validate_terminal(ch,	   AMPER, "&")
#define	validate_circumflex(ch)	validate_terminal(ch, CIRCUMFLEX, "^")
#define validate_colon(ch)	validate_terminal(ch,	   COLON, ":")
#define validate_comma(ch)	validate_terminal(ch,	   COMMA, ",")
#define validate_dedent(ch)	validate_terminal(ch,	  DEDENT, "")
#define	validate_equal(ch)	validate_terminal(ch,	   EQUAL, "=")
859
#define validate_indent(ch)	validate_terminal(ch,	  INDENT, 0)
860
#define validate_lparen(ch)	validate_terminal(ch,	    LPAR, "(")
861
#define	validate_newline(ch)	validate_terminal(ch,	 NEWLINE, 0)
862 863 864 865
#define validate_rparen(ch)	validate_terminal(ch,	    RPAR, ")")
#define validate_semi(ch)	validate_terminal(ch,	    SEMI, ";")
#define	validate_star(ch)	validate_terminal(ch,	    STAR, "*")
#define	validate_vbar(ch)	validate_terminal(ch,	    VBAR, "|")
866
#define validate_doublestar(ch)	validate_terminal(ch, DOUBLESTAR, "**")
Guido van Rossum's avatar
Guido van Rossum committed
867
#define validate_dot(ch)	validate_terminal(ch,	     DOT, ".")
868
#define	validate_name(ch, str)	validate_terminal(ch,	    NAME, str)
869

870
VALIDATER(node);		VALIDATER(small_stmt);
871 872 873 874 875
VALIDATER(class);		VALIDATER(node);
VALIDATER(parameters);		VALIDATER(suite);
VALIDATER(testlist);		VALIDATER(varargslist);
VALIDATER(fpdef);		VALIDATER(fplist);
VALIDATER(stmt);		VALIDATER(simple_stmt);
876
VALIDATER(expr_stmt);		VALIDATER(power);
877 878 879
VALIDATER(print_stmt);		VALIDATER(del_stmt);
VALIDATER(return_stmt);
VALIDATER(raise_stmt);		VALIDATER(import_stmt);
880
VALIDATER(global_stmt);
Guido van Rossum's avatar
Guido van Rossum committed
881
VALIDATER(assert_stmt);
882 883 884 885 886 887 888 889 890 891 892
VALIDATER(exec_stmt);		VALIDATER(compound_stmt);
VALIDATER(while);		VALIDATER(for);
VALIDATER(try);			VALIDATER(except_clause);
VALIDATER(test);		VALIDATER(and_test);
VALIDATER(not_test);		VALIDATER(comparison);
VALIDATER(comp_op);		VALIDATER(expr);
VALIDATER(xor_expr);		VALIDATER(and_expr);
VALIDATER(shift_expr);		VALIDATER(arith_expr);
VALIDATER(term);		VALIDATER(factor);
VALIDATER(atom);		VALIDATER(lambdef);
VALIDATER(trailer);		VALIDATER(subscript);
Guido van Rossum's avatar
Guido van Rossum committed
893
VALIDATER(subscriptlist);	VALIDATER(sliceop);
894
VALIDATER(exprlist);		VALIDATER(dictmaker);
895
VALIDATER(arglist);		VALIDATER(argument);
896 897 898 899 900 901 902 903


#define	is_even(n)	(((n) & 1) == 0)
#define	is_odd(n)	(((n) & 1) == 1)


static int
validate_ntype(n, t)
904 905
     node *n;
     int t;
Guido van Rossum's avatar
Guido van Rossum committed
906
{
907 908 909 910 911
    int res = (TYPE(n) == t);

    if (!res) {
	char buffer[128];
	sprintf(buffer, "Expected node type %d, got %d.", t, TYPE(n));
912
	err_string(buffer);
913 914 915 916 917 918
    }
    return (res);

}   /* validate_ntype() */


919 920 921 922 923
static int
validate_numnodes(n, num, name)
     node *n;
     int num;
     const char *const name;
Guido van Rossum's avatar
Guido van Rossum committed
924
{
925 926 927 928 929 930 931 932 933 934
    if (NCH(n) != num) {
	char buff[60];
	sprintf(buff, "Illegal number of children for %s node.", name);
	err_string(buff);
    }
    return (NCH(n) == num);

}   /* validate_numnodes() */


935 936
static int
validate_terminal(terminal, type, string)
937 938 939
     node *terminal;
     int type;
     char *string;
Guido van Rossum's avatar
Guido van Rossum committed
940
{
941 942
    int res = (validate_ntype(terminal, type)
	       && ((string == 0) || (strcmp(string, STR(terminal)) == 0)));
943

944 945 946 947
    if (!res && !PyErr_Occurred()) {
	char buffer[60];
	sprintf(buffer, "Illegal terminal: expected \"%s\"", string);
	err_string(buffer);
948 949 950 951 952 953
    }
    return (res);

}   /* validate_terminal() */


Guido van Rossum's avatar
Guido van Rossum committed
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
/*  X (',' X) [',']
 */
static int
validate_repeating_list(tree, ntype, vfunc, name)
    node *tree;
    int ntype;
    int (*vfunc)();
    const char *const name;
{
    int nch = NCH(tree);
    int res = (nch && validate_ntype(tree, ntype)
	       && vfunc(CHILD(tree, 0)));

    if (!res && !PyErr_Occurred())
	validate_numnodes(tree, 1, name);
    else {
	if (is_even(nch))
	    res = validate_comma(CHILD(tree, --nch));
	if (res && nch > 1) {
	    int pos = 1;
	    for ( ; res && pos < nch; pos += 2)
		res = (validate_comma(CHILD(tree, pos))
		       && vfunc(CHILD(tree, pos + 1)));
	}
    }
    return (res);

}   /* validate_repeating_list() */


984 985 986 987 988
/*  VALIDATE(class)
 *
 *  classdef:
 *	'class' NAME ['(' testlist ')'] ':' suite
 */
Guido van Rossum's avatar
Guido van Rossum committed
989
static int
990 991 992
validate_class(tree)
    node *tree;
{
993
    int nch = NCH(tree);
994
    int res = validate_ntype(tree, classdef) && ((nch == 4) || (nch == 7));
995

996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
    if (res) {
	res = (validate_name(CHILD(tree, 0), "class")
	       && validate_ntype(CHILD(tree, 1), NAME)
	       && validate_colon(CHILD(tree, nch - 2))
	       && validate_suite(CHILD(tree, nch - 1)));
    }
    else
	validate_numnodes(tree, 4, "class");
    if (res && (nch == 7)) {
	res = (validate_lparen(CHILD(tree, 2))
	       && validate_testlist(CHILD(tree, 3))
	       && validate_rparen(CHILD(tree, 4)));
1008 1009 1010 1011 1012 1013
    }
    return (res);

}   /* validate_class() */


1014 1015 1016
/*  if_stmt:
 *	'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
 */
Guido van Rossum's avatar
Guido van Rossum committed
1017
static int
1018 1019
validate_if(tree)
    node *tree;
1020 1021
{
    int nch = NCH(tree);
1022 1023
    int res = (validate_ntype(tree, if_stmt)
	       && (nch >= 4)
1024
	       && validate_name(CHILD(tree, 0), "if")
1025
	       && validate_test(CHILD(tree, 1))
1026 1027 1028 1029
	       && validate_colon(CHILD(tree, 2))
	       && validate_suite(CHILD(tree, 3)));

    if (res && ((nch % 4) == 3)) {
1030 1031 1032 1033
	/*  ... 'else' ':' suite  */
	res = (validate_name(CHILD(tree, nch - 3), "else")
	       && validate_colon(CHILD(tree, nch - 2))
	       && validate_suite(CHILD(tree, nch - 1)));
1034 1035
	nch -= 3;
    }
1036 1037
    else if (!res && !PyErr_Occurred())
	validate_numnodes(tree, 4, "if");
1038
    if ((nch % 4) != 0)
1039 1040
	/* Will catch the case for nch < 4 */
	res = validate_numnodes(tree, 0, "if");
1041
    else if (res && (nch > 4)) {
1042
	/*  ... ('elif' test ':' suite)+ ...  */
1043 1044
	int j = 4;
	while ((j < nch) && res) {
1045 1046 1047 1048
	    res = (validate_name(CHILD(tree, j), "elif")
		   && validate_colon(CHILD(tree, j + 2))
		   && validate_test(CHILD(tree, j + 1))
		   && validate_suite(CHILD(tree, j + 3)));
1049 1050 1051 1052 1053 1054 1055 1056
	    j += 4;
	}
    }
    return (res);

}   /* validate_if() */


1057 1058 1059 1060
/*  parameters:
 *	'(' [varargslist] ')'
 *
 */
Guido van Rossum's avatar
Guido van Rossum committed
1061
static int
1062 1063 1064
validate_parameters(tree)
    node *tree;
{
1065
    int nch = NCH(tree);
1066
    int res = validate_ntype(tree, parameters) && ((nch == 2) || (nch == 3));
1067

1068 1069 1070 1071 1072 1073 1074 1075
    if (res) {
	res = (validate_lparen(CHILD(tree, 0))
	       && validate_rparen(CHILD(tree, nch - 1)));
	if (res && (nch == 3))
	    res = validate_varargslist(CHILD(tree, 1));
    }
    else
	validate_numnodes(tree, 2, "parameters");
1076 1077 1078 1079 1080 1081

    return (res);

}   /* validate_parameters() */


1082 1083 1084 1085 1086 1087
/*  VALIDATE(suite)
 *
 *  suite:
 *	simple_stmt
 *    | NEWLINE INDENT stmt+ DEDENT
 */
Guido van Rossum's avatar
Guido van Rossum committed
1088
static int
1089 1090 1091
validate_suite(tree)
    node *tree;
{
1092
    int nch = NCH(tree);
1093
    int res = (validate_ntype(tree, suite) && ((nch == 1) || (nch >= 4)));
1094

1095 1096 1097 1098 1099
    if (res && (nch == 1))
	res = validate_simple_stmt(CHILD(tree, 0));
    else if (res) {
	/*  NEWLINE INDENT stmt+ DEDENT  */
	res = (validate_newline(CHILD(tree, 0))
1100
	       && validate_indent(CHILD(tree, 1))
1101
	       && validate_stmt(CHILD(tree, 2))
1102 1103
	       && validate_dedent(CHILD(tree, nch - 1)));

1104 1105 1106 1107 1108
	if (res && (nch > 4)) {
	    int i = 3;
	    --nch;			/* forget the DEDENT	 */
	    for ( ; res && (i < nch); ++i)
		res = validate_stmt(CHILD(tree, i));
1109
	}
1110 1111
	else if (nch < 4)
	    validate_numnodes(tree, 4, "suite");
1112 1113 1114 1115 1116 1117
    }
    return (res);

}   /* validate_suite() */


Guido van Rossum's avatar
Guido van Rossum committed
1118
static int
1119 1120 1121
validate_testlist(tree)
    node *tree;
{
Guido van Rossum's avatar
Guido van Rossum committed
1122 1123
    return (validate_repeating_list(tree, testlist,
				    validate_test, "testlist"));
1124 1125 1126 1127

}   /* validate_testlist() */


1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
/*  VALIDATE(varargslist)
 *
 *  varargslist:
 *	(fpdef ['=' test] ',')* ('*' NAME [',' '*' '*' NAME] | '*' '*' NAME)
 *    | fpdef ['=' test] (',' fpdef ['=' test])* [',']
 *
 *      (fpdef ['=' test] ',')*
 *           ('*' NAME [',' ('**'|'*' '*') NAME]
 *         | ('**'|'*' '*') NAME)
 *    | fpdef ['=' test] (',' fpdef ['=' test])* [',']
 *
 */
Guido van Rossum's avatar
Guido van Rossum committed
1140
static int
1141 1142 1143
validate_varargslist(tree)
    node *tree;
{
1144
    int nch = NCH(tree);
1145
    int res = validate_ntype(tree, varargslist) && (nch != 0);
1146

1147 1148 1149 1150
    if (res && (nch >= 2) && (TYPE(CHILD(tree, nch - 1)) == NAME)) {
	/*  (fpdef ['=' test] ',')*
	 *  ('*' NAME [',' '*' '*' NAME] | '*' '*' NAME)
	 */
1151
	int pos = 0;
1152
	int remaining = nch;
1153

1154 1155 1156 1157 1158 1159 1160 1161
	while (res && (TYPE(CHILD(tree, pos)) == fpdef)) {
	    res = validate_fpdef(CHILD(tree, pos));
	    if (res) {
		if (TYPE(CHILD(tree, pos + 1)) == EQUAL) {
		    res = validate_test(CHILD(tree, pos + 2));
		    pos += 2;
		}
		res = res && validate_comma(CHILD(tree, pos + 1));
1162 1163
		pos += 2;
	    }
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
	}
	if (res) {
	    remaining = nch - pos;
	    res = ((remaining == 2) || (remaining == 3)
		   || (remaining == 5) || (remaining == 6));
	    if (!res)
		validate_numnodes(tree, 2, "varargslist");
	    else if (TYPE(CHILD(tree, pos)) == DOUBLESTAR)
		return ((remaining == 2)
			&& validate_ntype(CHILD(tree, pos+1), NAME));
	    else {
		res = validate_star(CHILD(tree, pos++));
		--remaining;
1177 1178
	    }
	}
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
	if (res) {
	    if (remaining == 2) {
		res = (validate_star(CHILD(tree, pos))
		       && validate_ntype(CHILD(tree, pos + 1), NAME));
	    }
	    else {
		res = validate_ntype(CHILD(tree, pos++), NAME);
		if (res && (remaining >= 4)) {
		    res = validate_comma(CHILD(tree, pos));
		    if (--remaining == 3)
1189 1190
			res = (validate_star(CHILD(tree, pos + 1))
			       && validate_star(CHILD(tree, pos + 2)));
1191 1192 1193 1194 1195 1196 1197
		    else
			validate_ntype(CHILD(tree, pos + 1), DOUBLESTAR);
		}
	    }
	}
	if (!res && !PyErr_Occurred())
	    err_string("Incorrect validation of variable arguments list.");
1198
    }
1199 1200 1201 1202
    else if (res) {
	/*  fpdef ['=' test] (',' fpdef ['=' test])* [',']  */
	if (TYPE(CHILD(tree, nch - 1)) == COMMA)
	    --nch;
1203

1204 1205 1206
	/*  fpdef ['=' test] (',' fpdef ['=' test])*  */
	res = (is_odd(nch)
	       && validate_fpdef(CHILD(tree, 0)));
1207

1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
	if (res && (nch > 1)) {
	    int pos = 1;
	    if (TYPE(CHILD(tree, 1)) == EQUAL) {
		res = validate_test(CHILD(tree, 2));
		pos += 2;
	    }
	    /*  ... (',' fpdef ['=' test])*  */
	    for ( ; res && (pos < nch); pos += 2) {
		/* ',' fpdef */
		res = (validate_comma(CHILD(tree, pos))
		       && validate_fpdef(CHILD(tree, pos + 1)));
		if (res
		    && ((nch - pos) > 2)
		    && (TYPE(CHILD(tree, pos + 2)) == EQUAL)) {
		    /* ['=' test] */
		    res = validate_test(CHILD(tree, pos + 3));
		    pos += 2;
		}
	    }
1227 1228
	}
    }
1229 1230 1231
    else
	err_string("Improperly formed argument list.");

1232 1233 1234 1235 1236
    return (res);

}   /* validate_varargslist() */


1237 1238 1239 1240 1241 1242
/*  VALIDATE(fpdef)
 *
 *  fpdef:
 *	NAME
 *    | '(' fplist ')'
 */
Guido van Rossum's avatar
Guido van Rossum committed
1243
static int
1244 1245 1246
validate_fpdef(tree)
    node *tree;
{
1247
    int nch = NCH(tree);
1248
    int res = validate_ntype(tree, fpdef);
1249

1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
    if (res) {
	if (nch == 1)
	    res = validate_ntype(CHILD(tree, 0), NAME);
	else if (nch == 3)
	    res = (validate_lparen(CHILD(tree, 0))
		   && validate_fplist(CHILD(tree, 1))
		   && validate_rparen(CHILD(tree, 2)));
	else
	    validate_numnodes(tree, 1, "fpdef");
    }
    return (res);
1261 1262 1263 1264

} /* validate_fpdef() */


Guido van Rossum's avatar
Guido van Rossum committed
1265
static int
1266 1267 1268
validate_fplist(tree)
    node *tree;
{
Guido van Rossum's avatar
Guido van Rossum committed
1269 1270
    return (validate_repeating_list(tree, fplist,
				    validate_fpdef, "fplist"));
1271 1272 1273 1274

}   /* validate_fplist() */


1275 1276 1277
/*  simple_stmt | compound_stmt
 *
 */
Guido van Rossum's avatar
Guido van Rossum committed
1278
static int
1279 1280 1281 1282 1283
validate_stmt(tree)
    node *tree;
{
    int res = (validate_ntype(tree, stmt)
	       && validate_numnodes(tree, 1, "stmt"));
1284

1285 1286 1287 1288 1289 1290 1291 1292 1293
    if (res) {
	tree = CHILD(tree, 0);

	if (TYPE(tree) == simple_stmt)
	    res = validate_simple_stmt(tree);
	else
	    res = validate_compound_stmt(tree);
    }
    return (res);
1294 1295 1296 1297

}   /* validate_stmt() */


1298 1299 1300
/*  small_stmt (';' small_stmt)* [';'] NEWLINE
 *
 */
Guido van Rossum's avatar
Guido van Rossum committed
1301
static int
1302 1303 1304
validate_simple_stmt(tree)
    node *tree;
{
1305
    int nch = NCH(tree);
1306 1307
    int res = (validate_ntype(tree, simple_stmt)
	       && (nch >= 2)
1308 1309 1310
	       && validate_small_stmt(CHILD(tree, 0))
	       && validate_newline(CHILD(tree, nch - 1)));

1311 1312 1313 1314 1315
    if (nch < 2)
	res = validate_numnodes(tree, 2, "simple_stmt");
    --nch;				/* forget the NEWLINE	 */
    if (res && is_even(nch))
	res = validate_semi(CHILD(tree, --nch));
1316 1317 1318
    if (res && (nch > 2)) {
	int i;

1319
	for (i = 1; res && (i < nch); i += 2)
1320 1321 1322 1323 1324 1325 1326 1327
	    res = (validate_semi(CHILD(tree, i))
		   && validate_small_stmt(CHILD(tree, i + 1)));
    }
    return (res);

}   /* validate_simple_stmt() */


Guido van Rossum's avatar
Guido van Rossum committed
1328
static int
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
validate_small_stmt(tree)
    node *tree;
{
    int nch = NCH(tree);
    int	res = (validate_numnodes(tree, 1, "small_stmt")
	       && ((TYPE(CHILD(tree, 0)) == expr_stmt)
		   || (TYPE(CHILD(tree, 0)) == print_stmt)
		   || (TYPE(CHILD(tree, 0)) == del_stmt)
		   || (TYPE(CHILD(tree, 0)) == pass_stmt)
		   || (TYPE(CHILD(tree, 0)) == flow_stmt)
		   || (TYPE(CHILD(tree, 0)) == import_stmt)
		   || (TYPE(CHILD(tree, 0)) == global_stmt)
Guido van Rossum's avatar
Guido van Rossum committed
1341
		   || (TYPE(CHILD(tree, 0)) == assert_stmt)
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
		   || (TYPE(CHILD(tree, 0)) == exec_stmt)));

    if (res)
	res = validate_node(CHILD(tree, 0));
    else if (nch == 1) {
	char buffer[60];
	sprintf(buffer, "Unrecognized child node of small_stmt: %d.",
		TYPE(CHILD(tree, 0)));
	err_string(buffer);
    }
    return (res);

}   /* validate_small_stmt */


/*  compound_stmt:
 *	if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
 */
Guido van Rossum's avatar
Guido van Rossum committed
1360
static int
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
validate_compound_stmt(tree)
    node *tree;
{
    int res = (validate_ntype(tree, compound_stmt)
	       && validate_numnodes(tree, 1, "compound_stmt"));

    if (!res)
	return (0);

    tree = CHILD(tree, 0);
    res = ((TYPE(tree) == if_stmt)
	   || (TYPE(tree) == while_stmt)
	   || (TYPE(tree) == for_stmt)
	   || (TYPE(tree) == try_stmt)
	   || (TYPE(tree) == funcdef)
	   || (TYPE(tree) == classdef));
    if (res)
	res = validate_node(tree);
    else {
	char buffer[60];
	sprintf(buffer, "Illegal compound statement type: %d.", TYPE(tree));
	err_string(buffer);
    }
    return (res);

}   /* validate_compound_stmt() */


Guido van Rossum's avatar
Guido van Rossum committed
1389
static int
1390 1391 1392
validate_expr_stmt(tree)
    node *tree;
{
1393 1394
    int j;
    int nch = NCH(tree);
1395 1396 1397
    int res = (validate_ntype(tree, expr_stmt)
	       && is_odd(nch)
	       && validate_testlist(CHILD(tree, 0)));
1398

1399
    for (j = 1; res && (j < nch); j += 2)
1400 1401
	res = (validate_equal(CHILD(tree, j))
	       && validate_testlist(CHILD(tree, j + 1)));
1402

1403 1404 1405 1406 1407
    return (res);

}   /* validate_expr_stmt() */


1408 1409 1410 1411 1412
/*  print_stmt:
 *
 *	'print' (test ',')* [test]
 *
 */
Guido van Rossum's avatar
Guido van Rossum committed
1413
static int
1414 1415 1416
validate_print_stmt(tree)
    node *tree;
{
1417 1418
    int j;
    int nch = NCH(tree);
1419 1420 1421 1422 1423 1424 1425
    int res = (validate_ntype(tree, print_stmt)
	       && (nch != 0)
	       && validate_name(CHILD(tree, 0), "print"));

    if (res && is_even(nch)) {
	res = validate_test(CHILD(tree, nch - 1));
	--nch;
1426
    }
1427 1428 1429 1430 1431 1432
    else if (!res && !PyErr_Occurred())
	validate_numnodes(tree, 1, "print_stmt");
    for (j = 1; res && (j < nch); j += 2)
	res = (validate_test(CHILD(tree, j))
	       && validate_ntype(CHILD(tree, j + 1), COMMA));

1433 1434 1435 1436 1437
    return (res);

}   /* validate_print_stmt() */


Guido van Rossum's avatar
Guido van Rossum committed
1438
static int
1439 1440 1441 1442
validate_del_stmt(tree)
    node *tree;
{
    return (validate_numnodes(tree, 2, "del_stmt")
1443 1444 1445 1446 1447 1448
	    && validate_name(CHILD(tree, 0), "del")
	    && validate_exprlist(CHILD(tree, 1)));

}   /* validate_del_stmt() */


Guido van Rossum's avatar
Guido van Rossum committed
1449
static int
1450 1451 1452
validate_return_stmt(tree)
    node *tree;
{
1453
    int nch = NCH(tree);
1454 1455
    int res = (validate_ntype(tree, return_stmt)
	       && ((nch == 1) || (nch == 2))
1456 1457
	       && validate_name(CHILD(tree, 0), "return"));

1458 1459 1460
    if (res && (nch == 2))
	res = validate_testlist(CHILD(tree, 1));

1461 1462 1463 1464 1465
    return (res);

}   /* validate_return_stmt() */


Guido van Rossum's avatar
Guido van Rossum committed
1466
static int
1467 1468 1469
validate_raise_stmt(tree)
    node *tree;
{
1470
    int nch = NCH(tree);
1471 1472
    int res = (validate_ntype(tree, raise_stmt)
	       && ((nch == 2) || (nch == 4) || (nch == 6)));
1473

1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
    if (res) {
	res = (validate_name(CHILD(tree, 0), "raise")
	       && validate_test(CHILD(tree, 1)));
	if (res && nch > 2) {
	    res = (validate_comma(CHILD(tree, 2))
		   && validate_test(CHILD(tree, 3)));
	    if (res && (nch > 4))
		res = (validate_comma(CHILD(tree, 4))
		       && validate_test(CHILD(tree, 5)));
	}
    }
    else
	validate_numnodes(tree, 2, "raise");
    if (res && (nch == 4))
1488 1489
	res = (validate_comma(CHILD(tree, 2))
	       && validate_test(CHILD(tree, 3)));
1490

1491 1492 1493 1494 1495
    return (res);

}   /* validate_raise_stmt() */


1496 1497 1498 1499 1500
/*  import_stmt:
 *
 *    'import' dotted_name (',' dotted_name)*
 *  | 'from' dotted_name 'import' ('*' | NAME (',' NAME)*)
 */
Guido van Rossum's avatar
Guido van Rossum committed
1501
static int
1502 1503 1504
validate_import_stmt(tree)
    node *tree;
{
1505
    int nch = NCH(tree);
1506 1507
    int res = (validate_ntype(tree, import_stmt)
	       && (nch >= 2) && is_even(nch)
1508
	       && validate_ntype(CHILD(tree, 0), NAME)
1509
	       && validate_ntype(CHILD(tree, 1), dotted_name));
1510 1511

    if (res && (strcmp(STR(CHILD(tree, 0)), "import") == 0)) {
1512
	int j;
1513

1514 1515 1516
	for (j = 2; res && (j < nch); j += 2)
	    res = (validate_comma(CHILD(tree, j))
		   && validate_ntype(CHILD(tree, j + 1), dotted_name));
1517 1518
    }
    else if (res && validate_name(CHILD(tree, 0), "from")) {
1519
	res = ((nch >= 4) && is_even(nch)
1520 1521 1522
	       && validate_name(CHILD(tree, 2), "import"));
	if (nch == 4) {
	    res = ((TYPE(CHILD(tree, 3)) == NAME)
1523 1524 1525
		   || (TYPE(CHILD(tree, 3)) == STAR));
	    if (!res)
		err_string("Illegal import statement.");
1526 1527
	}
	else {
1528
	    /*  'from' NAME 'import' NAME (',' NAME)+  */
1529 1530
	    int j;
	    res = validate_ntype(CHILD(tree, 3), NAME);
1531
	    for (j = 4; res && (j < nch); j += 2)
1532 1533 1534 1535
		res = (validate_comma(CHILD(tree, j))
		       && validate_ntype(CHILD(tree, j + 1), NAME));
	}
    }
1536
    else
1537
	res = 0;
1538

1539 1540 1541 1542 1543
    return (res);

}   /* validate_import_stmt() */


Guido van Rossum's avatar
Guido van Rossum committed
1544
static int
1545 1546 1547
validate_global_stmt(tree)
    node *tree;
{
1548 1549
    int j;
    int nch = NCH(tree);
1550 1551
    int res = (validate_ntype(tree, global_stmt)
	       && is_even(nch) && (nch >= 2));
1552

1553 1554 1555 1556
    if (res)
	res = (validate_name(CHILD(tree, 0), "global")
	       && validate_ntype(CHILD(tree, 1), NAME));
    for (j = 2; res && (j < nch); j += 2)
1557 1558
	res = (validate_comma(CHILD(tree, j))
	       && validate_ntype(CHILD(tree, j + 1), NAME));
1559

1560 1561 1562 1563 1564
    return (res);

}   /* validate_global_stmt() */


1565 1566 1567 1568
/*  exec_stmt:
 *
 *  'exec' expr ['in' test [',' test]]
 */
Guido van Rossum's avatar
Guido van Rossum committed
1569
static int
1570 1571 1572
validate_exec_stmt(tree)
    node *tree;
{
1573
    int nch = NCH(tree);
1574 1575
    int res = (validate_ntype(tree, exec_stmt)
	       && ((nch == 2) || (nch == 4) || (nch == 6))
1576 1577 1578
	       && validate_name(CHILD(tree, 0), "exec")
	       && validate_expr(CHILD(tree, 1)));

1579 1580 1581
    if (!res && !PyErr_Occurred())
	err_string("Illegal exec statement.");
    if (res && (nch > 2))
1582 1583
	res = (validate_name(CHILD(tree, 2), "in")
	       && validate_test(CHILD(tree, 3)));
1584
    if (res && (nch == 6))
1585 1586
	res = (validate_comma(CHILD(tree, 4))
	       && validate_test(CHILD(tree, 5)));
1587

1588 1589 1590 1591 1592
    return (res);

}   /* validate_exec_stmt() */


Guido van Rossum's avatar
Guido van Rossum committed
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
/*  assert_stmt:
 *
 *  'assert' test [',' test]
 */
static int
validate_assert_stmt(tree)
    node *tree;
{
    int nch = NCH(tree);
    int res = (validate_ntype(tree, assert_stmt)
	       && ((nch == 2) || (nch == 4))
	       && (validate_name(CHILD(tree, 0), "__assert__") ||
		   validate_name(CHILD(tree, 0), "assert"))
	       && validate_test(CHILD(tree, 1)));

    if (!res && !PyErr_Occurred())
	err_string("Illegal assert statement.");
    if (res && (nch > 2))
	res = (validate_comma(CHILD(tree, 2))
	       && validate_test(CHILD(tree, 3)));

    return (res);

}   /* validate_assert_stmt() */


Guido van Rossum's avatar
Guido van Rossum committed
1619
static int
1620 1621 1622
validate_while(tree)
    node *tree;
{
1623
    int nch = NCH(tree);
1624 1625
    int res = (validate_ntype(tree, while_stmt)
	       && ((nch == 4) || (nch == 7))
1626 1627 1628 1629 1630
	       && validate_name(CHILD(tree, 0), "while")
	       && validate_test(CHILD(tree, 1))
	       && validate_colon(CHILD(tree, 2))
	       && validate_suite(CHILD(tree, 3)));

1631
    if (res && (nch == 7))
1632 1633 1634
	res = (validate_name(CHILD(tree, 4), "else")
	       && validate_colon(CHILD(tree, 5))
	       && validate_suite(CHILD(tree, 6)));
1635

1636 1637 1638 1639 1640
    return (res);

}   /* validate_while() */


Guido van Rossum's avatar
Guido van Rossum committed
1641
static int
1642 1643 1644
validate_for(tree)
    node *tree;
{
1645
    int nch = NCH(tree);
1646 1647
    int res = (validate_ntype(tree, for_stmt)
	       && ((nch == 6) || (nch == 9))
1648 1649 1650 1651 1652 1653 1654
	       && validate_name(CHILD(tree, 0), "for")
	       && validate_exprlist(CHILD(tree, 1))
	       && validate_name(CHILD(tree, 2), "in")
	       && validate_testlist(CHILD(tree, 3))
	       && validate_colon(CHILD(tree, 4))
	       && validate_suite(CHILD(tree, 5)));

1655
    if (res && (nch == 9))
1656 1657 1658
	res = (validate_name(CHILD(tree, 6), "else")
	       && validate_colon(CHILD(tree, 7))
	       && validate_suite(CHILD(tree, 8)));
1659

1660 1661 1662 1663 1664
    return (res);

}   /* validate_for() */


1665 1666 1667 1668 1669
/*  try_stmt:
 *	'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
 *    | 'try' ':' suite 'finally' ':' suite
 *
 */
Guido van Rossum's avatar
Guido van Rossum committed
1670
static int
1671 1672 1673
validate_try(tree)
    node *tree;
{
1674
    int nch = NCH(tree);
1675 1676 1677 1678 1679 1680
    int pos = 3;
    int res = (validate_ntype(tree, try_stmt)
	       && (nch >= 6) && ((nch % 3) == 0));

    if (res)
	res = (validate_name(CHILD(tree, 0), "try")
1681 1682 1683 1684
	       && validate_colon(CHILD(tree, 1))
	       && validate_suite(CHILD(tree, 2))
	       && validate_colon(CHILD(tree, nch - 2))
	       && validate_suite(CHILD(tree, nch - 1)));
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711
    else {
	const char* name = "execpt";
	char buffer[60];
	if (TYPE(CHILD(tree, nch - 3)) != except_clause)
	    name = STR(CHILD(tree, nch - 3));
	sprintf(buffer, "Illegal number of children for try/%s node.", name);
	err_string(buffer);
    }
    /*	Skip past except_clause sections:  */
    while (res && (TYPE(CHILD(tree, pos)) == except_clause)) {
	res = (validate_except_clause(CHILD(tree, pos))
	       && validate_colon(CHILD(tree, pos + 1))
	       && validate_suite(CHILD(tree, pos + 2)));
	pos += 3;
    }
    if (res && (pos < nch)) {
	res = validate_ntype(CHILD(tree, pos), NAME);
	if (res && (strcmp(STR(CHILD(tree, pos)), "finally") == 0))
	    res = (validate_numnodes(tree, 6, "try/finally")
		   && validate_colon(CHILD(tree, 4))
		   && validate_suite(CHILD(tree, 5)));
	else if (res)
	    if (nch == (pos + 3)) {
		res = ((strcmp(STR(CHILD(tree, pos)), "except") == 0)
		       || (strcmp(STR(CHILD(tree, pos)), "else") == 0));
		if (!res)
		    err_string("Illegal trailing triple in try statement.");
1712
	    }
1713 1714 1715 1716 1717 1718 1719
	    else if (nch == (pos + 6))
		res = (validate_name(CHILD(tree, pos), "except")
		       && validate_colon(CHILD(tree, pos + 1))
		       && validate_suite(CHILD(tree, pos + 2))
		       && validate_name(CHILD(tree, pos + 3), "else"));
	    else
		res = validate_numnodes(tree, pos + 3, "try/except");
1720 1721 1722 1723 1724 1725
    }
    return (res);

}   /* validate_try() */


Guido van Rossum's avatar
Guido van Rossum committed
1726
static int
1727 1728 1729
validate_except_clause(tree)
    node *tree;
{
1730
    int nch = NCH(tree);
1731 1732
    int res = (validate_ntype(tree, except_clause)
	       && ((nch == 1) || (nch == 2) || (nch == 4))
1733 1734
	       && validate_name(CHILD(tree, 0), "except"));

1735 1736 1737
    if (res && (nch > 1))
	res = validate_test(CHILD(tree, 1));
    if (res && (nch == 4))
1738 1739
	res = (validate_comma(CHILD(tree, 2))
	       && validate_test(CHILD(tree, 3)));
1740

1741 1742 1743 1744 1745
    return (res);

}   /* validate_except_clause() */


Guido van Rossum's avatar
Guido van Rossum committed
1746
static int
1747 1748 1749
validate_test(tree)
    node *tree;
{
1750
    int nch = NCH(tree);
1751
    int res = validate_ntype(tree, test) && is_odd(nch);
1752

1753
    if (res && (TYPE(CHILD(tree, 0)) == lambdef))
1754 1755 1756 1757
	res = ((nch == 1)
	       && validate_lambdef(CHILD(tree, 0)));
    else if (res) {
	int pos;
1758 1759 1760
	res = validate_and_test(CHILD(tree, 0));
	for (pos = 1; res && (pos < nch); pos += 2)
	    res = (validate_name(CHILD(tree, pos), "or")
1761 1762 1763 1764 1765 1766 1767
		   && validate_and_test(CHILD(tree, pos + 1)));
    }
    return (res);

}   /* validate_test() */


Guido van Rossum's avatar
Guido van Rossum committed
1768
static int
1769 1770 1771
validate_and_test(tree)
    node *tree;
{
1772 1773
    int pos;
    int nch = NCH(tree);
1774 1775
    int res = (validate_ntype(tree, and_test)
	       && is_odd(nch)
1776 1777
	       && validate_not_test(CHILD(tree, 0)));

1778
    for (pos = 1; res && (pos < nch); pos += 2)
1779 1780
	res = (validate_name(CHILD(tree, pos), "and")
	       && validate_not_test(CHILD(tree, 0)));
1781

1782 1783 1784 1785 1786
    return (res);

}   /* validate_and_test() */


Guido van Rossum's avatar
Guido van Rossum committed
1787
static int
1788 1789 1790
validate_not_test(tree)
    node *tree;
{
1791
    int nch = NCH(tree);
1792
    int res = validate_ntype(tree, not_test) && ((nch == 1) || (nch == 2));
1793

1794 1795 1796 1797 1798 1799 1800 1801
    if (res) {
	if (nch == 2)
	    res = (validate_name(CHILD(tree, 0), "not")
		   && validate_not_test(CHILD(tree, 1)));
	else if (nch == 1)
	    res = validate_comparison(CHILD(tree, 0));
    }
    return (res);
1802 1803 1804 1805

}   /* validate_not_test() */


Guido van Rossum's avatar
Guido van Rossum committed
1806
static int
1807 1808 1809
validate_comparison(tree)
    node *tree;
{
1810 1811
    int pos;
    int nch = NCH(tree);
1812 1813
    int res = (validate_ntype(tree, comparison)
	       && is_odd(nch)
1814 1815
	       && validate_expr(CHILD(tree, 0)));

1816 1817 1818 1819
    for (pos = 1; res && (pos < nch); pos += 2)
	res = (validate_comp_op(CHILD(tree, pos))
	       && validate_expr(CHILD(tree, pos + 1)));

1820 1821 1822 1823 1824
    return (res);

}   /* validate_comparison() */


Guido van Rossum's avatar
Guido van Rossum committed
1825
static int
1826 1827 1828
validate_comp_op(tree)
    node *tree;
{
1829 1830 1831
    int res = 0;
    int nch = NCH(tree);

1832 1833
    if (!validate_ntype(tree, comp_op))
	return (0);
1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
    if (nch == 1) {
	/*
	 *  Only child will be a terminal with a well-defined symbolic name
	 *  or a NAME with a string of either 'is' or 'in'
	 */
	tree = CHILD(tree, 0);
	switch (TYPE(tree)) {
	    case LESS:
	    case GREATER:
	    case EQEQUAL:
	    case EQUAL:
	    case LESSEQUAL:
	    case GREATEREQUAL:
	    case NOTEQUAL:
	      res = 1;
	      break;
	    case NAME:
	      res = ((strcmp(STR(tree), "in") == 0)
		     || (strcmp(STR(tree), "is") == 0));
	      if (!res) {
1854 1855 1856
		  char buff[128];
		  sprintf(buff, "Illegal operator: '%s'.", STR(tree));
		  err_string(buff);
1857 1858 1859
	      }
	      break;
	  default:
1860
	      err_string("Illegal comparison operator type.");
1861 1862 1863
	      break;
	}
    }
Guido van Rossum's avatar
Guido van Rossum committed
1864
    else if ((res = validate_numnodes(tree, 2, "comp_op")) != 0) {
1865 1866 1867 1868 1869 1870
	res = (validate_ntype(CHILD(tree, 0), NAME)
	       && validate_ntype(CHILD(tree, 1), NAME)
	       && (((strcmp(STR(CHILD(tree, 0)), "is") == 0)
		    && (strcmp(STR(CHILD(tree, 1)), "not") == 0))
		   || ((strcmp(STR(CHILD(tree, 0)), "not") == 0)
		       && (strcmp(STR(CHILD(tree, 1)), "in") == 0))));
1871 1872
	if (!res && !PyErr_Occurred())
	    err_string("Unknown comparison operator.");
1873 1874 1875 1876 1877 1878
    }
    return (res);

}   /* validate_comp_op() */


Guido van Rossum's avatar
Guido van Rossum committed
1879
static int
1880 1881 1882
validate_expr(tree)
    node *tree;
{
1883 1884
    int j;
    int nch = NCH(tree);
1885 1886
    int res = (validate_ntype(tree, expr)
	       && is_odd(nch)
1887 1888
	       && validate_xor_expr(CHILD(tree, 0)));

1889 1890
    for (j = 2; res && (j < nch); j += 2)
	res = (validate_xor_expr(CHILD(tree, j))
1891
	       && validate_vbar(CHILD(tree, j - 1)));
1892

1893 1894 1895 1896 1897
    return (res);

}   /* validate_expr() */


Guido van Rossum's avatar
Guido van Rossum committed
1898
static int
1899 1900 1901
validate_xor_expr(tree)
    node *tree;
{
1902 1903
    int j;
    int nch = NCH(tree);
1904 1905
    int res = (validate_ntype(tree, xor_expr)
	       && is_odd(nch)
1906 1907
	       && validate_and_expr(CHILD(tree, 0)));

1908
    for (j = 2; res && (j < nch); j += 2)
1909 1910
	res = (validate_circumflex(CHILD(tree, j - 1))
	       && validate_and_expr(CHILD(tree, j)));
1911

1912 1913 1914 1915 1916
    return (res);

}   /* validate_xor_expr() */


Guido van Rossum's avatar
Guido van Rossum committed
1917
static int
1918 1919 1920
validate_and_expr(tree)
    node *tree;
{
1921 1922
    int pos;
    int nch = NCH(tree);
1923 1924
    int res = (validate_ntype(tree, and_expr)
	       && is_odd(nch)
1925 1926
	       && validate_shift_expr(CHILD(tree, 0)));

1927
    for (pos = 1; res && (pos < nch); pos += 2)
1928 1929
	res = (validate_ampersand(CHILD(tree, pos))
	       && validate_shift_expr(CHILD(tree, pos + 1)));
1930

1931 1932 1933 1934 1935 1936
    return (res);

}   /* validate_and_expr() */


static int
1937 1938 1939 1940 1941 1942 1943
validate_chain_two_ops(tree, termvalid, op1, op2)
     node *tree;
     int (*termvalid)();
     int op1;
     int op2;
 {
    int pos = 1;
1944 1945 1946 1947
    int nch = NCH(tree);
    int res = (is_odd(nch)
	       && (*termvalid)(CHILD(tree, 0)));

1948 1949 1950 1951 1952
    for ( ; res && (pos < nch); pos += 2) {
	if (TYPE(CHILD(tree, pos)) != op1)
	    res = validate_ntype(CHILD(tree, pos), op2);
	if (res)
	    res = (*termvalid)(CHILD(tree, pos + 1));
1953 1954 1955 1956 1957 1958
    }
    return (res);

}   /* validate_chain_two_ops() */


Guido van Rossum's avatar
Guido van Rossum committed
1959
static int
1960 1961 1962 1963 1964 1965
validate_shift_expr(tree)
    node *tree;
{
    return (validate_ntype(tree, shift_expr)
	    && validate_chain_two_ops(tree, validate_arith_expr,
				      LEFTSHIFT, RIGHTSHIFT));
1966 1967 1968 1969

}   /* validate_shift_expr() */


Guido van Rossum's avatar
Guido van Rossum committed
1970
static int
1971 1972 1973 1974 1975
validate_arith_expr(tree)
    node *tree;
{
    return (validate_ntype(tree, arith_expr)
	    && validate_chain_two_ops(tree, validate_term, PLUS, MINUS));
1976 1977 1978 1979

}   /* validate_arith_expr() */


Guido van Rossum's avatar
Guido van Rossum committed
1980
static int
1981 1982 1983 1984
validate_term(tree)
    node *tree;
{
    int pos = 1;
1985
    int nch = NCH(tree);
1986 1987
    int res = (validate_ntype(tree, term)
	       && is_odd(nch)
1988 1989
	       && validate_factor(CHILD(tree, 0)));

1990 1991
    for ( ; res && (pos < nch); pos += 2)
	res = (((TYPE(CHILD(tree, pos)) == STAR)
1992
	       || (TYPE(CHILD(tree, pos)) == SLASH)
1993 1994 1995
	       || (TYPE(CHILD(tree, pos)) == PERCENT))
	       && validate_factor(CHILD(tree, pos + 1)));

1996 1997 1998 1999 2000
    return (res);

}   /* validate_term() */


2001 2002 2003 2004
/*  factor:
 *
 *  factor: ('+'|'-'|'~') factor | power
 */
Guido van Rossum's avatar
Guido van Rossum committed
2005
static int
2006 2007 2008
validate_factor(tree)
    node *tree;
{
2009
    int nch = NCH(tree);
2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
    int res = (validate_ntype(tree, factor)
	       && (((nch == 2)
		    && ((TYPE(CHILD(tree, 0)) == PLUS)
		        || (TYPE(CHILD(tree, 0)) == MINUS)
		        || (TYPE(CHILD(tree, 0)) == TILDE))
		    && validate_factor(CHILD(tree, 1)))
		   || ((nch == 1)
		       && validate_power(CHILD(tree, 0)))));
    return (res);

}   /* validate_factor() */
2021

2022 2023 2024 2025 2026

/*  power:
 *
 *  power: atom trailer* ('**' factor)*
 */
Guido van Rossum's avatar
Guido van Rossum committed
2027
static int
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041
validate_power(tree)
    node *tree;
{
    int pos = 1;
    int nch = NCH(tree);
    int res = (validate_ntype(tree, power) && (nch >= 1)
	       && validate_atom(CHILD(tree, 0)));

    while (res && (pos < nch) && (TYPE(CHILD(tree, pos)) == trailer))
	res = validate_trailer(CHILD(tree, pos++));
    if (res && (pos < nch)) {
	if (!is_even(nch - pos)) {
	    err_string("Illegal number of nodes for 'power'.");
	    return (0);
2042
	}
2043 2044 2045
	for ( ; res && (pos < (nch - 1)); pos += 2)
	    res = (validate_doublestar(CHILD(tree, pos))
		   && validate_factor(CHILD(tree, pos + 1)));
2046 2047 2048
    }
    return (res);

2049
}   /* validate_power() */
2050 2051


Guido van Rossum's avatar
Guido van Rossum committed
2052
static int
2053 2054 2055
validate_atom(tree)
    node *tree;
{
2056 2057
    int pos;
    int nch = NCH(tree);
2058
    int res = validate_ntype(tree, atom) && (nch >= 1);
2059 2060 2061 2062 2063 2064 2065

    if (res) {
	switch (TYPE(CHILD(tree, 0))) {
	  case LPAR:
	    res = ((nch <= 3)
		   && (validate_rparen(CHILD(tree, nch - 1))));

2066 2067
	    if (res && (nch == 3))
		res = validate_testlist(CHILD(tree, 1));
2068 2069 2070 2071 2072
	    break;
	  case LSQB:
	    res = ((nch <= 3)
		   && validate_ntype(CHILD(tree, nch - 1), RSQB));

2073 2074
	    if (res && (nch == 3))
		res = validate_testlist(CHILD(tree, 1));
2075 2076 2077 2078 2079
	    break;
	  case LBRACE:
	    res = ((nch <= 3)
		   && validate_ntype(CHILD(tree, nch - 1), RBRACE));

2080 2081
	    if (res && (nch == 3))
		res = validate_dictmaker(CHILD(tree, 1));
2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092
	    break;
	  case BACKQUOTE:
	    res = ((nch == 3)
		   && validate_testlist(CHILD(tree, 1))
		   && validate_ntype(CHILD(tree, 2), BACKQUOTE));
	    break;
	  case NAME:
	  case NUMBER:
	    res = (nch == 1);
	    break;
	  case STRING:
2093
	    for (pos = 1; res && (pos < nch); ++pos)
2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105
		res = validate_ntype(CHILD(tree, pos), STRING);
	    break;
	  default:
	    res = 0;
	    break;
	}
    }
    return (res);

}   /* validate_atom() */


2106 2107 2108 2109
/*  funcdef:
 *	'def' NAME parameters ':' suite
 *
 */
Guido van Rossum's avatar
Guido van Rossum committed
2110
static int
2111 2112 2113 2114 2115
validate_funcdef(tree)
    node *tree;
{
    return (validate_ntype(tree, funcdef)
	    && validate_numnodes(tree, 5, "funcdef")
2116 2117 2118 2119 2120 2121 2122 2123 2124
	    && validate_name(CHILD(tree, 0), "def")
	    && validate_ntype(CHILD(tree, 1), NAME)
	    && validate_colon(CHILD(tree, 3))
	    && validate_parameters(CHILD(tree, 2))
	    && validate_suite(CHILD(tree, 4)));

}   /* validate_funcdef() */


Guido van Rossum's avatar
Guido van Rossum committed
2125
static int
2126 2127 2128
validate_lambdef(tree)
    node *tree;
{
2129
    int nch = NCH(tree);
2130 2131
    int res = (validate_ntype(tree, lambdef)
	       && ((nch == 3) || (nch == 4))
2132 2133
	       && validate_name(CHILD(tree, 0), "lambda")
	       && validate_colon(CHILD(tree, nch - 2))
2134 2135 2136 2137 2138 2139
	       && validate_test(CHILD(tree, nch - 1)));

    if (res && (nch == 4))
	res = validate_varargslist(CHILD(tree, 1));
    else if (!res && !PyErr_Occurred())
	validate_numnodes(tree, 3, "lambdef");
2140 2141 2142 2143 2144 2145

    return (res);

}   /* validate_lambdef() */


2146 2147 2148 2149
/*  arglist:
 *
 *  argument (',' argument)* [',']
 */
Guido van Rossum's avatar
Guido van Rossum committed
2150
static int
2151 2152 2153
validate_arglist(tree)
    node *tree;
{
Guido van Rossum's avatar
Guido van Rossum committed
2154 2155
    return (validate_repeating_list(tree, arglist,
				    validate_argument, "arglist"));
2156 2157 2158 2159 2160 2161 2162 2163 2164

}   /* validate_arglist() */



/*  argument:
 *
 *  [test '='] test
 */
Guido van Rossum's avatar
Guido van Rossum committed
2165
static int
2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185
validate_argument(tree)
    node *tree;
{
    int nch = NCH(tree);
    int res = (validate_ntype(tree, argument)
	       && ((nch == 1) || (nch == 3))
	       && validate_test(CHILD(tree, 0)));

    if (res && (nch == 3))
	res = (validate_equal(CHILD(tree, 1))
	       && validate_test(CHILD(tree, 2)));

    return (res);

}   /* validate_argument() */



/*  trailer:
 *
Guido van Rossum's avatar
Guido van Rossum committed
2186
 *  '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
2187
 */
Guido van Rossum's avatar
Guido van Rossum committed
2188
static int
2189 2190 2191 2192 2193
validate_trailer(tree)
    node *tree;
{
    int nch = NCH(tree);
    int res = validate_ntype(tree, trailer) && ((nch == 2) || (nch == 3));
2194 2195 2196 2197 2198

    if (res) {
	switch (TYPE(CHILD(tree, 0))) {
	  case LPAR:
	    res = validate_rparen(CHILD(tree, nch - 1));
2199 2200
	    if (res && (nch == 3))
		res = validate_arglist(CHILD(tree, 1));
2201 2202
	    break;
	  case LSQB:
2203
	    res = (validate_numnodes(tree, 3, "trailer")
Guido van Rossum's avatar
Guido van Rossum committed
2204
		   && validate_subscriptlist(CHILD(tree, 1))
2205 2206 2207
		   && validate_ntype(CHILD(tree, 2), RSQB));
	    break;
	  case DOT:
2208
	    res = (validate_numnodes(tree, 2, "trailer")
2209 2210 2211 2212 2213 2214 2215
		   && validate_ntype(CHILD(tree, 1), NAME));
	    break;
	  default:
	    res = 0;
	    break;
	}
    }
2216 2217 2218
    else
	validate_numnodes(tree, 2, "trailer");

2219 2220 2221 2222 2223
    return (res);

}   /* validate_trailer() */


Guido van Rossum's avatar
Guido van Rossum committed
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237
/*  subscriptlist:
 *
 *  subscript (',' subscript)* [',']
 */
static int
validate_subscriptlist(tree)
    node *tree;
{
    return (validate_repeating_list(tree, subscriptlist,
				    validate_subscript, "subscriptlist"));

}   /* validate_subscriptlist() */


2238 2239
/*  subscript:
 *
Guido van Rossum's avatar
Guido van Rossum committed
2240
 *  '.' '.' '.' | test | [test] ':' [test] [sliceop]
2241
 */
Guido van Rossum's avatar
Guido van Rossum committed
2242
static int
2243 2244 2245
validate_subscript(tree)
    node *tree;
{
Guido van Rossum's avatar
Guido van Rossum committed
2246
    int offset = 0;
2247
    int nch = NCH(tree);
Guido van Rossum's avatar
Guido van Rossum committed
2248
    int res = validate_ntype(tree, subscript) && (nch >= 1) && (nch <= 4);
2249

Guido van Rossum's avatar
Guido van Rossum committed
2250 2251 2252 2253
    if (!res) {
	if (!PyErr_Occurred())
	    err_string("invalid number of arguments for subscript node");
	return (0);
2254
    }
Guido van Rossum's avatar
Guido van Rossum committed
2255 2256 2257 2258 2259 2260 2261 2262
    if (TYPE(CHILD(tree, 0)) == DOT)
	/* take care of ('.' '.' '.') possibility */
	return (validate_numnodes(tree, 3, "subscript")
		&& validate_dot(CHILD(tree, 0))
		&& validate_dot(CHILD(tree, 1))
		&& validate_dot(CHILD(tree, 2)));
    if (nch == 1) {
	if (TYPE(CHILD(tree, 0)) == test)
2263 2264
	    res = validate_test(CHILD(tree, 0));
	else
Guido van Rossum's avatar
Guido van Rossum committed
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288
	    res = validate_colon(CHILD(tree, 0));
	return (res);
    }
    /*	Must be [test] ':' [test] [sliceop],
     *	but at least one of the optional components will
     *	be present, but we don't know which yet.
     */
    if ((TYPE(CHILD(tree, 0)) != COLON) || (nch == 4)) {
	res = validate_test(CHILD(tree, 0));
	offset = 1;
    }
    if (res)
	res = validate_colon(CHILD(tree, offset));
    if (res) {
	int rem = nch - ++offset;
	if (rem) {
	    if (TYPE(CHILD(tree, offset)) == test) {
		res = validate_test(CHILD(tree, offset));
		++offset;
		--rem;
	    }
	    if (res && rem)
		res = validate_sliceop(CHILD(tree, offset));
	}
2289
    }
2290 2291 2292 2293 2294
    return (res);

}   /* validate_subscript() */


Guido van Rossum's avatar
Guido van Rossum committed
2295 2296
static int
validate_sliceop(tree)
2297 2298
    node *tree;
{
2299
    int nch = NCH(tree);
Guido van Rossum's avatar
Guido van Rossum committed
2300 2301 2302 2303 2304
    int res = ((nch == 1) || validate_numnodes(tree, 2, "sliceop"))
	      && validate_ntype(tree, sliceop);
    if (!res && !PyErr_Occurred()) {
	validate_numnodes(tree, 1, "sliceop");
	res = 0;
2305
    }
Guido van Rossum's avatar
Guido van Rossum committed
2306 2307 2308 2309 2310
    if (res)
	res = validate_colon(CHILD(tree, 0));
    if (res && (nch == 2))
	res = validate_test(CHILD(tree, 1));

2311 2312
    return (res);

Guido van Rossum's avatar
Guido van Rossum committed
2313 2314 2315 2316 2317 2318 2319 2320 2321 2322
}   /* validate_sliceop() */


static int
validate_exprlist(tree)
    node *tree;
{
    return (validate_repeating_list(tree, exprlist,
				    validate_expr, "exprlist"));

2323 2324 2325
}   /* validate_exprlist() */


Guido van Rossum's avatar
Guido van Rossum committed
2326
static int
2327 2328 2329
validate_dictmaker(tree)
    node *tree;
{
2330
    int nch = NCH(tree);
2331 2332
    int res = (validate_ntype(tree, dictmaker)
	       && (nch >= 3)
2333 2334 2335 2336
	       && validate_test(CHILD(tree, 0))
	       && validate_colon(CHILD(tree, 1))
	       && validate_test(CHILD(tree, 2)));

2337
    if (res && ((nch % 4) == 0))
2338
	res = validate_comma(CHILD(tree, --nch));
2339
    else if (res)
2340
	res = ((nch % 4) == 3);
2341

2342 2343
    if (res && (nch > 3)) {
	int pos = 3;
2344
	/*  ( ',' test ':' test )*  */
2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357
	while (res && (pos < nch)) {
	    res = (validate_comma(CHILD(tree, pos))
		   && validate_test(CHILD(tree, pos + 1))
		   && validate_colon(CHILD(tree, pos + 2))
		   && validate_test(CHILD(tree, pos + 3)));
	    pos += 4;
	}
    }
    return (res);

}   /* validate_dictmaker() */


Guido van Rossum's avatar
Guido van Rossum committed
2358
static int
2359 2360 2361
validate_eval_input(tree)
    node *tree;
{
2362 2363
    int pos;
    int nch = NCH(tree);
2364 2365
    int res = (validate_ntype(tree, eval_input)
	       && (nch >= 2)
2366 2367 2368
	       && validate_testlist(CHILD(tree, 0))
	       && validate_ntype(CHILD(tree, nch - 1), ENDMARKER));

2369
    for (pos = 1; res && (pos < (nch - 1)); ++pos)
2370
	res = validate_ntype(CHILD(tree, pos), NEWLINE);
2371

2372 2373 2374 2375 2376
    return (res);

}   /* validate_eval_input() */


Guido van Rossum's avatar
Guido van Rossum committed
2377
static int
2378 2379 2380
validate_node(tree)
    node *tree;
{
2381 2382 2383
    int   nch  = 0;			/* num. children on current node  */
    int   res  = 1;			/* result value			  */
    node* next = 0;			/* node to process after this one */
2384

2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399
    while (res & (tree != 0)) {
	nch  = NCH(tree);
	next = 0;
	switch (TYPE(tree)) {
	    /*
	     *  Definition nodes.
	     */
	  case funcdef:
	    res = validate_funcdef(tree);
	    break;
	  case classdef:
	    res = validate_class(tree);
	    break;
	    /*
	     *  "Trivial" parse tree nodes.
2400
	     *  (Why did I call these trivial?)
2401 2402 2403 2404 2405
	     */
	  case stmt:
	    res = validate_stmt(tree);
	    break;
	  case small_stmt:
2406 2407
	    /*
	     *  expr_stmt | print_stmt  | del_stmt | pass_stmt | flow_stmt
Guido van Rossum's avatar
Guido van Rossum committed
2408
	     *  | import_stmt | global_stmt | exec_stmt | assert_stmt
2409 2410
	     */
	    res = validate_small_stmt(tree);
2411 2412
	    break;
	  case flow_stmt:
2413
	    res  = (validate_numnodes(tree, 1, "flow_stmt")
2414 2415 2416
		    && ((TYPE(CHILD(tree, 0)) == break_stmt)
			|| (TYPE(CHILD(tree, 0)) == continue_stmt)
			|| (TYPE(CHILD(tree, 0)) == return_stmt)
2417 2418 2419 2420 2421
			|| (TYPE(CHILD(tree, 0)) == raise_stmt)));
	    if (res)
		next = CHILD(tree, 0);
	    else if (nch == 1)
		err_string("Illegal flow_stmt type.");
2422 2423 2424 2425 2426 2427 2428 2429
	    break;
	    /*
	     *  Compound statements.
	     */
	  case simple_stmt:
	    res = validate_simple_stmt(tree);
	    break;
	  case compound_stmt:
2430
	    res = validate_compound_stmt(tree);
2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444
	    break;
	    /*
	     *  Fundemental statements.
	     */
	  case expr_stmt:
	    res = validate_expr_stmt(tree);
	    break;
	  case print_stmt:
	    res = validate_print_stmt(tree);
	    break;
	  case del_stmt:
	    res = validate_del_stmt(tree);
	    break;
	  case pass_stmt:
2445
	    res = (validate_numnodes(tree, 1, "pass")
2446 2447 2448
		   && validate_name(CHILD(tree, 0), "pass"));
	    break;
	  case break_stmt:
2449
	    res = (validate_numnodes(tree, 1, "break")
2450 2451 2452
		   && validate_name(CHILD(tree, 0), "break"));
	    break;
	  case continue_stmt:
2453
	    res = (validate_numnodes(tree, 1, "continue")
2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470
		   && validate_name(CHILD(tree, 0), "continue"));
	    break;
	  case return_stmt:
	    res = validate_return_stmt(tree);
	    break;
	  case raise_stmt:
	    res = validate_raise_stmt(tree);
	    break;
	  case import_stmt:
	    res = validate_import_stmt(tree);
	    break;
	  case global_stmt:
	    res = validate_global_stmt(tree);
	    break;
	  case exec_stmt:
	    res = validate_exec_stmt(tree);
	    break;
Guido van Rossum's avatar
Guido van Rossum committed
2471 2472 2473
	  case assert_stmt:
	    res = validate_assert_stmt(tree);
	    break;
2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509
	  case if_stmt:
	    res = validate_if(tree);
	    break;
	  case while_stmt:
	    res = validate_while(tree);
	    break;
	  case for_stmt:
	    res = validate_for(tree);
	    break;
	  case try_stmt:
	    res = validate_try(tree);
	    break;
	  case suite:
	    res = validate_suite(tree);
	    break;
	    /*
	     *  Expression nodes.
	     */
	  case testlist:
	    res = validate_testlist(tree);
	    break;
	  case test:
	    res = validate_test(tree);
	    break;
	  case and_test:
	    res = validate_and_test(tree);
	    break;
	  case not_test:
	    res = validate_not_test(tree);
	    break;
	  case comparison:
	    res = validate_comparison(tree);
	    break;
	  case exprlist:
	    res = validate_exprlist(tree);
	    break;
2510 2511 2512
	  case comp_op:
	    res = validate_comp_op(tree);
	    break;
2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533
	  case expr:
	    res = validate_expr(tree);
	    break;
	  case xor_expr:
	    res = validate_xor_expr(tree);
	    break;
	  case and_expr:
	    res = validate_and_expr(tree);
	    break;
	  case shift_expr:
	    res = validate_shift_expr(tree);
	    break;
	  case arith_expr:
	    res = validate_arith_expr(tree);
	    break;
	  case term:
	    res = validate_term(tree);
	    break;
	  case factor:
	    res = validate_factor(tree);
	    break;
2534 2535 2536
	  case power:
	    res = validate_power(tree);
	    break;
2537 2538 2539
	  case atom:
	    res = validate_atom(tree);
	    break;
2540

2541 2542
	  default:
	    /* Hopefully never reached! */
2543
	    err_string("Unrecogniged node type.");
2544 2545 2546 2547 2548 2549 2550 2551 2552 2553
	    res = 0;
	    break;
	}
	tree = next;
    }
    return (res);

}   /* validate_node() */


Guido van Rossum's avatar
Guido van Rossum committed
2554
static int
2555 2556 2557 2558 2559 2560 2561 2562 2563
validate_expr_tree(tree)
    node *tree;
{
    int res = validate_eval_input(tree);

    if (!res && !PyErr_Occurred())
	err_string("Could not validate expression tuple.");

    return (res);
2564 2565 2566 2567

}   /* validate_expr_tree() */


2568 2569 2570
/*  file_input:
 *	(NEWLINE | stmt)* ENDMARKER
 */
Guido van Rossum's avatar
Guido van Rossum committed
2571
static int
2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584
validate_file_input(tree)
    node *tree;
{
    int j   = 0;
    int nch = NCH(tree) - 1;
    int res = ((nch >= 0)
	       && validate_ntype(CHILD(tree, nch), ENDMARKER));

    for ( ; res && (j < nch); ++j) {
	if (TYPE(CHILD(tree, j)) == stmt)
	    res = validate_stmt(CHILD(tree, j));
	else
	    res = validate_newline(CHILD(tree, j));
2585
    }
2586 2587 2588 2589 2590 2591 2592
    /*	This stays in to prevent any internal failues from getting to the
     *	user.  Hopefully, this won't be needed.  If a user reports getting
     *	this, we have some debugging to do.
     */
    if (!res && !PyErr_Occurred())
	err_string("VALIDATION FAILURE: report this to the maintainer!.");

2593 2594
    return (res);

2595
}   /* validate_file_input() */
2596 2597 2598 2599 2600


/*  Functions exported by this module.  Most of this should probably
 *  be converted into an AST object with methods, but that is better
 *  done directly in Python, allowing subclasses to be created directly.
2601 2602
 *  We'd really have to write a wrapper around it all anyway to allow
 *  inheritance.
2603 2604
 */
static PyMethodDef parser_functions[] =  {
2605 2606
    {"ast2tuple",	parser_ast2tuple,	1,
	"Creates a tuple-tree representation of an AST."},
Guido van Rossum's avatar
Guido van Rossum committed
2607 2608
    {"ast2list",	parser_ast2list,	1,
	"Creates a list-tree representation of an AST."},
2609 2610 2611 2612 2613 2614 2615 2616 2617 2618
    {"compileast",	parser_compileast,	1,
	"Compiles an AST object into a code object."},
    {"expr",		parser_expr,		1,
	"Creates an AST object from an expression."},
    {"isexpr",		parser_isexpr,		1,
	"Determines if an AST object was created from an expression."},
    {"issuite",		parser_issuite,		1,
	"Determines if an AST object was created from a suite."},
    {"suite",		parser_suite,		1,
	"Creates an AST object from a suite."},
Guido van Rossum's avatar
Guido van Rossum committed
2619 2620
    {"sequence2ast",	parser_tuple2ast,	1,
	"Creates an AST object from a tree representation."},
2621
    {"tuple2ast",	parser_tuple2ast,	1,
Guido van Rossum's avatar
Guido van Rossum committed
2622
	"Creates an AST object from a tree representation."},
2623 2624 2625 2626 2627 2628

    {0, 0, 0}
    };


void
2629 2630
initparser()
 {
2631 2632 2633 2634 2635 2636
    PyObject* module;
    PyObject* dict;
	
    PyAST_Type.ob_type = &PyType_Type;
    module = Py_InitModule("parser", parser_functions);
    dict = PyModule_GetDict(module);
2637

2638
    parser_error = PyErr_NewException("parser.ParserError", NULL, NULL);
2639 2640 2641 2642 2643 2644

    if ((parser_error == 0)
	|| (PyDict_SetItemString(dict, "ParserError", parser_error) != 0)) {
	/*
	 *  This is serious.
	 */
2645
	Py_FatalError("can't define parser.ParserError");
2646 2647 2648 2649
    }
    /*
     *  Nice to have, but don't cry if we fail.
     */
2650 2651 2652
    Py_INCREF(&PyAST_Type);
    PyDict_SetItemString(dict, "ASTType", (PyObject*)&PyAST_Type);

2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663
    PyDict_SetItemString(dict, "__copyright__",
			 PyString_FromString(parser_copyright_string));
    PyDict_SetItemString(dict, "__doc__",
			 PyString_FromString(parser_doc_string));
    PyDict_SetItemString(dict, "__version__",
			 PyString_FromString(parser_version_string));

}   /* initparser() */


/*
2664
 *  end of parsermodule.c
2665
 */