diff --git a/src/modal.c b/src/modal.c index 4faa8cc..9cd090f 100644 --- a/src/modal.c +++ b/src/modal.c @@ -66,15 +66,13 @@ match(char *p, Rule *r) return b; } -static void +static int bind(char r) { int depth = 0; char c, *s = regs[(int)r]; - if(!s) { - printf("!! Reading from invalid register: ?%c\n", r); - return; - } + if(!s) + return !printf("!! Reading from invalid register: ?%c\n", r); if(s[0] == '(') { while((c = *s++)) { if(c == '(') depth++; @@ -85,7 +83,7 @@ bind(char r) } while(!spacer(s[0]) && (*outp_++ = *s++)) ; - return; + return 1; } static void @@ -98,6 +96,33 @@ save(int rule) printf("%02d %s\n", rule, prog); } +static char * +parse_rulefrag(char *line) +{ + int depth = 0; + char c, *s = line, *res = dict_; + if(s[0] == '(') { + while((c = *s++)) { + if(c == '(') { + depth++; + if(depth == 1) continue; + } + if(c == ')') { + --depth; + if(!depth) { + *dict_++ = 0; + return res; + } + } + *dict_++ = c; + } + } + while(!spacer(s[0]) && (*dict_++ = *s++)) + ; + *dict_++ = 0; + return res; +} + static char * addrule(char *s) { @@ -152,44 +177,45 @@ print_rules(void) printf("\n"); } -static char * -parse_rulefrag(char *line) +static int +parse_line(char *line) { - int depth = 0; - char c, *s = line, *res = dict_; - if(s[0] == '(') { - while((c = *s++)) { - if(c == '(') { - depth++; - if(depth == 1) continue; - } - if(c == ')') { - --depth; - if(!depth) { - *dict_++ = 0; - return res; - } - } - *dict_++ = c; - } + char c; + if(line[0] == 0) return 1; + if(line[0] == '<' && line[1] == '>') + return !!addrule(line); + while((c = *line++)) + *prog_++ = c; + return 1; +} + +static int +parse(char *path) +{ + FILE *f; + char c, line[0x400], *line_ = line; + if(!(f = fopen(path, "r"))) + return 0; + while(f && fread(&c, 1, 1, f)) { + if(c == 0xa) + *line_++ = 0x00, parse_line(line), line_ = line; + else if(line_ - line < 0x400) + *line_++ = c; } - while(!spacer(s[0]) && (*dict_++ = *s++)) - ; - *dict_++ = 0; - return res; + *line_++ = 0x00, parse_line(line), line_ = line; + fclose(f); + return 1; } int main(int argc, char **argv) { - FILE *f; if(argc < 2) return !printf("usage: modal [-v] source.modal\n"); if(argc < 3 && argv[1][0] == '-' && argv[1][1] == 'v') return !printf("Modal - Modal Interpreter, 4 Apr 2024.\n"); - if(!(f = fopen(argv[1], "r"))) - return !printf("Invalid file: %s\n", argv[1]); - fread(&prog, 1, 0x1000, f), fclose(f); + if(!parse(argv[1])) + return !printf("Invalid Modal file: %s.\n", argv[1]); print_rules(); printf(".. %s\n", prog); while(rewrite())