Introduction to Yacc Ying-Hung Jiang
Outlines Review of parser Introduction to yacc Cooperate with lex Semantic routines Resources
Review of Parser Parser invokes scanner for tokens. Parser analyze the syntactic structure according to grammars. Finally, parser executes the semantic routines. See teacher ’ s slide
Introduction to yacc Yacc – yet another compiler compiler. An LALR(1) parser generator. Yacc generates – Tables – according to the grammar rules. – Driver routines – in C programming language. – y.output – a report file.
Cooperate with lex Invokes yylex() automatically. Generate y.tab.h file through the -d option. The lex input file must contains y.tab.h For each token that lex recognized, a number is returned (from yylex() function.)
Writing Yacc Input File A Yacc input file consists of three sections: – Definition – Rules – User code Separate by % Similar to lex (actually, lex imitates yacc.)
Definition Section C source code, include files, etc. %token Yacc invokes yylex() when a token is required. All terminal symbols should be declared through %token. Yacc produces y.tab.h by %token definitions.
Definition Section %union { } – Default: int Yacc produces C source where YYSTYPE is the type declared by %union. All symbols, include terminal and nonterminal symbols are of type YYSTYPE. %start Default start rule is the first one in rules section.
Rules Section Each rule contains LHS and RHS, separated by a colon and end by a semicolon. White spaces or tabs are allowed. Ex: statement: name EUQALSIGN expression | expression ; expression: number PLUSSIGN number | number MINUSSIGN number ;
Writing Grammar Rules Lex & yacc, 2/e. O ’ REILLY, 1999 The C Programming Language, Prentice-Hall, 1988 The C++ Programming Language, Addison- Wesley, 1991 Some language specifications. Ex: ANSI C, C99, C++98
Semantic Routines The action in semantic routines are executed for the production rule. The action is actually C source code. LHS: $$ RHS: $1 $2 …… Default action: { $$ = $1; } Action between a rule is allowed. For ex: expression : simple_expression | simple_expression {somefunc($1);} relop simple_expression;
Example See the calculator example.
Resources See course website.