%{ #include #include #include #include "symtab.h" #include "strlist.h" #define INT_TYPE 0 int yylex() ; void yyerror(const char *s) { fprintf(stderr, "yyerror: %s\n", s) ; exit(1) ; } int global_var_no = 0 ; int global_str_no = 0 ; FILE *of ; %} %union { char *strval ; int ival ; } %token NAME STRING %token NUMBER %token PRINT PRINTLN VAR %left '+' '-' %left '*' '/' %nonassoc UMINUS %type declaration %type assignment %type print_statement %type expression %% program : statement_list { fprintf(of, "bye\n") ; } ; statement_list : statement_list 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) ; // st_dump() ; fprintf(of, "VARIABLE %s\n", $2) ; free($2) ; } ; assignment: NAME '=' expression ';' { st_entry *p ; fprintf(stderr, "Assignment for variable %s.\n", $1) ; // st_dump() ; p = st_find($1) ; if (p == NULL) { fprintf(stderr, "Error: Undeclared variable: %s\n", $1) ; } else { fprintf(of, "%s !\n", $1) ; } free($1) ; } ; print_statement: PRINT expression ';' { fprintf(of, ".\n") ; } | PRINTLN expression ';' { fprintf(of, ". CR\n") ; } | PRINT STRING ';' { fprintf(stderr, "Printing literal string %s.\n", $2) ; strlist_append(global_str_no, $2, 0) ; global_str_no++ ; fprintf(of, ".\" %s\"\n", $2) ; free($2) ; } | PRINTLN STRING ';' { fprintf(stderr, "Printing literal string %s.\n", $2) ; strlist_append(global_str_no, $2, 1) ; global_str_no++ ; 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) ; } | NAME { st_entry *p ; fprintf(stderr, "Using variable %s in expression.\n", $1) ; // st_dump() ; p = st_find($1) ; if (p == NULL) { fprintf(stderr, "Error: Undeclared variable: %s\n", $1) ; } else { fprintf(of, "%s @ ", $1) ; } free($1) ; } ; %% int main () { /* Set up symbol table and string list */ st_init() ; /* Currently does nothing */ strlist_init() ; fprintf (stderr, "Type in a program\n") ; of = fopen ("out.fs", "w") ; assert(of != NULL) ; yyparse() ; fclose(of) ; strlist_destroy() ; return 0 ; } /* End of main() */