Experiment No 7 - SPCC
Experiment No 7 - SPCC
Kulra(W)Department of
Computer Engineering
CSL601: System Programming and Compiler Construction Lab2023-
24
Experiment No. 07
Experiment Title
Parser generator tool : Yacc.
Task:
Student Name
Roll No.
•
Bottom-Up Parsing: Utilizes LR parsing for efficient
analysis of context-free grammars.
•
Symbol Table Management: Supports the creation and
management of symbol tables during parsing.
•
Action Code Embedding: Allows developers to embed
custom action code within grammar rules.
•
Error Handling: Provides mechanisms for handling
syntax errors gracefully during parsing.
•
Integration with Lex/Flex: Works seamlessly with
lexical analyzer generators like Lex/Flex.
•
Modularity and Reusability: Promotes modularity and
reusability in compiler design by separating parsing
from other compiler phases.
•
Compiler Construction Support: Essential tool for
building compilers, interpreters, and language
processors.
•
1) Explain how to Define Terminals and Non-Terminals:
write production • Terminals: These are the basic symbols in the
rules in yacc language, such as identifiers,
specification with keywords, operators, and punctuation.
example • Non-Terminals: These are symbols that
represent groups of terminals and/or other
non-terminals and are used to define the
structure of statements or expressions.
•
Use Syntax for Production Rules:
• Production rules follow the syntax: non-
terminal : symbols... ;
• The non-terminal is a symbol that appears on
the left-hand side of the rule and represents a
higher-level construct in the language.
• The symbols on the right-hand side can
include terminals (enclosed in quotes) and/or
non-terminals.
•
Example Production Rules:
%{
#include <stdio.h>
%}
%token NUMBER
%token PLUS MULTIPLY
%left PLUS
%left MULTIPLY
%%
expr : expr PLUS expr { printf("%d + %d\n", $1, $3); $$ =
$1 + $3; }
| expr MULTIPLY expr { printf("%d * %d\n", $1, $3); $$ =
$1 * $3; }
| NUMBER { printf("Number: %d\n", $1); $$ = $1; }
;
%%
int main() {
yyparse();
return 0;
}
In this example:
• %token is used to define terminals (NUMBER,
PLUS, MULTIPLY).
• %left specifies the associativity and precedence of
operators.
• expr is a non-terminal representing an arithmetic
expression.
• The production rules define how expressions are
formed using addition, multiplication, and numbers.
• The action code within curly braces performs
semantic actions like printing and
computation.
• $$ refers to the result of the production rule, and $1,
$3 refer to the symbols on the right-hand side.
%%
int yywrap(){
return 1;
}
cal.y
%{
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int yylex(void);
int yyerror();
%}
%%
%%
int main(){
yyparse();
return 0;
}
int yyerror(){
exit(0);
}
Output of
the
program: