parser.c 9.95 KB
Newer Older
1

Guido van Rossum's avatar
Guido van Rossum committed
2 3 4 5 6 7
/* Parser implementation */

/* For a description, see the comments at end of this file */

/* XXX To do: error recovery */

8
#include "Python.h"
Guido van Rossum's avatar
Guido van Rossum committed
9
#include "pgenheaders.h"
Guido van Rossum's avatar
Guido van Rossum committed
10 11 12 13 14 15 16
#include "token.h"
#include "grammar.h"
#include "node.h"
#include "parser.h"
#include "errcode.h"


17
#ifdef Py_DEBUG
18 19
extern int Py_DebugFlag;
#define D(x) if (!Py_DebugFlag); else x
Guido van Rossum's avatar
Guido van Rossum committed
20 21 22 23 24 25 26
#else
#define D(x)
#endif


/* STACK DATA TYPE */

27
static void s_reset(stack *);
Guido van Rossum's avatar
Guido van Rossum committed
28 29

static void
Thomas Wouters's avatar
Thomas Wouters committed
30
s_reset(stack *s)
Guido van Rossum's avatar
Guido van Rossum committed
31 32 33 34 35 36 37
{
	s->s_top = &s->s_base[MAXSTACK];
}

#define s_empty(s) ((s)->s_top == &(s)->s_base[MAXSTACK])

static int
Thomas Wouters's avatar
Thomas Wouters committed
38
s_push(register stack *s, dfa *d, node *parent)
Guido van Rossum's avatar
Guido van Rossum committed
39 40 41 42
{
	register stackentry *top;
	if (s->s_top == s->s_base) {
		fprintf(stderr, "s_push: parser stack overflow\n");
43
		return E_NOMEM;
Guido van Rossum's avatar
Guido van Rossum committed
44 45 46 47 48 49 50 51
	}
	top = --s->s_top;
	top->s_dfa = d;
	top->s_parent = parent;
	top->s_state = 0;
	return 0;
}

52
#ifdef Py_DEBUG
Guido van Rossum's avatar
Guido van Rossum committed
53 54

static void
Thomas Wouters's avatar
Thomas Wouters committed
55
s_pop(register stack *s)
Guido van Rossum's avatar
Guido van Rossum committed
56
{
57
	if (s_empty(s))
58
		Py_FatalError("s_pop: parser stack underflow -- FATAL");
Guido van Rossum's avatar
Guido van Rossum committed
59 60 61
	s->s_top++;
}

62
#else /* !Py_DEBUG */
Guido van Rossum's avatar
Guido van Rossum committed
63 64 65 66 67 68 69 70 71

#define s_pop(s) (s)->s_top++

#endif


/* PARSER CREATION */

parser_state *
Thomas Wouters's avatar
Thomas Wouters committed
72
PyParser_New(grammar *g, int start)
Guido van Rossum's avatar
Guido van Rossum committed
73 74 75 76
{
	parser_state *ps;
	
	if (!g->g_accel)
77
		PyGrammar_AddAccelerators(g);
78
	ps = (parser_state *)PyMem_MALLOC(sizeof(parser_state));
Guido van Rossum's avatar
Guido van Rossum committed
79 80 81
	if (ps == NULL)
		return NULL;
	ps->p_grammar = g;
82 83
#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
	ps->p_flags = 0;
84
#endif
85
	ps->p_tree = PyNode_New(start);
Guido van Rossum's avatar
Guido van Rossum committed
86
	if (ps->p_tree == NULL) {
87
		PyMem_FREE(ps);
Guido van Rossum's avatar
Guido van Rossum committed
88 89 90
		return NULL;
	}
	s_reset(&ps->p_stack);
91
	(void) s_push(&ps->p_stack, PyGrammar_FindDFA(g, start), ps->p_tree);
Guido van Rossum's avatar
Guido van Rossum committed
92 93 94 95
	return ps;
}

void
Thomas Wouters's avatar
Thomas Wouters committed
96
PyParser_Delete(parser_state *ps)
Guido van Rossum's avatar
Guido van Rossum committed
97
{
98 99
	/* NB If you want to save the parse tree,
	   you must set p_tree to NULL before calling delparser! */
100
	PyNode_Free(ps->p_tree);
101
	PyMem_FREE(ps);
Guido van Rossum's avatar
Guido van Rossum committed
102 103 104 105 106 107
}


/* PARSER STACK OPERATIONS */

