#include typedef struct { char *a, *b; } Rule; static int rules_len; static Rule rules[0x100]; static char dict[0x8000], *next = dict; static char prog[0x1000], *prog_ = prog; static char *regs[0x100]; static void bind(int id, char *addr) { printf("bind register %02x -> %s\n", id, addr); regs[id] = addr; } static char * walk(char *s) { char c; while((c = *s++)) if(*s == ')') break; return s; } static int match(char *p, Rule *r) { char c, *a = r->a, *b = p; while((c = *a)) { if(c == '?') bind(*(++a), b), a++, b = walk(b), c = *b; if(c != *b) return 0; a++, b++; } printf("> found: %s = %s, rule: %s\n", p, r->a, r->b); return 1; } static int reduce(void) { char c, *p = prog; while((c = *p)) { int i; for(i = 0; i < rules_len; i++) { Rule *r = &rules[i]; match(p, r); } p++; } return 1; } static void display(void) { int i; for(i = 0; i < rules_len; i++) { Rule *r = &rules[i]; printf("Rule #%d: %s -> %s\n", i, r->a, r->b); } printf("Program: %s\n", prog); } static char * parse_rulefrag(FILE *f) { int depth = 0; char c, *origin = next; while(f && fread(&c, 1, 1, f) && c && c != 0xa) { if(c == '(') depth++; if(c == ')') --depth; if(c == ' ' && !depth) break; else *next++ = c; } *next++ = 0; return origin; } static void tokenize(char *t, FILE *f) { char c; if(t[0] == '<' && t[1] == '>') { Rule *r = &rules[rules_len++]; r->a = parse_rulefrag(f), r->b = parse_rulefrag(f); return; } while(f && fread(&c, 1, 1, f) && c && c != 0xa) *prog_++ = c; *prog_++ = 0x20; } static int parse(char *path) { FILE *f; char c, token[0x40], *tokptr; if(!(f = fopen(path, "r"))) return !printf("Invalid file: %s\n", path); tokptr = token; while(f && fread(&c, 1, 1, f)) { if(c < 0x21) *tokptr++ = 0x00, tokenize(token, f), tokptr = token; else if(tokptr - token < 0x3f) *tokptr++ = c; else return printf("Token too long: %s\n", token); } *tokptr++ = 0x00, tokenize(token, f), tokptr = token; fclose(f); return 1; } int main(int argc, char **argv) { 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, 3 Apr 2024.\n"); parse(argv[1]); display(); return !reduce(); }