Parse lines at a time

This commit is contained in:
Devine Lu Linvega 2024-04-05 08:54:39 -07:00
parent b0499fad18
commit 0557b06faf
2 changed files with 37 additions and 39 deletions

View File

@ -1,4 +1,5 @@
<> (?x dup) (?x ?x) <> (?x dup) (?x ?x)
<> (?x ?y swap) (?y ?x) <> (?x ?y swap) (?y ?x)
(A B swap) dup ((A B swap) dup)

View File

@ -112,62 +112,59 @@ print_rules(void)
} }
static char * static char *
parse_rulefrag(FILE *f) parse_rulefrag(char *line)
{ {
int depth = 0, trim = 0; int depth = 0;
char c, *origin = dict_; char c, *s = line, *res = dict_;
while(f && fread(&c, 1, 1, f) && c && c != 0xa) { if(s[0] == '(') {
if(c == ' ' && !trim) continue; while((c = *s++)) {
trim = 1; if(c == '(') depth++;
if(c == '(') { *dict_++ = c;
depth++; if(c == ')') --depth;
if(depth == 1) continue; if(!depth) {
*dict_++ = 0;
return res;
}
} }
if(c == ')') {
--depth;
if(depth == 0) continue;
}
if(c == ' ' && !depth) break;
*dict_++ = c;
} }
while(!spacer(s[0]) && (*dict_++ = *s++))
;
*dict_++ = 0; *dict_++ = 0;
return origin; return res;
} }
static void static int
tokenize(char *t, FILE *f) parse_line(char *line)
{ {
char c; if(line[0] == 0) return 1;
if(!t[0]) return; if(line[0] == '<' && line[1] == '>') {
if(t[0] == '<' && t[1] == '>') {
Rule *r = &rules[rules_len++]; Rule *r = &rules[rules_len++];
r->a = parse_rulefrag(f), r->b = parse_rulefrag(f); line += 3;
return; r->a = parse_rulefrag(line);
line = walk(line) + 1;
r->b = parse_rulefrag(line);
return 1;
} }
while((c = *t++)) while((*prog_++ = *line++))
*prog_++ = c; ;
*prog_++ = ' '; *prog_++ = 0xa;
while(f && fread(&c, 1, 1, f) && c) return 1;
*prog_++ = c == 0xa ? ' ' : c;
} }
static int static int
parse(char *path) parse(char *path)
{ {
FILE *f; FILE *f;
char c, token[0x40], *token_; char c, line[0x400], *line_ = line;
if(!(f = fopen(path, "r"))) if(!(f = fopen(path, "r")))
return !printf("Invalid file: %s\n", path); return !printf("Invalid file: %s\n", path);
token_ = token;
while(f && fread(&c, 1, 1, f)) { while(f && fread(&c, 1, 1, f)) {
if(c < 0x21) if(c == 0xa)
*token_++ = 0x00, tokenize(token, f), token_ = token; *line_++ = 0x00, parse_line(line), line_ = line;
else if(token_ - token < 0x3f) else if(line_ - line < 0x400)
*token_++ = c; *line_++ = c;
else
return printf("Token too long: %s\n", token);
} }
*token_++ = 0x00, tokenize(token, f), token_ = token; *line_++ = 0x00, parse_line(line), line_ = line;
fclose(f); fclose(f);
return 1; return 1;
} }