static int
108
shift(register stack *s, int type, char *str, int newstate, int lineno, int col_offset)
Guido van Rossum's avatar
Guido van Rossum committed
109
{
110
	int err;
Guido van Rossum's avatar
Guido van Rossum committed
111
	assert(!s_empty(s));
112
	err = PyNode_AddChild(s->s_top->s_parent, type, str, lineno, col_offset);
113 114
	if (err)
		return err;
Guido van Rossum's avatar
Guido van Rossum committed
115 116 117 118 119
	s->s_top->s_state = newstate;
	return 0;
}

static int
120
push(register stack *s, int type, dfa *d, int newstate, int lineno, int col_offset)
Guido van Rossum's avatar
Guido van Rossum committed
121
{
122
	int err;
Guido van Rossum's avatar
Guido van Rossum committed
123 124 125
	register node *n;
	n = s->s_top->s_parent;
	assert(!s_empty(s));
126
	err = PyNode_AddChild(n, type, (char *)NULL, lineno, col_offset);
127 128
	if (err)
		return err;
Guido van Rossum's avatar
Guido van Rossum committed
129 130 131 132 133 134 135 136
	s->s_top->s_state = newstate;
	return s_push(s, d, CHILD(n, NCH(n)-1));
}


/* PARSER PROPER */

static int
137
classify(parser_state *ps, int type, char *str)
Guido van Rossum's avatar
Guido van Rossum committed
138
{
139
	grammar *g = ps->p_grammar;
Guido van Rossum's avatar
Guido van Rossum committed
140 141 142 143 144 145 146
	register int n = g->g_ll.ll_nlabels;
	
	if (type == NAME) {
		register char *s = str;
		register label *l = g->g_ll.ll_label;
		register int i;
		for (i = n; i > 0; i--, l++) {
147 148 149 150
			if (l->lb_type != NAME || l->lb_str == NULL ||
			    l->lb_str[0] != s[0] ||
			    strcmp(l->lb_str, s) != 0)
				continue;
151
#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
152
#if 0
153
                        /* Leaving this in as an example */
154 155 156 157 158
			if (!(ps->p_flags & CO_FUTURE_WITH_STATEMENT)) {
				if (s[0] == 'w' && strcmp(s, "with") == 0)
					break; /* not a keyword yet */
				else if (s[0] == 'a' && strcmp(s, "as") == 0)
					break; /* not a keyword yet */
Guido van Rossum's avatar
Guido van Rossum committed
159
			}
160
#endif
161 162 163
#endif
			D(printf("It's a keyword\n"));
			return n - i;
Guido van Rossum's avatar
Guido van Rossum committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
		}
	}
	
	{
		register label *l = g->g_ll.ll_label;
		register int i;
		for (i = n; i > 0; i--, l++) {
			if (l->lb_type == type && l->lb_str == NULL) {
				D(printf("It's a token we know\n"));
				return n - i;
			}
		}
	}
	
	D(printf("Illegal token\n"));
	return -1;
}

182
#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
183
#if 0
184
/* Leaving this in as an example */
185 186 187 188
static void
future_hack(parser_state *ps)
{
	node *n = ps->p_stack.s_top->s_parent;
189
	node *ch, *cch;
190
	int i;
191

192 193 194 195 196 197
	/* from __future__ import ..., must have at least 4 children */
	n = CHILD(n, 0);
	if (NCH(n) < 4)
		return;
	ch = CHILD(n, 0);
	if (STR(ch) == NULL || strcmp(STR(ch), "from") != 0)
198 199
		return;
	ch = CHILD(n, 1);
200 201
	if (NCH(ch) == 1 && STR(CHILD(ch, 0)) &&
	    strcmp(STR(CHILD(ch, 0)), "__future__") != 0)
202
		return;
203 204 205 206 207 208 209 210 211
	ch = CHILD(n, 3);
	/* ch can be a star, a parenthesis or import_as_names */
	if (TYPE(ch) == STAR)
		return;
	if (TYPE(ch) == LPAR)
		ch = CHILD(n, 4);
	
	for (i = 0; i < NCH(ch); i += 2) {
		cch = CHILD(ch, i);
212 213 214 215 216 217 218 219 220
		if (NCH(cch) >= 1 && TYPE(CHILD(cch, 0)) == NAME) {
			char *str_ch = STR(CHILD(cch, 0));
			if (strcmp(str_ch, FUTURE_WITH_STATEMENT) == 0) {
				ps->p_flags |= CO_FUTURE_WITH_STATEMENT;
			} else if (strcmp(str_ch, FUTURE_PRINT_FUNCTION) == 0) {
				ps->p_flags |= CO_FUTURE_PRINT_FUNCTION;
			} else if (strcmp(str_ch, FUTURE_UNICODE_LITERALS) == 0) {
				ps->p_flags |= CO_FUTURE_UNICODE_LITERALS;
			}
221 222
		}
	}
223
}
224
#endif
225
#endif /* future keyword */
226

