0% found this document useful (0 votes)
12 views

YACC Basics and Example

Uploaded by

vadini.vatsla76
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

YACC Basics and Example

Uploaded by

vadini.vatsla76
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

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:

Grammar rules in a specific format.


Actions to execute when grammar rules are matched.
2. Output:

C code for the parser.


3. Usage:

Commonly used with lex, a lexical analyzer generator, to build a complete


compiler or interpreter.

Basic Steps to Use YACC:


1. Define Grammar: Write a .y file that contains grammar rules and corresponding
actions.

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.

Example: Simple Calculator

calc.y (YACC file):

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();
}

void yyerror(const char *s) {


fprintf(stderr, "Error: %s\n", s);
}

lex file (calc.l):

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

2. Generate lex.yy.c using Lex:

bash

lex calc.l

4/6
3. Compile and link:

bash

gcc y.tab.c lex.yy.c -o calc -ll

4. Run the calculator:

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

You might also like