added print table functionality to main in grammar.y with custom EOF input in '!'

This commit is contained in:
Partho Bhattacharya
2025-02-27 17:58:01 -05:00
parent 77596a9d96
commit fad44e21ea
3 changed files with 22 additions and 10 deletions

View File

@ -8,7 +8,9 @@
extern int yylex(void); extern int yylex(void);
void yyerror(const char *err); void yyerror(const char *err);
extern char* yytext; extern char* yytext;
extern int yychar; extern int yychar;
SymbolTable * st;
%} %}
%token ID 101 %token ID 101
@ -59,28 +61,28 @@
%token COMMENT 700 %token COMMENT 700
%% %%
input: /*empty for now*/ start: /*empty for now*/
OPTIONAL; OPTIONAL;
OPTIONAL: OPTIONAL:
L_BRACKET {printf("success");}; L_BRACKET {printf("success");};
// B : '{'{CreateScope(cur,line,column)} E '}'; //Braced Expressions can have braces removed to get regular expressions
// D : '[' l ']'; //Declaration Lists Brackets can be taken out to get a list of Declarations
// E : Maybe_D U; //An expression can start with an optional D followed by an undeclared segment
// Maybe_D : D
// | ; //Either D or not
//l : A ';' l;
// | ; //a declaration list can either be empty or be an assignment followed by a semi-colon and another list
//
%% %%
void yyerror(const char *err) { void yyerror(const char *err) {
fprintf(stderr, "Error: %s\n", err); fprintf(stderr, "Error: %s\n", err);
} }
int main() { int main() {
st=CreateScope(NULL,1,1);
int a; int a;
while (a = yyparse()){ while ((a = yyparse()) != EOF){
printf("%d = a: yytext = %s: yychar = %d\n", a, yytext, yychar); printf("%d = a: yytext = %s: yychar = %d\n", a, yytext, yychar);
if(yytext[0] == '!'){
print_symbol_table(getAncestor(st),stdout);
break;
}
} }
return 0; return 0;
} }

BIN
parser

Binary file not shown.

View File

@ -64,6 +64,16 @@ TableNode * look_up(SymbolTable * table, char * x){
} }
return look_up(table->Parent_Scope, x); return look_up(table->Parent_Scope, x);
} }
SymbolTable * getAncestor(SymbolTable * table){
if(table->Parent_Scope == NULL){
//if table has no parent, return itself
return table;
} else {
//call function recursively to grab ancestor
return getAncestor(table->Parent_Scope);
}
}
void print_symbol_table(SymbolTable *table, FILE *file_ptr){ void print_symbol_table(SymbolTable *table, FILE *file_ptr){
if(table->Parent_Scope == NULL){ if(table->Parent_Scope == NULL){
fprintf(file_ptr, "%-17s: %-6s : %-6s : %-21s: %-28s\n", "NAME", "SCOPE", "PARENT", "TYPE", "Extra annotation"); fprintf(file_ptr, "%-17s: %-6s : %-6s : %-21s: %-28s\n", "NAME", "SCOPE", "PARENT", "TYPE", "Extra annotation");