Guido van Rossum's avatar
Guido van Rossum committed
227
int
Thomas Wouters's avatar
Thomas Wouters committed
228
PyParser_AddToken(register parser_state *ps, register int type, char *str,
229
	          int lineno, int col_offset, int *expected_ret)
Guido van Rossum's avatar
Guido van Rossum committed
230 231
{
	register int ilabel;
232
	int err;
Guido van Rossum's avatar
Guido van Rossum committed
233
	
234
	D(printf("Token %s/'%s' ... ", _PyParser_TokenNames[type], str));
Guido van Rossum's avatar
Guido van Rossum committed
235 236
	
	/* Find out which label this token is */
237
	ilabel = classify(ps, type, str);
Guido van Rossum's avatar
Guido van Rossum committed
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
	if (ilabel < 0)
		return E_SYNTAX;
	
	/* Loop until the token is shifted or an error occurred */
	for (;;) {
		/* Fetch the current dfa and state */
		register dfa *d = ps->p_stack.s_top->s_dfa;
		register state *s = &d->d_state[ps->p_stack.s_top->s_state];
		
		D(printf(" DFA '%s', state %d:",
			d->d_name, ps->p_stack.s_top->s_state));
		
		/* Check accelerator */
		if (s->s_lower <= ilabel && ilabel < s->s_upper) {
			register int x = s->s_accel[ilabel - s->s_lower];
			if (x != -1) {
				if (x & (1<<7)) {
					/* Push non-terminal */
					int nt = (x >> 8) + NT_OFFSET;
					int arrow = x & ((1<<7)-1);
258 259
					dfa *d1 = PyGrammar_FindDFA(
						ps->p_grammar, nt);
260
					if ((err = push(&ps->p_stack, nt, d1,
261
						arrow, lineno, col_offset)) > 0) {
262
						D(printf(" MemError: push\n"));
263
						return err;
Guido van Rossum's avatar
Guido van Rossum committed
264 265 266 267 268 269
					}
					D(printf(" Push ...\n"));
					continue;
				}
				
				/* Shift the token */
270
				if ((err = shift(&ps->p_stack, type, str,
271
						x, lineno, col_offset)) > 0) {
Guido van Rossum's avatar
Guido van Rossum committed
272
					D(printf(" MemError: shift.\n"));
273
					return err;
Guido van Rossum's avatar
Guido van Rossum committed
274 275 276 277 278 279
				}
				D(printf(" Shift.\n"));
				/* Pop while we are in an accept-only state */
				while (s = &d->d_state
						[ps->p_stack.s_top->s_state],
					s->s_accept && s->s_narcs == 1) {
280 281 282 283
					D(printf("  DFA '%s', state %d: "
						 "Direct pop.\n",
						 d->d_name,
						 ps->p_stack.s_top->s_state));
284
#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
285
#if 0
286 287 288 289
					if (d->d_name[0] == 'i' &&
					    strcmp(d->d_name,
						   "import_stmt") == 0)
						future_hack(ps);
290
#endif
291
#endif
Guido van Rossum's avatar
Guido van Rossum committed
292 293 294 295 296 297 298 299 300 301 302 303
					s_pop(&ps->p_stack);
					if (s_empty(&ps->p_stack)) {
						D(printf("  ACCEPT.\n"));
						return E_DONE;
					}
					d = ps->p_stack.s_top->s_dfa;
				}
				return E_OK;
			}
		}
		
		if (s->s_accept) {
304
#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
305
#if 0
306 307 308
			if (d->d_name[0] == 'i' &&
			    strcmp(d->d_name, "import_stmt") == 0)
				future_hack(ps);
309
#endif
310
#endif
Guido van Rossum's avatar
Guido van Rossum committed
311 312 313 314 315 316 317 318 319 320 321 322
			/* Pop this dfa and try again */
			s_pop(&ps->p_stack);
			D(printf(" Pop ...\n"));
			if (s_empty(&ps->p_stack)) {
				D(printf(" Error: bottom of stack.\n"));
				return E_SYNTAX;
			}
			continue;
		}
		
		/* Stuck, report syntax error */
		D(printf(" Error.\n"));
323 324 325 326 327 328 329 330 331
		if (expected_ret) {
			if (s->s_lower == s->s_upper - 1) {
				/* Only one possible expected token */
				*expected_ret = ps->p_grammar->
				    g_ll.ll_label[s->s_lower].lb_type;
			}
			else 
		        	*expected_ret = -1;
		}
Guido van Rossum's avatar
Guido van Rossum committed
332 333 334 335 336
		return E_SYNTAX;
	}
}


