Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 5

M.

Ahmed Raza 20021519-050


Hafiz M. Nouman 20021519-111
Talha Fayaz 20021519-112
What is Yacc
• Yacc stands for Yet Another Compiler Compiler.
• It is a tool for generating parsers in syntax analysis just like Lex in lexical
analysis.
• Yacc takes a formal grammar description as input and produces a parser in C or
another programming language.
• Often used in combination with Lex (or Flex) for complete compiler front-end
development.
Structure of a Yacc Program
• Contains declarations, including header files and global variables.
Definitions Section: • Enclosed in %{ ... %} and preceded by the % symbol.

• Defines tokens produced by the lexer.


Token Definitions Section: • Starts with %token followed by token names.

• Heart of the program, specifying the language's syntax.


Grammar Rules Section: • Contains rules describing how to build language constructs.

• Includes actions associated with grammar rules.


C Code Section: • Embedded C code enclosed in curly braces { ... }.

• Contains extra C code and typically includes the program's entry point.
Additional Code Section: • Placed at the end of the Yacc file.
%{#include <stdio.h>
#include <math.h>%}
%union {
double dvalue;}
%token <dvalue> NUMBER
%token PLUS TIMES LPAREN RPAREN
%left PLUS MINUS
%start calc
%%calc: expression { printf("Result: %f\n", $1); } ;
expression: expression PLUS expression { $$ = $1 + $3; }
| expression MINUS expression { $$ = $1 - $3; }
| LPAREN expression RPAREN { $$ = $2; }
| NUMBER { $$ = $1; } ;%%
int yylex();
int yyerror(const char *s) {
fprintf(stderr, "Error: %s\n", s);
return 1;}
int main() { yyparse();
return 0;}

You might also like