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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
#include <stdio.h>
#include <stdlib.h>
#include "parts/symbol.h"
enum symbol {
PLUS = 0,
MINUS,
LPAREN,
RPAREN,
N0, N1,
END_INPUT,
EP, E, T, N,
SYMBOLS_END,
};
size_t total_symbols = SYMBOLS_END;
IMPLEMENT_FUNCPTR(int, symbol_is_terminal, (symbol s)) { return s < EP; }
IMPLEMENT_FUNCPTR(int, symbol_is_input_end, (symbol s)) { return s == END_INPUT; }
IMPLEMENT_FUNCPTR(int, symbol_is_valid,(symbol s)) { return s < SYMBOLS_END; }
#include "parts/grammar.h"
#define PROD(LHS, _, ...) {LHS, (symbol[]){__VA_ARGS__}, sizeof((symbol[]){__VA_ARGS__})/sizeof(symbol)}
static struct production _grammar[] = {
PROD(EP, ->, E, END_INPUT),
PROD(E, -->, E, PLUS, T),
PROD(E, -->, E, MINUS, T),
PROD(E, -->, T),
PROD(T, -->, LPAREN, E, RPAREN),
PROD(T, -->, N),
PROD(N, -->, N0),
PROD(N, -->, N1),
};
struct production *grammar = _grammar;
size_t total_productions = sizeof(_grammar)/sizeof(*_grammar);
#include "parts/toklist.h"
static symbol toklist[] = {N0, PLUS, N1, MINUS, N0, END_INPUT};
static symbol *tok = toklist;
symbol toklist_eat() { return *(tok++); } // unsafe
symbol toklist_peek() { return *tok; } // unsafe
int __prod0_action(int *stack_head) { return *(stack_head-4); }
int __prod1_action(int *stack_head) { return *(stack_head-7) + *(stack_head-1); }
int __prod2_action(int *stack_head) { return *(stack_head-7) + *(stack_head-1); }
int __prod3_action(int *stack_head) { return *(stack_head - 1); }
int __prod4_action(int *stack_head) { return *(stack_head - 4); }
int __prod5_action(int *stack_head) { return *(stack_head - 1); }
int __prod6_action(int *stack_head) { return 0; }
int __prod7_action(int *stack_head) { return 1; }
typedef int (*semantic_action_fn)(int *stack_head);
semantic_action_fn *semantic_actions = (semantic_action_fn[]){
__prod0_action, __prod1_action, __prod2_action, __prod3_action,
__prod4_action, __prod5_action, __prod6_action, __prod7_action,
};
#include "slr-table.c"
#include "util-tables.c"
#include "lr-parser.c"
int main(void)
{
util_tables_fill();
int r = 0;
if((r = table_fill())) goto cleanup;
table_print();
printf("RESULT: %d\n", lr_parser());
cleanup:
table_free();
util_tables_free();
return r;
}
|