Bison Marcin Zubrowski
What is it YACC – Yet Another Compiler Compiler Parser Generator Define the BNF Context-free grammar By default generates an LALR parser, but you can generate a GLR parser For C, C++, and Java Can be used in conjunction with Flex Need some sort of lexical analyzer for token input
Bison Grammar File To define the language for Bison you need to write a Grammar File
Bison Grammar File General Structure C declarations Header files Can omit this section
Bison Grammar File – Bison Declarations Declare tokens “%type” specifies your nonterminals “%Union” specifies the different types that the lexical analysis can return “%Start” defines the starting rule Can be omitted, will see the first rule defined as start
Bison Grammar File – Grammar Rules General rule format ‘|’ for multiple rules that have the same result Actions follow the rule
Show Example Calc.y
The Bison Parser Algorithm Bison reads tokens and pushes them onto the parser stack Bison looks at the stack and decides the reduction based on the rules you set Tries to reduce the stack to a single grouping, which is the start symbol Reductions are based on the look-ahead token
The Bison Parser Algorithm (cont.) Can handle shift/reduce conflicts if the number of shift/reduce conflicts is exactly n Use the “%expect n” declaration to avoid warnings Else you may need to specify operator precedence with “%left” and “%right”
The Bison Parser Algorithm (cont.) Imagine we have “1 – 2 * 3” ‘1’, ‘-’, and ‘2’ are on the stack, do we reduce or shift? Each will produce different results “1 – (2 op 3)” vs. “(1 – 2) op 3” The first is right precedence which is preferable for assignment operators The second is left precedence which is preferable for most operators Declare the operator whose precedence is lower first A third alternative is “%nonassoc”, which declares that it is a syntax error to find the same operator twice in a row
The Bison Parser Algorithm (cont.) Bison handles reduce/reduce conflicts by choosing the first rule that appears in the grammar which is risky Just rewrite your rules