L
luserXtrog
Hello all,
I've hacked up a little fsm pattern matcher and hit a wall.
I'm not sure what's wrong with it (semantically), but hope
someone can spot something.
TIA
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
void fatal(char *msg) {
fprintf(stderr,"%s\n",msg);
exit(EXIT_FAILURE);
}
typedef struct fsm {
int match;
int (*on_yes)(int);
struct fsm *yes;
struct fsm *no;
} fsm;
fsm *fsm_new() {
fsm *f;
if ((f=malloc(sizeof*f)) == NULL) {
fatal("malloc");
}
f->on_yes = NULL;
f->yes = NULL;
f->no = NULL;
}
fsm *fsm_string (char *s) {
fsm *fh, **ft;
fh = fsm_new();
ft = &fh;
for ( ;*s;s++) {
(*ft)->match = *s;
(*ft)->yes = fsm_new();
ft = &(*ft)->yes;
}
return fh;
}
int fsm_match(fsm *f, char *s) {
while (1)
if (f->match == *s) {
if (f->on_yes) (*f->on_yes)(*s);
if (f->yes) f = f->yes;
else return true;
} else {
if (f->no) f = f->no;
else return false;
}
}
int main() {
fsm *f;
printf("fsm_match(fsm_string(\"foo\"),\"foo\") : %d\n",
fsm_match(f = fsm_string("foo"), "foo") );
return 0;
}
I've hacked up a little fsm pattern matcher and hit a wall.
I'm not sure what's wrong with it (semantically), but hope
someone can spot something.
TIA
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
void fatal(char *msg) {
fprintf(stderr,"%s\n",msg);
exit(EXIT_FAILURE);
}
typedef struct fsm {
int match;
int (*on_yes)(int);
struct fsm *yes;
struct fsm *no;
} fsm;
fsm *fsm_new() {
fsm *f;
if ((f=malloc(sizeof*f)) == NULL) {
fatal("malloc");
}
f->on_yes = NULL;
f->yes = NULL;
f->no = NULL;
}
fsm *fsm_string (char *s) {
fsm *fh, **ft;
fh = fsm_new();
ft = &fh;
for ( ;*s;s++) {
(*ft)->match = *s;
(*ft)->yes = fsm_new();
ft = &(*ft)->yes;
}
return fh;
}
int fsm_match(fsm *f, char *s) {
while (1)
if (f->match == *s) {
if (f->on_yes) (*f->on_yes)(*s);
if (f->yes) f = f->yes;
else return true;
} else {
if (f->no) f = f->no;
else return false;
}
}
int main() {
fsm *f;
printf("fsm_match(fsm_string(\"foo\"),\"foo\") : %d\n",
fsm_match(f = fsm_string("foo"), "foo") );
return 0;
}