aboutsummaryrefslogtreecommitdiff
path: root/demos/generate-parser.c
blob: 8d50ad64517f879bee972ee640208f354ec8fb52 (plain)
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
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>

#include "parts/symbol.h"
#include "parts/table.h"
size_t total_symbols;
int (*symbol_is_terminal)(symbol s);
int (*symbol_is_input_end)(symbol s);
int (*symbol_is_valid)(symbol s);

#include "parts/grammar.h"

struct production *grammar;
size_t total_productions;

#include "util-tables.c"

#define _LAZY_LALR
#include "clr-table.c"

void *xdlsym(void *handle, char *sym)
{
    void *r = dlsym(handle, sym);
    if(!r) {
        fprintf(stderr, "ERROR: Symbol '%s' was not found\n", sym);
        exit(1);
    }
    return r;
}

#define GET_VARIABLE(var, handle)                    \
    var = *(typeof(&var))xdlsym(handle, #var)

int main(int argc, char **argv)
{
    if(argc != 2) return 1;
    
    void *handle = dlopen(argv[1], RTLD_LAZY);
    if(!handle) { puts(dlerror()); return 1; }

    GET_VARIABLE(total_symbols, handle);    
    GET_VARIABLE(symbol_is_terminal, handle);
    GET_VARIABLE(symbol_is_input_end, handle);
    GET_VARIABLE(symbol_is_valid, handle);
    GET_VARIABLE(grammar, handle);
    GET_VARIABLE(total_productions, handle);
    util_tables_fill();
    table_fill() && (fprintf(stderr, "ERROR: Table couldn't be generated\n"), exit(1), 1);
    
    printf("size_t total_symbols = %zu;\n", total_symbols);
    printf("IMPLEMENT_FUNCPTR(int, symbol_is_valid, (symbol s), {return s < total_symbols;})\n");

    printf("struct production _grammar[] = {\n");
    grammar_print_cstyle();
    printf("};\n");

    printf("struct production *grammar = _grammar;");
    printf("size_t total_productions = %zu;\n", total_productions);
    
    printf("struct action **table = (struct action *([])){\n", table_states, total_symbols);
    table_print_cstyle();
    printf("};\n");
    printf("size_t table_states = %zu;\n", table_states);

    table_free();
    util_tables_free();
    
    dlclose(handle);
    return 0;
}