/* * * Interpreter for the language decsribed by the grammar below * * written by Andrew Taylor andrewt@cse.unsw.edu.au * October 2005 as a the starting point * for a COMP1721 lab exercise * * * Statement --> Identifier = Term ; * Statement --> output Term ; * * Term --> Identifier * --> Int_Constant */ #include "cavy_syntax.h" #include #include typedef struct variable variable; struct variable { char *name; variable *next; int value; }; void statement(void); int term(void); int *lookup_variable(char *name); token *expect(token_type expected_type); /* * Interpret a single statement * * Statement --> Identifier = Term ; * Statement --> output Term ; * * You need to change this method. */ void statement(void) { token *t; t = get_token(); if (t->type == T_PUTI) { printf("%d\n", term()); } else if (t->type == T_IDENTIFIER) { int *i = lookup_variable(t->text); expect(T_ASSIGNMENT); *i = term(); } else { printf("Unexpected token in expression: %s\n", token_type_to_string(t->type)); return; } expect(T_SEMICOLON); } /* * Interpret a term * and return its value * * Term --> Identifier * --> Int_Constant * * YOU NEED TO CHANGE THIS METHOD */ int term() { token *t; t = get_token(); if (t->type == T_CONSTANT) return t->int_value; if (t->type == T_IDENTIFIER) { int *i = lookup_variable(t->text); return *i; } printf("Unexpected token in term: %s\n", token_type_to_string(t->type)); return 0; } /* * PUT YOUR CODE ABOVE HERE * * DO NOT CHANGE THE CODE BELOW HERE */ int main(void) { open_lexical_analysis(stdin); printf("> "); while (view_token(0)->type != T_EOF) { statement(); printf("> "); } return 0; } /* * Find the int variable associated with a name. * * A pointer to the int variable is returned. * * If the name has not been previously associated * with an int variable, a variable is created * and initialized to zero. */ int * lookup_variable(char *name) { static variable *list; variable *v; for (v = list; v != NULL; v = v->next) if (strcmp(name, v->name) == 0) return &(v->value); if ((v = malloc(sizeof *v)) == NULL) { fprintf(stderr, "Out of memory\n"); exit(1); } v->name = name; v->next = list; v->value = 0; list = v; return &(v->value); } /* * Get the next token and check that it is of the specified type, * if not print an error message and exit. The token is returned. */ token * expect(token_type expected_type) { token *next = get_token(); if (next->type != expected_type) { printf("Syntax error - expected %s found %s\n", token_type_to_string(expected_type), token_type_to_string(next->type)); exit(1); } return next; }