parser.c 11.6 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
    s->s_top = &s->s_base[MAXSTACK];
Guido van Rossum's avatar
Guido van Rossum committed
33 34 35 36 37
}

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

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

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

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

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 77 78 79 80 81
    parser_state *ps;

    if (!g->g_accel)
        PyGrammar_AddAccelerators(g);
    ps = (parser_state *)PyMem_MALLOC(sizeof(parser_state));
    if (ps == NULL)
        return NULL;
    ps->p_grammar = g;
82
#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
83
    ps->p_flags = 0;
84
#endif
85 86 87 88 89 90 91 92
    ps->p_tree = PyNode_New(start);
    if (ps->p_tree == NULL) {
        PyMem_FREE(ps);
        return NULL;
    }
    s_reset(&ps->p_stack);
    (void) s_push(&ps->p_stack, PyGrammar_FindDFA(g, start), ps->p_tree);
    return ps;
Guido van Rossum's avatar
Guido van Rossum committed
93 94 95
}

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 100 101
    /* NB If you want to save the parse tree,
       you must set p_tree to NULL before calling delparser! */
    PyNode_Free(ps->p_tree);
    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(stack *s, int type, char *str, int newstate, int lineno, int col_offset)
Guido van Rossum's avatar
Guido van Rossum committed
109
{
110 111 112 113 114 115 116
    int err;
    assert(!s_empty(s));
    err = PyNode_AddChild(s->s_top->s_parent, type, str, lineno, col_offset);
    if (err)
        return err;
    s->s_top->s_state = newstate;
    return 0;
Guido van Rossum's avatar
Guido van Rossum committed
117 118 119
}

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


/* PARSER PROPER */

