Permalink
Browse files

parsin like mofo

  • Loading branch information...
1 parent 09c04bf commit 0d4c23e5f49f230bff885bf60136d8c57b550a78 Alan Dipert committed Jul 2, 2009
Showing with 55 additions and 8 deletions.
  1. BIN .Makefile.swp
  2. +55 −8 parse.c
View
Binary file not shown.
View
63 parse.c
@@ -20,26 +20,50 @@ static Token* t_append(Token *t1, Token *t2) {
}
}
+//recursively free child tokens
+static void t_free(Token *t) {
+}
+
static Token* t_rewind(Token *t) {
while(t->prev) {
t = t->prev;
}
return t;
}
-static void t_pp(Token *t) {
+static void t_tab(int level) {
+ while(level--) {
+ printf("\t");
+ }
+}
+
+static char* op_pp(enum operator_type op) {
+ switch(op) {
+ case ADD: return "add";
+ case SUBTRACT: return "subtract";
+ case MULTIPLY: return "multiply";
+ case DIVIDE: return "divide";
+ default: return "unknown";
+ }
+}
+
+static void t_pp(Token *t, int level) {
if(t != NULL) {
t = t_rewind(t);
do {
switch(t->type) {
case ATOM:
- printf("val: %f\n", t->n_value);
+ t_tab(level);
+ printf("atom: %f\n", t->n_value);
break;
case OPERATOR:
- printf("operator\n");
+ t_tab(level);
+ printf("%s\n", op_pp(t->o_type));
break;
case LIST:
+ t_tab(level);
printf("list\n");
+ t_pp(t->head, level+1);
break;
}
} while ((t = t->next));
@@ -53,8 +77,32 @@ static Token* tokenize(char *input) {
Token *last_token = NULL;
char buf[100];
for(i = 0; i < strlen(input); i++) {
- //numbers
- if(isdigit(input[i])) {
+ if(input[i] == '(') {
+ int p_count = 1;
+ char tmp;
+ m_start = &input[i+1];
+ m_count = 0;
+ while((tmp = input[i+(++m_count)]) != '\0' && p_count != 0) {
+ if(tmp == '(') {
+ p_count++;
+ } else if(tmp == ')') {
+ p_count--;
+ }
+ }
+ if(p_count) {
+ fprintf(stderr, "unmatched parens\n");
+ exit(1);
+ } else {
+ /*printf("all parens match\n");*/
+ strncpy(buf, m_start, m_count-1);
+ buf[m_count-2] = '\0';
+ Token *t2 = t_mk();
+ t2->type = LIST;
+ t2->head = tokenize(buf);
+ last_token = t_append(last_token, t2);
+ }
+ i += m_count;
+ } else if(isdigit(input[i])) {
m_start = &input[i];
m_count = 1;
while(isdigit(m_start[m_count]) || m_start[m_count] == '.'){
@@ -64,7 +112,7 @@ static Token* tokenize(char *input) {
t2->type = ATOM;
t2->a_type = NUMBER;
strncpy(buf, m_start, m_count);
- buf[m_count+1] = '\0';
+ buf[m_count] = '\0';
t2->n_value = atof(buf);
last_token = t_append(last_token, t2);
i += m_count;
@@ -77,10 +125,9 @@ static Token* tokenize(char *input) {
}
}
- t_pp(last_token);
return last_token;
}
void eval(char *input) {
- tokenize(input);
+ t_pp(tokenize(input), 0);
}

0 comments on commit 0d4c23e

Please sign in to comment.