%{ #define YYDEBUG 1 #include #include #include #include "prodrules.h" #include "tree.h" struct node *yyroot; %} %union { struct node *np; } /* YACC Declarations */ %token NUM '\n' '(' ')' %left '-' '+' %left '*' '/' %left NEG /* negation--unary minus */ %right '^' /* exponentiation */ %type input line exp mystart /* Grammar follows */ %% mystart: input { yyroot = $1 ; printf("setting yyroot to %p\n", yyroot); } ; input: input line { $$ = alcnary(INPUT, INPUT_R2, 2, $1, $2); printf("setting input $$ to %p\n", $$); } | { $$ = alcleaf( 0, ""); printf("$$ NULL\n"); } ; line: '\n' { $$ = alcnary(LINE, LINE_R1, 1, $1); } | exp '\n' { $$ = alcnary(LINE, LINE_R2, 2, $1, $2); } ; exp: NUM { $$ = $1; /* syntax tree vs. parse tree*/ } | exp '+' exp { $$ = alcternary(EXP, EXP_R2, $1, $2, $3);} | exp '-' exp { $$ = alcnary(EXP, EXP_R3, 3, $1, $2, $3);} | exp '*' exp { $$ = alcnary(EXP, EXP_R4, 3, $1, $2, $3);} | exp '/' exp { $$ = alcnary(EXP, EXP_R5, 3, $1, $2, $3);} | '-' exp %prec NEG { $$ = alcnary(EXP, EXP_R6, 2, $1, $2);} | exp '^' exp { $$ = alcnary(EXP, EXP_R7, 3, $1, $2, $3);} | '(' exp ')' { $$ = alcnary(EXP, EXP_R8, 3, $1, $2, $3);} ; %% #if 0 static char line[1024]; int advance(int n) { int i; for (i=n; line[i]; i++) line[i-n] = line[i]; line[i-n] = line[i]; } int yylex() { int tok, val; static int token_char; if (!strcmp(line, "")) { if (fgets(line, 1024, stdin) == NULL) { return -1; } } switch (line[0]) { case '\n': { advance(1); return '\n'; } case ' ': case '\t': { advance(1); return yylex(); } case '+': case '-': case '*': case '/': case '^': case '(': case ')': { int rv = line[0]; advance(1); return rv; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': { val = atoi(line); yylval.np = (struct node *)malloc(sizeof(struct node)); yylval.np->symbol = NUM; yylval.np->t.val = val; yylval.np->t.lexeme = strdup(line); /* unfinished: trim lexeme to stop at first char after number*/ while (isdigit(line[0]) || (line[0]=='.')) advance(1); return NUM; } } } #endif int yyerror(char *s) { fprintf(stderr, "%s\n", s); fflush(stderr); } int main() { int rv; /* yydebug = 1; */ printf("---calling yyparse---\n"); rv = yyparse(); printf("---yyparse returned %d---\n", rv); printf("---calling treeprint---\n"); treeprint(yyroot); printf("---done w/ treeprint---\n"); }