From a2ea2a6ac26a33b72954908a09329af184dd9a1e Mon Sep 17 00:00:00 2001 From: Devine Lu Linvega Date: Sat, 27 Apr 2024 09:24:48 -0700 Subject: [PATCH] Pretty print rules --- src/modal.c | 44 ++++++++++++++++++++++++++++++-------------- 1 file changed, 30 insertions(+), 14 deletions(-) diff --git a/src/modal.c b/src/modal.c index 8a594e1..c7bc1a4 100644 --- a/src/modal.c +++ b/src/modal.c @@ -2,7 +2,7 @@ typedef struct { unsigned int id, refs, ptr; - char *a, *b, reg[0x8]; + char *a, *b, reg[8]; } Rule; static int flip, quiet, cycles = 0x10000; @@ -102,8 +102,8 @@ write_tail(char *s) static int apply_rule(Rule *r, char *s) { - unsigned int i, id; - char c, *a = r->a, *b = r->b, *origin = dst_, *reg, *regs[0x8]; + unsigned int i, rid; + char c, *a = r->a, *b = r->b, *origin = dst_, *reg, *regs[8]; /* phase: clean regs */ for(i = 0; i < r->ptr; i++) regs[i] = NULL; @@ -111,13 +111,13 @@ apply_rule(Rule *r, char *s) while((c = *a++)) { if(c == '?') { char *pcap = walk(s); - id = *a++ - '0'; - if((reg = regs[id])) { /* reg cmp */ + rid = *a++ - '0'; + if((reg = regs[rid])) { /* reg cmp */ char *rcap = walk(reg), *pp = s; while(reg < rcap || pp < pcap) if(*reg++ != *pp++) return 0; } else /* reg set */ - regs[id] = s; + regs[rid] = s; s = pcap; } else if(c != *s++) return 0; @@ -127,9 +127,9 @@ apply_rule(Rule *r, char *s) /* phase: write rule */ while((c = *b++)) { if(c == '?') { - id = *b - '0'; - if(id < 9 && (reg = regs[id])) - b++, write_reg(r->reg[id], reg); + rid = *b - '0'; + if(rid < 9 && (reg = regs[rid])) + b++, write_reg(r->reg[rid], reg); else *dst_++ = c; } else @@ -146,9 +146,9 @@ apply_rule(Rule *r, char *s) static int find_reg(Rule *r, char reg) { - int i; - for(i = 0; i < (int)r->ptr; i++) - if(r->reg[i] == reg) return i; + int rid; + for(rid = 0; rid < (int)r->ptr; rid++) + if(r->reg[rid] == reg) return rid; return -1; } @@ -204,6 +204,20 @@ find_rule(char *s, char *cap) return r; } +static void +echo_rule(Rule *r, char *field) +{ + char c, *s = field; + putc('(', stdout); + while((c = *s++)) { + int rid; + putc(c, stdout); + if(c == '?') + c = *s++, rid = c - '0', putc(rid < 8 ? r->reg[rid] : c, stdout); + } + putc(')', stdout), putc(' ', stdout); +} + static int rewrite(void) { @@ -216,7 +230,8 @@ rewrite(void) if(c == '<' && s[1] == '>') { r = rules_++; s = compile_rule(r, rules_ - rules - 1, s + 2); - if(!quiet && r->a) printf("<> (%s) (%s)\n", r->a, r->b); + if(!quiet && r->a) + printf("<> "), echo_rule(r, r->a), echo_rule(r, r->b), putc('\n', stdout); while(*s == ' ') s++; return write_tail(s); } @@ -225,7 +240,8 @@ rewrite(void) s += 2; while(*s == ' ') s++; cap = walk(s), r = find_rule(s, cap), r->a = 0; - if(!quiet && r->a) printf(">< (%s)\n", r->a); + if(!quiet && r->a) + printf(">< "), echo_rule(r, r->a), putc('\n', stdout); while(*cap == ' ') cap++; return write_tail(cap); }