More robust walking

This commit is contained in:
Devine Lu Linvega 2024-04-04 17:15:16 -07:00
parent d0acff37be
commit f51040de77
2 changed files with 12 additions and 8 deletions

View File

@ -1,4 +1,5 @@
<> (?x dup) (?x ?x)
<> (dup ?x) (?x ?x)
<> (?x ?y swap) (?y ?x)
(1234 dup)
((hey) (there) swap)

View File

@ -19,11 +19,11 @@ walk(char *s)
int depth = 0;
char c;
while((c = *s++)) {
if(spacer(c) && !depth) break;
if(c == '(') depth++;
if(c == ')') --depth;
if(spacer(c) && !depth) break;
}
return s - 1;
return s;
}
static char *
@ -31,7 +31,9 @@ match(char *p, Rule *r)
{
char c, *a = r->a, *b = p;
while((c = *a)) {
if(c == '?') regs[(int)*(++a)] = b, a++, b = walk(b), c = *b;
if(c == '?') {
regs[(int)*(++a)] = b, a++, b = walk(b), c = *b;
}
if(c != *b) return NULL;
a++, b++;
}
@ -44,10 +46,10 @@ writereg(char r)
int depth = 0;
char c, *s = regs[(int)r];
while((c = *s++)) {
if(spacer(c) && !depth) break;
*outp_++ = c;
if(c == '(') depth++;
if(c == ')') --depth;
*outp_++ = c;
if(!depth) break;
}
return 1;
}
@ -74,11 +76,12 @@ rewrite(void)
char *res = match(p, r);
if(res != NULL) {
char cc, *b = r->b;
while((cc = *b++))
while((cc = *b++)) {
if(cc == '?')
writereg(*b++);
else
*outp_++ = cc;
}
found = success = 1;
p = res;
}