Open In App

Introduction to YACC

Each translation rule input to YACC has a string specification that resembles a production of a grammar-it has a nonterminal on the LHS and a few alternatives on the RHS. For simplicity, we will refer to a string specification as a production. YACC generates an LALR(1) parser for language L from the productions, which is a bottom-up parser. The parser would operate as follows: For a shift action, it would invoke the scanner to obtain the next token and continue the parse by using that token. While performing a reduced action in accordance with production, it would perform the semantic action associated with that production. 

The semantic actions associated with productions achieve the building of an intermediate representation or target code as follows: 



A parser generator is a program that takes as input a specification of a syntax and produces as output a procedure for recognizing that language. Historically, they are also called compiler compilers. YACC (yet another compiler-compiler) is an LALR(1) (LookAhead, Left-to-right, Rightmost derivation producer with 1 lookahead token) parser generator. YACC was originally designed for being complemented by Lex. 

Input File: YACC input file is divided into three parts.



/* definitions */
 ....

%% 
/* rules */ 
....
%% 

/* auxiliary routines */
.... 

Input File: Definition Part:

%token NUMBER 
%token ID 
%token NUMBER 621 
%start nonterminal 

Input File: Rule Part:

Input File: Auxiliary Routines Part:

Input File:

#include "lex.yy.c"  
 .y 

Output Files:

Example: Yacc File (.y) 




%{
   #include <ctype.h>
   #include <stdio.h>
   #define YYSTYPE double /* double type for yacc stack */
%}
 
%%
 Lines :  Lines S '\n' { printf("OK \n"); }
       |  S '\n’
       |  error '\n' {yyerror("Error: reenter last line:");
                        yyerrok; };
 S     :  '(' S ')’
       '[' S ']’
       |   /* empty */    ;
%%
 
#include "lex.yy.c"
  
void yyerror(char * s)
/* yacc error handler */
{  
 fprintf (stderr, "%s\n", s);
}
  
int main(void)
 {
 return yyparse();
 

Lex File (.l) 




%{
%}
 
%%
[ \t]     { /* skip blanks and tabs */ }
\n|.      { return yytext[0]; }
%%

For Compiling YACC Program:

  1. Write lex program in a file file.l and yacc in a file file.y
  2. Open Terminal and Navigate to the Directory where you have saved the files.
  3. type lex file.l
  4. type yacc file.y
  5. type cc lex.yy.c y.tab.h -ll
  6. type ./a.out

Article Tags :