Parser generators: YACC and Bison
Practical study notes on parser generators YACC and Bison: what they are, how they work, important syntax and directives, example grammars, and common exam questions.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Parser generators are tools engineers use to convert a language grammar into a parser automatically. YACC and Bison let you write a high-level grammar and semantic actions so the front end of a compiler (the parser and parts of the semantic analysis) is produced faster and with fewer bugs.
Key ideas
- Bison: the GNU replacement for YACC. It is backward-compatible with YACC in most uses and adds extensions (better error messages, more skeletons, C++ support, GLR parsing via
%glr-parser, %union improvements). - Grammar: a set of productions (rules) of the form A -> α where A is a nonterminal and α is a string of terminals and nonterminals. Terminals are token types provided by the lexer (e.g., IDENT, NUM, '+'). The start symbol is the special nonterminal from which parsing begins.
- Token: a unit of lexical input returned by the lexer (for example, an INTEGER or IDENTIFIER). The lexer (e.g., lex or Flex) produces tokens for the parser.
- Semantic action: code snippets (usually C/C++) placed in grammar rules that run when a rule is reduced. In YACC/Bison these are written between braces
{ ... }after a production. - YYSTYPE: the C type (or union) used for semantic values of tokens and nonterminals. In Bison you set this by
%unionand use typed symbols with<tag>. - LALR(1): a class of bottom-up parsers called Look-Ahead LR with 1 token of lookahead. YACC/Bison produce LALR(1) parsers: they are constructed by merging LR(1) item sets that share the same LR(0) cores, using lookaheads to decide actions.
- Shift-reduce conflict: when the parser state and lookahead token allow both a shift (push a token) and a reduce (apply a production). YACC/Bison report these as conflicts; they are resolved by default rules (shift over reduce) or by explicit precedence directives.
- Reduce-reduce conflict: when two different reductions are both possible; usually indicates an ambiguous grammar.
- Precedence and associativity directives: in YACC/Bison you declare precedence with
%left,%right,%nonassocfollowed by tokens. These help resolve shift-reduce conflicts by comparing precedence of the incoming token and the production. Later precedence lines have higher precedence. A rule’s precedence is that of its rightmost terminal unless overridden with%prec TOKEN. - Skeleton: the template source file (runtime) that Bison/YACC combine with the grammar to form the final parser (contains the parsing engine and support functions).
Exact statements students should memorise (unambiguous and exam style):
- "A context-free grammar G = (V, Σ, P, S) where V is the set of nonterminals, Σ is the set of terminals, P is the set of productions, and S ∈ V is the start symbol." State this when asked for formal definition of grammar.
- "If merging LR(1) item sets with identical LR(0) cores introduces no new conflicts, the resulting LALR(1) parser recognizes the same language as the canonical LR(1) parser for that grammar." Assume standard construction of LR(1) and the LALR(1) merging procedure.
What to draw in an exam when asked about parser-generator internals:
- Draw an LR automaton: draw states as circles with sets of items (e.g., [E -> E . + T, $]) and labeled arrows for shifts on terminals and goto on nonterminals. Label start state and accepting state. Show one shift-reduce conflict: mark the state with both a shift arrow and a reduce action.
- For precedence resolution: draw a small table showing token precedences (e.g.,
%left '+' '-',%left '*' '/') and explain which action is chosen for inputE + E * E.
Derivation commonly asked: show how to convert an ambiguous expression grammar into one with precedence via precedence declarations or by rewriting grammar into E -> E + T | T and T -> T * F | F then show associativity by recursion position.
Formulas
(Note: for this programming topic, list syntax and commands to remember.)
%token NAME ... — declare token named NAME (used in grammar). NAME is a C identifier.
%left '+' '-' — declare left associativity for tokens '+' and '-' (resolves conflicts).
%right '^' — declare right associativity for '^'.
%nonassoc '<' '>' — declare non-associative.
%union { ... } — declare the union type for semantic values (YYSTYPE fields inside braces). Declare %union before any %type or typed %token that use its tags.
%type <tag> nonterminal — declare the semantic type (tag from %union) for a nonterminal.
%% — separates declarations, grammar rules, and C code sections in a YACC/Bison file.
name: rule1 { action1 } | rule2 { action2 } ; — grammar rule with semantic actions.
yacc -d -v file.y — generate y.tab.c, y.tab.h, and y.output (names may vary by implementation).
bison -d -v file.y — generate file.tab.c, file.tab.h, and file.output (use -o to set output names; in --yacc mode Bison may produce y.tab.c/y.output).
yylex() — function called by parser to get next token value from lexer.
yyparse() — function generated by parser to start parsing on tokens from yylex(). Define yyerror(const char *s) for diagnostics, and use the special token error in grammar rules for error recovery.
For each symbol, the name is self-explanatory; these apply when writing a .y grammar file for YACC or Bison targeting C.
Worked examples
Example 1 — Simple arithmetic grammar in Bison and its evaluation (exam-style model answer): Grammar (write inside .y file):
%union { int ival; }
%token <ival> NUM
%left '+' '-'
%left '*' '/'
%type <ival> expr
%%
input: /* empty */
| input expr '\n' { printf("%d\n", $2); }
;
expr: NUM { $$ = $1; }
| expr '+' expr { $$ = $1 + $3; }
| expr '*' expr { $$ = $1 * $3; }
;
%%
Step-by-step for input 3 + 4 * 5\n: (1) Lexer returns NUM(3), '+', NUM(4), '*', NUM(5), '\n'. (2) Parser uses precedence: * has higher precedence so reduces 4 * 5 to 20, then 3 + 20 to 23. Final printed result 23. Show the stack contents at each shift/reduce step: list of states and symbols, indicate reductions.
Example 2 — Shift-reduce conflict and precedence resolution (trace): Grammar snippet that causes dangling else:
stmt: IF '(' expr ')' stmt
| IF '(' expr ')' stmt ELSE stmt
| other
;
This grammar is ambiguous (shift-reduce conflict on ELSE). YACC/Bison resolve by preferring shift by default, which results in the usual rule that else pairs with nearest unmatched if. To show resolution in exam: draw the state where lookahead ELSE leads both to shift (into ELSE branch) and reduce (reduce the shorter if production). Explain that default is shift; to force different behavior, give ELSE higher precedence and attach a lower precedence to the shorter rule using %prec, e.g., declare %nonassoc ELSE and write stmt: IF '(' expr ')' stmt %prec ELSE | IF '(' expr ')' stmt ELSE stmt | other ;.
Example 3 — Bison command and files (practical steps):
- Write grammar in
calc.yand lexer inlex.l. - Run
bison -d -v calc.y(createscalc.tab.c,calc.tab.h, andcalc.output; in --yacc mode these may bey.tab.c,y.tab.h,y.output). - Run
flex lex.l→lex.yy.c. - Compile:
cc calc.tab.c lex.yy.c -lfl -o calc. - Run
./calcand type expressions. (Verify that-lflis correct link on your system.)
Common mistakes
- Using wrong field names in
%unionor mismatching%type <tag>and accessing$1as wrong type—causes runtime crashes. - Expecting Bison to detect all ambiguities: it reports conflicts but may still produce a parser using default resolutions; do not assume grammar is unambiguous.
- Mixing
%leftand%rightwithout understanding that just ordering of precedence lines matters (later lines have higher precedence). - Forgetting to return token semantic value in
yylex()(setyylval) — tokens arrive with empty values.
For your exam
Possible question types:
- Definitions: define parser generator, LALR(1), shift-reduce conflict; include a short example.
- Short notes: differences between YACC and Bison, role of
%union,%type,%left/%right. - Derivations: show LR(0)/LALR(1) item construction for a small grammar; show where conflicts arise.
- Programs: write a .y file for an arithmetic evaluator and explain how lex and yacc/bison interact.
- Diagrams: draw LR automaton, label states and transitions; mark conflict state.
What a full-marks answer includes:
- Clear definitions with bolded terms (e.g., LALR(1)).
- Correct sample grammar or code snippet following YACC/Bison syntax with
%%sections. - If asked, a step-by-step construction of item sets or a parse trace showing stack content, lookahead, and action (shift/reduce).
- Explanation of how conflicts are resolved (default rule and precedence declarations) and any assumptions made.
Quick check
- What directive declares token types in a Bison .y file?
- What default action does YACC/Bison take when a shift-reduce conflict appears?
- Name the function Bison generates to start parsing.
Answers:
%token; prefer shift over reduce;yyparse().
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?