110 likes | 162 Views
Bison: Parser Generator. CSE470: Spring 2000 Updated by Prasad. Motivation. Bison : A general purpose Parser Generator that converts a CFG (Context Free Grammar) description into a C program to parse that grammar. It is also called as YACC (Yet Another Compiler Compiler).
E N D
Bison: Parser Generator CSE470: Spring 2000 Updated by Prasad
Motivation • Bison: A general purpose Parser Generator that converts a CFG (Context Free Grammar) description into a C program to parse that grammar. • It is also called as YACC (Yet Another Compiler Compiler). • Integrates smoothly with Flex for Text Processing. • Responsible for deducing the relationship between the tokens passed on to it by the Lexical Analyzer.
Example for a Grammar Statement NAME ‘=‘ Expression | Expression ; Expression NUMBER | Expression ‘+’ NUMBER | Expression ‘-’ NUMBER ; This grammar can generate expressions like: fred = 12 + 13 fred = 14 + 23 – 11 + 7
Bison Parser • Reads sequence of Tokens as Input • Groups tokens using Grammar rules recursively. (Actually builds a Parse Tree for the input token sequence). • Valid Input: • Entire token sequence reduces to single grouping whose symbol is Grammar’s start symbol. • Invalid Input: • Parser reports syntax error if token sequence cannot be reduced to START symbol of grammar.
Input Text File Lexical Analyzer Call for token token Bison Grammar Files Rules Bison Parser yyparse()
Bison Source %{C Declarations%} Bison Declarations %%Grammar Rules Section%% Additional C Code • Consists of four sections:
Example Bison Rules %token NAME NUMBER %% Statement: NAME ‘=‘ expression | expression { printf(“= %d\n”, $1); } ; expression: expression ‘+’ NUMBER {$$ = $1 + $3; } | expression ‘-’ NUMBER {$$ = $1 - $3; } | NUMBER {$$ = $1;} ; %%
Sample Flex Program for this parser %{ extern int yylval; %} %% [a-zA-Z]+ return NAME; [0-9]+ {yylval = atoi(yytext); return NUMBER; } [ \t]+ ; /* ignore spaces */ \n return 0; . return yytext[0] %%