modal/src/modal.c

173 lines
2.9 KiB
C

#include <stdio.h>
#include <string.h>
typedef struct {
char *a, *b;
} Rule;
static int rules_len;
static Rule rules[0x100];
static char dict[0x8000], *dict_ = dict;
static char prog[0x1000], *prog_ = prog;
static char outp[0x1000], *outp_ = outp;
static char *regs[0x100];
static char *
walk(char *s)
{
int depth = 0;
char c;
while((c = *s++)) {
if(c == '(') depth++;
if(c == ')') --depth;
if(c == ' ' && !depth)
break;
}
return s - 1;
}
static char *
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 != *b) return NULL;
a++, b++;
}
return b;
}
static int
writereg(char r)
{
int depth = 0;
char c, *s = regs[(int)r];
while((c = *s++)) {
if(c == '(') depth++;
if(c == ')') --depth;
if(c == ' ' && !depth)
break;
*outp_++ = c;
}
return 1;
}
static int
rewrite(void)
{
char c, *p = prog;
printf("STEP ---------\n");
while((c = *p)) {
int i, found = 0;
for(i = 0; i < rules_len; i++) {
Rule *r = &rules[i];
char *res = match(p, r);
if(res != NULL) {
char cc, *b = r->b;
printf("MATCH: %s -> %s\n", r->a, r->b);
while((cc = *b++)) {
if(cc == '?')
writereg(*b++);
else
*outp_++ = cc;
}
found = 1;
p = res;
}
}
if(!found) {
*outp_++ = c;
p++;
}
}
*outp_++ = 0;
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("\nStep %s -- %s\n", prog, outp);
}
static char *
parse_rulefrag(FILE *f)
{
int depth = 0;
char c, *origin = dict_;
while(f && fread(&c, 1, 1, f) && c && c != 0xa) {
if(c == '(') depth++;
if(c == ')') --depth;
if(c == ' ' && !depth)
break;
else
*dict_++ = c;
}
*dict_++ = 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)
*prog_++ = c == 0xa ? 0x20 : c;
}
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;
}
static void
save(void)
{
int i, end = outp_ - outp;
for(i = 0; i < end; i++)
prog[i] = outp[i];
prog[i] = 0;
}
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]);
rewrite();
display();
save();
rewrite();
display();
return 0;
}