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 ?y swap) (?y ?x)
(A B swap) dup
((A B swap) dup)

View File

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