aboutsummaryrefslogtreecommitdiff
path: root/src/prc1/pop.c
blob: 977129e1b31360504b29e6975b463ffeb0cac36c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include "prv.h"
#include "dbg.h"
#include <stdlib.h>

int pop(const struct lex *l, struct prv *p)
{
    size_t n;
    struct pos *pos;
    int (*end)(const struct lex *, struct prv *);
    const char *name;

    if (!p->n)
    {
        fprintf(stderr, "%s: underflow\n", __func__);
        return -1;
    }

    pos = &p->pos[p->i];
    end = pos->end;
    name = pos->name;

    if (!(n = p->n - 1))
    {
        free(p->pos);
        p->pos = pos = NULL;
    }
    else if (!(pos = realloc(p->pos, n * sizeof *pos)))
    {
        perror("realloc(3)");
        return -1;
    }

    ddbg("pop rule %s [%zu]", name, p->i);

    if (end)
        ddbg(", end=%p", end);

    ddbg("\n");
    p->pos = pos;
    p->n = n;
    p->i--;

    if (end)
        return end(l, p);

    return 0;
}