%{ #include #include #include #include "symtab.h" #define INT_TYPE 0 int yylex() ; void yyerror(const char *s) { fprintf(stderr, "yyerror: %s\n", s) ; exit(1) ; } unsigned int global_var_no = 0 ; FILE *of ; %} %union { char *strval ; int ival ; } %token NAME %token NUMBER %token PRINT VAR %left '+' '-' %left '*' '/' %nonassoc UMINUS %type declaration %type assignment %type print_statement %type expression %% program : program statement | statement ; statement: declaration | assignment | print_statement ; declaration: VAR NAME ';' { fprintf(stderr, "Variable %s delcared.\n", $2) ; st_entry s ; s.type = INT_TYPE ; s.var_no = global_var_no++ ; st_insert($2, s) ; fprintf(of, "VARIABLE %s\n", $2) ; free($2) ; } ; assignment: NAME '=' expression ';' { fprintf(stderr, "Assignment for variable %s.\n", $1) ; st_entry *p ; p = st_find($1) ; fprintf(of, "%s !\n", $1) ; free($1) ; } ; print_statement: PRINT NAME ';' { fprintf(stderr, "Printing variable %s.\n", $2) ; st_entry *p ; p = st_find($2) ; fprintf(of, "%s ? CR\n", $2) ; free($2) ; } ; expression: '(' expression ')' { /* do nothing */ } | expression '+' expression { fprintf (of, "+ ") ; } | expression '-' expression { fprintf (of, "- ") ; } | expression '*' expression { fprintf (of, "* ") ; } | expression '/' expression { fprintf (of, "/ ") ; } | '-' expression %prec UMINUS { fprintf (of, "negate ") ; } | NUMBER { fprintf (of, "%d ", $1) ; } ; %% int main () { st_init() ; /* Currently does nothing */ // fprintf (stderr, "Hello World\n") ; of = fopen ("out.fs", "w") ; assert(of != NULL) ; yyparse() ; fclose(of) ; return 0 ; } /* End of main() */