YACC Basics and Example
YACC Basics and Example
chatgpt.com/c/673ace29-5050-8013-914f-326e96fbc6a5
YACC (Yet Another Compiler Compiler) is a tool used to generate parsers, which are
essential components in compilers and interpreters. It takes a formal grammar
specification (usually written in Backus-Naur Form or similar) and generates source code
for a parser that recognizes the language described by that grammar.
Key Features:
1. Input:
1/6
2. Generate Parser: Use the yacc command to process the .y file and generate a .c
file (e.g., y.tab.c).
3. Compile and Link: Compile the generated C file, often linking it with a scanner
produced by lex.
4. Execute Parser: Run the final executable to parse input and execute actions based
on grammar rules.
2/6
yacc
%{
#include <stdio.h>
#include <stdlib.h>
%}
%token NUM
%left '+' '-'
%left '*' '/'
%%
input:
/* empty */
| input line
;
line:
'\n'
| expr '\n' { printf("Result: %d\n", $1); }
;
expr:
NUM { $$ = $1; }
| expr '+' expr { $$ = $1 + $3; }
| expr '-' expr { $$ = $1 - $3; }
| expr '*' expr { $$ = $1 * $3; }
| expr '/' expr { $$ = $1 / $3; }
;
%%
int main() {
return yyparse();
}
3/6
lex
%{
#include "y.tab.h"
%}
%%
[0-9]+ { yylval = atoi(yytext); return NUM; }
[+\-*/] { return yytext[0]; }
\n { return '\n'; }
[ \t] { /* Ignore whitespace */ }
. { return yytext[0]; }
%%
Compilation:
1. Generate y.tab.c and y.tab.h using YACC:
bash
yacc -d calc.y
bash
lex calc.l
4/6
3. Compile and link:
bash
bash
./calc
Input/Output:
Input:
3 + 4
Output:
5/6
makefile
Result: 7
Applications of YACC:
Compilers and interpreters.
Code generation tools.
Query language parsers (e.g., SQL).
Domain-specific languages.
6/6