diff options
Diffstat (limited to 'demos/sample-files/calc-skeleton.c')
-rw-r--r-- | demos/sample-files/calc-skeleton.c | 100 |
1 files changed, 100 insertions, 0 deletions
diff --git a/demos/sample-files/calc-skeleton.c b/demos/sample-files/calc-skeleton.c new file mode 100644 index 0000000..29f181b --- /dev/null +++ b/demos/sample-files/calc-skeleton.c @@ -0,0 +1,100 @@ +#include <stdio.h> +#include <string.h> +#include <ctype.h> + +#include "lr-parser.c" +#include "bin/a.c" + +// from calc-defs.c +#include "parts/symbol.h" +enum symbol { + PLUS = 0, + MINUS, + LPAREN, + RPAREN, + NUM, + END_INPUT, + + EP, E, T, + SYMBOLS_END, +}; + +static struct token { + symbol s; + int v; +} tok; + +static inline int issep(char c) +{ + return isspace(c) || c == '\0' || c == '(' || c == ')' || c == '+' || c == '-'; +} + +static inline int tillsep(char *str) +{ + size_t i = 0; + while(!issep(str[i++])); + return i-1; +} + +static inline char *substring(char *str, size_t sub_end) +{ + static char sub[128]; + if(sub_end+1 > sizeof(sub)) return NULL; + + sub[sub_end] = '\0'; + return memcpy(sub, str, sub_end); +} + +static char *next_token(char *str) +{ + size_t off = 0; + char c0 = str[0]; + + if(c0 == '\0') tok.s = END_INPUT; + if(isspace(c0)) return next_token(str+1); + else { + off = tillsep(str); + if(off == 0) { // sep + switch(str[off++]) { + case '(': tok.s = LPAREN; break; + case ')': tok.s = RPAREN; break; + case '-': tok.s = MINUS; break; + case '+': tok.s = PLUS; break; + } + } else if(c0 >= '0' && c0 <= '9') { // num + tok.s = NUM; + tok.v = atoi(substring(str, off)); + } + } + + return str+off; +} + +static char *input; + +symbol token_sym(struct token *t) { return t->s; } +int token_val(struct token *t) { return t->v; } + +struct token *toklist_eat() +{ + static struct token t; + t = tok; + input = next_token(input); + return &t; +} +struct token *toklist_peek() { return &tok; } + +int main(int argc, char **argv) +{ + if(argc != 2) return 1; + + input = next_token(argv[1]); + + int value; + if(lr_parser(&value)) return 1; + + printf("INPUT: '%s'\n", argv[1]); + printf("OUTPUT: %d\n", value); + + return 0; +} |