static int
137
classify(parser_state *ps, int type, const char *str)
Guido van Rossum's avatar
Guido van Rossum committed
138
{
139
    grammar *g = ps->p_grammar;
140
    int n = g->g_ll.ll_nlabels;
141 142

    if (type == NAME) {
143 144
        label *l = g->g_ll.ll_label;
        int i;
145 146
        for (i = n; i > 0; i--, l++) {
            if (l->lb_type != NAME || l->lb_str == NULL ||
147 148
                l->lb_str[0] != str[0] ||
                strcmp(l->lb_str, str) != 0)
149
                continue;
150
#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
151
#if 0
152 153
            /* Leaving this in as an example */
            if (!(ps->p_flags & CO_FUTURE_WITH_STATEMENT)) {
154
                if (str[0] == 'w' && strcmp(str, "with") == 0)
155
                    break; /* not a keyword yet */
156
                else if (str[0] == 'a' && strcmp(str, "as") == 0)
157 158
                    break; /* not a keyword yet */
            }
159
#endif
160
#endif
161 162 163 164 165 166
            D(printf("It's a keyword\n"));
            return n - i;
        }
    }

    {
167 168
        label *l = g->g_ll.ll_label;
        int i;
169 170 171 172 173 174 175 176 177 178
        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;
Guido van Rossum's avatar
Guido van Rossum committed
179 180
}

181
#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
182
#if 0
183
/* Leaving this in as an example */
184 185 186
static void
future_hack(parser_state *ps)
{
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    node *n = ps->p_stack.s_top->s_parent;
    node *ch, *cch;
    int i;

    /* 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)
        return;
    ch = CHILD(n, 1);
    if (NCH(ch) == 1 && STR(CHILD(ch, 0)) &&
        strcmp(STR(CHILD(ch, 0)), "__future__") != 0)
        return;
    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);
        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;
            }
        }
    }
222
}
223
#endif
224
#endif /* future keyword */
225

Guido van Rossum's avatar
Guido van Rossum committed
226
int
227
PyParser_AddToken(parser_state *ps, int type, char *str,
228
                  int lineno, int col_offset, int *expected_ret)
Guido van Rossum's avatar
Guido van Rossum committed
229
{
230
    int ilabel;
231 232 233 234 235 236 237 238 239 240 241 242
    int err;

    D(printf("Token %s/'%s' ... ", _PyParser_TokenNames[type], str));

    /* Find out which label this token is */
    ilabel = classify(ps, type, str);
    if (ilabel < 0)
        return E_SYNTAX;

    /* Loop until the token is shifted or an error occurred */
    for (;;) {
        /* Fetch the current dfa and state */
243 244
        dfa *d = ps->p_stack.s_top->s_dfa;
        state *s = &d->d_state[ps->p_stack.s_top->s_state];
245 246 247 248 249 250

        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) {
251
            int x = s->s_accel[ilabel - s->s_lower];
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
            if (x != -1) {
                if (x & (1<<7)) {
                    /* Push non-terminal */
                    int nt = (x >> 8) + NT_OFFSET;
                    int arrow = x & ((1<<7)-1);
                    dfa *d1 = PyGrammar_FindDFA(
                        ps->p_grammar, nt);
                    if ((err = push(&ps->p_stack, nt, d1,
                        arrow, lineno, col_offset)) > 0) {
                        D(printf(" MemError: push\n"));
                        return err;
                    }
                    D(printf(" Push ...\n"));
                    continue;
                }

                /* Shift the token */
                if ((err = shift(&ps->p_stack, type, str,
                                x, lineno, col_offset)) > 0) {
                    D(printf(" MemError: shift.\n"));
                    return err;
                }
                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) {
                    D(printf("  DFA '%s', state %d: "
                             "Direct pop.\n",
                             d->d_name,
                             ps->p_stack.s_top->s_state));
283
#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
284
#if 0
285 286 287 288
                    if (d->d_name[0] == 'i' &&
                        strcmp(d->d_name,
                           "import_stmt") == 0)
                        future_hack(ps);
289
#endif
290
#endif
291 292 293 294 295 296 297 298 299 300 301 302
                    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) {
303
#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
304
#if 0
305 306 307
            if (d->d_name[0] == 'i' &&
                strcmp(d->d_name, "import_stmt") == 0)
                future_hack(ps);
308
#endif
309
#endif
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
            /* 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"));
        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;
        }
        return E_SYNTAX;
    }
Guido van Rossum's avatar
Guido van Rossum committed
333 334 335
}


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

/* DEBUG OUTPUT */

void
Thomas Wouters's avatar
Thomas Wouters committed
341
dumptree(grammar *g, node *n)
Guido van Rossum's avatar
Guido van Rossum committed
342
{
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    int i;

    if (n == NULL)
        printf("NIL");
    else {
        label l;
        l.lb_type = TYPE(n);
        l.lb_str = STR(n);
        printf("%s", PyGrammar_LabelRepr(&l));
        if (ISNONTERMINAL(TYPE(n))) {
            printf("(");
            for (i = 0; i < NCH(n); i++) {
                if (i > 0)
                    printf(",");
                dumptree(g, CHILD(n, i));
            }
            printf(")");
        }
    }
Guido van Rossum's avatar
Guido van Rossum committed
362 363 364
}

void
Thomas Wouters's avatar
Thomas Wouters committed
365
showtree(grammar *g, node *n)
Guido van Rossum's avatar
Guido van Rossum committed
366
{
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
    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))) {
        printf("%s", _PyParser_TokenNames[TYPE(n)]);
        if (TYPE(n) == NUMBER || TYPE(n) == NAME)
            printf("(%s)", STR(n));
        printf(" ");
    }
    else
        printf("? ");
Guido van Rossum's avatar
Guido van Rossum committed
383 384 385
}

void
Thomas Wouters's avatar
Thomas Wouters committed
386
printtree(parser_state *ps)
Guido van Rossum's avatar
Guido van Rossum committed
387
{
388 389 390 391 392 393 394 395 396 397 398
    if (Py_DebugFlag) {
        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");
    PyNode_ListTree(ps->p_tree);
    printf("\n");
Guido van Rossum's avatar
Guido van Rossum committed
399 400
}

401
#endif /* Py_DEBUG */
Guido van Rossum's avatar
Guido van Rossum committed
402 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

/*

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:

433 434
expr:   term (OP term)*
term:   CONSTANT | '(' expr ')'
Guido van Rossum's avatar
Guido van Rossum committed
435 436 437 438

The DFA corresponding to the rule for expr is:

------->.---term-->.------->
439 440 441
    ^          |
    |          |
    \----OP----/
Guido van Rossum's avatar
Guido van Rossum committed
442 443 444 445 446 447

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

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

*/