337
#ifdef Py_DEBUG
Guido van Rossum's avatar
Guido van Rossum committed
338 339 340 341

/* DEBUG OUTPUT */

void
Thomas Wouters's avatar
Thomas Wouters committed
342
dumptree(grammar *g, node *n)
Guido van Rossum's avatar
Guido van Rossum committed
343 344 345 346 347 348 349 350
{
	int i;
	
	if (n == NULL)
		printf("NIL");
	else {
		label l;
		l.lb_type = TYPE(n);
351
		l.lb_str = STR(n);
352
		printf("%s", PyGrammar_LabelRepr(&l));
Guido van Rossum's avatar
Guido van Rossum committed
353 354 355 356 357 358 359 360 361 362 363 364 365
		if (ISNONTERMINAL(TYPE(n))) {
			printf("(");
			for (i = 0; i < NCH(n); i++) {
				if (i > 0)
					printf(",");
				dumptree(g, CHILD(n, i));
			}
			printf(")");
		}
	}
}

void
Thomas Wouters's avatar
Thomas Wouters committed
366
showtree(grammar *g, node *n)
Guido van Rossum's avatar
Guido van Rossum committed
367 368 369 370 371 372 373 374 375 376
{
	int i;
	
	if (n == NULL)
		return;
	if (ISNONTERMINAL(TYPE(n))) {
		for (i = 0; i < NCH(n); i++)
			showtree(g, CHILD(n, i));
	}
	else if (ISTERMINAL(TYPE(n))) {
377
		printf("%s", _PyParser_TokenNames[TYPE(n)]);
Guido van Rossum's avatar
Guido van Rossum committed
378 379 380 381 382 383 384 385 386
		if (TYPE(n) == NUMBER || TYPE(n) == NAME)
			printf("(%s)", STR(n));
		printf(" ");
	}
	else
		printf("? ");
}

void
Thomas Wouters's avatar
Thomas Wouters committed
387
printtree(parser_state *ps)
Guido van Rossum's avatar
Guido van Rossum committed
388
{
389
	if (Py_DebugFlag) {
Guido van Rossum's avatar
Guido van Rossum committed
390 391 392 393 394 395 396 397
		printf("Parse tree:\n");
		dumptree(ps->p_grammar, ps->p_tree);
		printf("\n");
		printf("Tokens:\n");
		showtree(ps->p_grammar, ps->p_tree);
		printf("\n");
	}
	printf("Listing:\n");
398
	PyNode_ListTree(ps->p_tree);
Guido van Rossum's avatar
Guido van Rossum committed
399 400 401
	printf("\n");
}

402
#endif /* Py_DEBUG */
Guido van Rossum's avatar
Guido van Rossum committed
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448

/*

Description
-----------

The parser's interface is different than usual: the function addtoken()
must be called for each token in the input.  This makes it possible to
turn it into an incremental parsing system later.  The parsing system
constructs a parse tree as it goes.

A parsing rule is represented as a Deterministic Finite-state Automaton
(DFA).  A node in a DFA represents a state of the parser; an arc represents
a transition.  Transitions are either labeled with terminal symbols or
with non-terminals.  When the parser decides to follow an arc labeled
with a non-terminal, it is invoked recursively with the DFA representing
the parsing rule for that as its initial state; when that DFA accepts,
the parser that invoked it continues.  The parse tree constructed by the
recursively called parser is inserted as a child in the current parse tree.

The DFA's can be constructed automatically from a more conventional
language description.  An extended LL(1) grammar (ELL(1)) is suitable.
Certain restrictions make the parser's life easier: rules that can produce
the empty string should be outlawed (there are other ways to put loops
or optional parts in the language).  To avoid the need to construct
FIRST sets, we can require that all but the last alternative of a rule
(really: arc going out of a DFA's state) must begin with a terminal
symbol.

As an example, consider this grammar:

expr:	term (OP term)*
term:	CONSTANT | '(' expr ')'

The DFA corresponding to the rule for expr is:

------->.---term-->.------->
	^          |
	|          |
	\----OP----/

The parse tree generated for the input a+b is:

(expr: (term: (NAME: a)), (OP: +), (term: (NAME: b)))

*/