SlideShare a Scribd company logo
Home work for modifying the syntactic analyzer for the
attached compiler by adding to the existing grammar. The full
grammar of the language is shown below. The highlighted
portions of the grammar show what you must either modify or
add to the existing grammar.
function:
function_header {variable} body
function_header:
FUNCTION IDENTIFIER [parameters] RETURNS type ;
variable:
IDENTIFIER : type IS statement
parameters:
parameter {, parameter}
parameter:
IDENTIFIER : type
type:
INTEGER | REAL | BOOLEAN
body:
BEGIN statement END ;
statement: expression ; |
REDUCE operator {statement} ENDREDUCE ; |
IF expression THEN statement ELSE statement ENDIF ; |
CASE expression IS {case} OTHERS ARROW statement ;
ENDCASE ;
operator:
ADDOP | MULOP
case:
WHEN INT_LITERAL ARROW statement
expression:
( expression ) |
REAL_LITERAL
NOT expression
expression binary_operator expression |
|
INT_LITERAL | IDENTIFIER
| BOOL_LITERAL |
binary_operator: ADDOP | MULOP | REMOP | EXPOP | RELOP
| ANDOP | OROP
In the above grammar, the red symbols are nonterminals, the
blue symbols are terminals and the black punctuation are EBNF
metasymbols. The braces denote repetition 0 or more times and
the brackets denote optional.
You must rewrite the grammar to eliminate the EBNF brace and
bracket metasymbols and to incorporate the significance of
parentheses, operator precedence and associativity for all
operators. Among arithmetic operators the exponentiation
operator has highest precedence following by the multiplying
operators and then the adding operators. All relational operators
have the same precedence. Among the binary logical operators,
and has higher precedence than or. Of the categories of
operators, the unary logical operator has highest precedence, the
arithmetic operators have next highest precedence, followed by
the relational operators and finally the binary logical operators.
All operators except the exponentiation operator are left
associative. The directives to specify precedence and
associativity, such as %prec and %left, may not be used
Your parser should be able to correctly parse any syntactically
correct program without any problem.
You must modify the syntactic analyzer to detect and recover
from additional syntax errors using the semicolon as the
synchronization token. To accomplish detecting additional
errors an error production must be added to the function header
and another to the variable declaration.
Your bison input file should not produce any shift/reduce or
reduce/reduce errors. Eliminating them can be difficult so the
best strategy is not introduce any. That is best achieved by
making small incremental additions to the grammar and
ensuring that no addition introduces any such errors.
An example of compilation listing output containing syntax
errors is shown below:
1 -- Multiple errors 2
function main a integer returns real; Syntax Error, Unexpected
INTEGER, expecting ':'
b: integer is * 2; Syntax Error, Unexpected MULOP
c: real is 6.0;
begin
if a > c then 8 b 3.0;
Syntax Error, Unexpected REAL_LITERAL, expecting ';'
9 else
10 b = 4.;
11 endif;
12 ;
Syntax Error, Unexpected ';', expecting END
Lexical Errors 0
Syntax Errors 4
Semantic Errors 0
------------------------------------------------------------
listing.h
// This file contains the function prototypes for the functions
that produce the // compilation listing
enum ErrorCategories {LEXICAL, SYNTAX,
GENERAL_SEMANTIC, DUPLICATE_IDENTIFIER,
UNDECLARED};
void firstLine();
void nextLine();
int lastLine();
void appendError(ErrorCategories errorCategory, string
message);
---------------------------------------------------------------------------
-------
makefile
compile: scanner.o parser.o listing.o
g++ -o compile scanner.o parser.o listing.o
scanner.o: scanner.c listing.h tokens.h
g++ -c scanner.c
scanner.c: scanner.l
flex scanner.l
mv lex.yy.c scanner.c
parser.o: parser.c listing.h
g++ -c parser.c
parser.c tokens.h: parser.y
bison -d -v parser.y
mv parser.tab.c parser.c
mv parser.tab.h tokens.h
listing.o: listing.cc listing.h
g++ -c listing.cc
----------------------------------------------------------
parser.y
%{
#include
using namespace std;
#include "listing.h"
int yylex();
void yyerror(const char* message);
%}
%error-verbose
%token IDENTIFIER
%token INT_LITERAL
%token ADDOP MULOP RELOP ANDOP
%token BEGIN_ BOOLEAN END ENDREDUCE FUNCTION
INTEGER IS REDUCE RETURNS
%%
function:
function_header optional_variable body ;
function_header:
FUNCTION IDENTIFIER RETURNS type ';' ;
optional_variable:
variable |
;
variable:
IDENTIFIER ':' type IS statement_ ;
type:
INTEGER |
BOOLEAN ;
body:
BEGIN_ statement_ END ';' ;
statement_:
statement ';' |
error ';' ;
statement:
expression |
REDUCE operator reductions ENDREDUCE ;
operator:
ADDOP |
MULOP ;
reductions:
reductions statement_ |
;
expression:
expression ANDOP relation |
relation ;
relation:
relation RELOP term |
term;
term:
term ADDOP factor |
factor ;
factor:
factor MULOP primary |
primary ;
primary:
'(' expression ')' |
INT_LITERAL |
IDENTIFIER ;
%%
void yyerror(const char* message)
{
appendError(SYNTAX, message);
}
int main(int argc, char *argv[])
{
firstLine();
yyparse();
lastLine();
return 0;
}
------------------------------------------------------------------------
scanner
/* Compiler Theory and Design
Dr. Duane J. Jarc */
/* This file contains flex input file */
%{
#include
#include
using namespace std;
#include "listing.h"
#include "tokens.h"
%}
%option noyywrap
ws [ tr]+
comment --.*n
line [n]
id [A-Za-z][A-Za-z0-9]*
digit [0-9]
int {digit}+
punc [(),:;]
%%
{ws} { ECHO; }
{comment} { ECHO; nextLine();}
{line} { ECHO; nextLine();}
"<" { ECHO; return(RELOP); }
"+" { ECHO; return(ADDOP); }
"*" { ECHO; return(MULOP); }
begin { ECHO; return(BEGIN_); }
boolean { ECHO; return(BOOLEAN); }
end { ECHO; return(END); }
endreduce { ECHO; return(ENDREDUCE); }
function { ECHO; return(FUNCTION); }
integer { ECHO; return(INTEGER); }
is { ECHO; return(IS); }
reduce { ECHO; return REDUCE; }
returns { ECHO; return(RETURNS); }
and { ECHO; return(ANDOP); }
{id} { ECHO; return(IDENTIFIER);}
{int} { ECHO; return(INT_LITERAL); }
{punc} { ECHO; return(yytext[0]); }
. { ECHO; appendError(LEXICAL, yytext); }
%%
----------------------------------------------------------------
listing.cc
// Compiler Theory and Design
// Dr. Duane J. Jarc
// This file contains the bodies of the functions that produces
the compilation
// listing
#include
#include
using namespace std;
#include "listing.h"
static int lineNumber;
static string error = "";
static int totalErrors = 0;
static void displayErrors();
void firstLine()
{
lineNumber = 1;
printf("n%4d ",lineNumber);
}
void nextLine()
{
displayErrors();
lineNumber++;
printf("%4d ",lineNumber);
}
int lastLine()
{
printf("r");
displayErrors();
printf(" n");
return totalErrors;
}
void appendError(ErrorCategories errorCategory, string
message)
{
string messages[] = { "Lexical Error, Invalid Character ", "",
"Semantic Error, ", "Semantic Error, Duplicate Identifier:
",
"Semantic Error, Undeclared " };
error = messages[errorCategory] + message;
totalErrors++;
}
void displayErrors()
{
if (error != "")
printf("%sn", error.c_str());
error = "";
}
----------------------------------------------------------

More Related Content

PPT
Arithmetic.ppt
PPTX
Approaches to Grammar - Book Third Edition
PDF
Grammar 2
PPTX
Vowels latest
PDF
English vowel , monothongs, diphthong, triphthongs
PPTX
Teaching Oral Communication Skills
PPTX
Pronunciation
PDF
Fundamental aspects of language teaching
Arithmetic.ppt
Approaches to Grammar - Book Third Edition
Grammar 2
Vowels latest
English vowel , monothongs, diphthong, triphthongs
Teaching Oral Communication Skills
Pronunciation
Fundamental aspects of language teaching

What's hot (20)

PPTX
Phonetics & phonology, INTRODUCTION, Dr, Salama Embarak
ODP
Grammatical gender
PPT
English word stress
PPTX
What is Phonology?
PDF
Summary of ELT Methods & Approaches
PPTX
Grammar Translation Method (G.T.M)
PPTX
Teaching vocabulary
POT
Structural approach
PPTX
Myths and Misconceptions about Grammar
PPTX
Traditional grammar ppt
PPTX
Arabic syllable structure and stress
PPTX
Standard and non standard englishes
PDF
Jordanian arabic between diglossia and bilingualism
PPT
Generative grammar
PPT
Weak ,Strong Syllables2
PPTX
English language teaching, ch4
PPSX
Graphic organizers
PPTX
trapezoid and its properties
PPT
Teaching vocabulary & grammar
Phonetics & phonology, INTRODUCTION, Dr, Salama Embarak
Grammatical gender
English word stress
What is Phonology?
Summary of ELT Methods & Approaches
Grammar Translation Method (G.T.M)
Teaching vocabulary
Structural approach
Myths and Misconceptions about Grammar
Traditional grammar ppt
Arabic syllable structure and stress
Standard and non standard englishes
Jordanian arabic between diglossia and bilingualism
Generative grammar
Weak ,Strong Syllables2
English language teaching, ch4
Graphic organizers
trapezoid and its properties
Teaching vocabulary & grammar
Ad

Similar to Home work for modifying the syntactic analyzer for the attached comp.docx (20)

PDF
You should be able to use the same function to check a narrowing fun.pdf
PPTX
PLSQLmy Updated (1).pptx
PPTX
Programming-in-C
PPTX
Programming in C
DOCX
Basics of c++
PDF
learn basic to advance C Programming Notes
PPT
the new education support for software new
PPTX
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
PPT
Fundamentals of c programming techniques
PPTX
Materi_Pemrograman_-Variable-and-Input-Output.pptx
PDF
Dive into Python Functions Fundamental Concepts.pdf
PDF
PSPC-UNIT-4.pdf
PPT
Error management
DOCX
CS 280 Fall 2022 Programming Assignment 2 November.docx
PDF
Presentation 2 (1).pdf
PPTX
Functions.pptx, programming language in c
PPT
Php Error Handling
PPT
P H P Part I, By Kian
PPTX
MODULE hdsfsf gefegsfs wfefwfwfg etegeg.pptx
You should be able to use the same function to check a narrowing fun.pdf
PLSQLmy Updated (1).pptx
Programming-in-C
Programming in C
Basics of c++
learn basic to advance C Programming Notes
the new education support for software new
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
Fundamentals of c programming techniques
Materi_Pemrograman_-Variable-and-Input-Output.pptx
Dive into Python Functions Fundamental Concepts.pdf
PSPC-UNIT-4.pdf
Error management
CS 280 Fall 2022 Programming Assignment 2 November.docx
Presentation 2 (1).pdf
Functions.pptx, programming language in c
Php Error Handling
P H P Part I, By Kian
MODULE hdsfsf gefegsfs wfefwfwfg etegeg.pptx
Ad

More from simonithomas47935 (20)

DOCX
Hours, A. (2014). Reading Fairy Tales and Playing A Way of Treati.docx
DOCX
How are authentication and authorization alike and how are the.docx
DOCX
How are self-esteem and self-concept different What is the or.docx
DOCX
How are morality and religion similar and how are they different.docx
DOCX
How are financial statements used to evaluate business activities.docx
DOCX
How are Japanese and Chinese Americans similar How are they differe.docx
DOCX
Hot Spot PolicingPlace can be an important aspect of crime and.docx
DOCX
HOSP3075 Brand Analysis Paper 1This is the first of three assignme.docx
DOCX
Hou, J., Li, Y., Yu, J. & Shi, W. (2020). A Survey on Digital Fo.docx
DOCX
How (Not) to be Secular by James K.A. SmithSecular (1)—the ea.docx
DOCX
Hopefully, you enjoyed this class on Digital Media and Society.Q.docx
DOCX
hoose (1) one childhood experience from the list provided below..docx
DOCX
honesty, hard work, caring, excellence HIS 1110 Dr. .docx
DOCX
hoose one of the four following visualsImage courtesy o.docx
DOCX
HomeworkChoose a site used by the public such as a supermark.docx
DOCX
Homework 2 Please answer the following questions in small paragraph.docx
DOCX
HomeNotificationsMy CommunityBBA 2010-16J-5A21-S1, Introductio.docx
DOCX
HomeAnnouncementsSyllabusDiscussionsQuizzesGra.docx
DOCX
Homeless The Motel Kids of Orange CountyWrite a 1-2 page pa.docx
DOCX
Home work 8 Date 042220201. what are the different between.docx
Hours, A. (2014). Reading Fairy Tales and Playing A Way of Treati.docx
How are authentication and authorization alike and how are the.docx
How are self-esteem and self-concept different What is the or.docx
How are morality and religion similar and how are they different.docx
How are financial statements used to evaluate business activities.docx
How are Japanese and Chinese Americans similar How are they differe.docx
Hot Spot PolicingPlace can be an important aspect of crime and.docx
HOSP3075 Brand Analysis Paper 1This is the first of three assignme.docx
Hou, J., Li, Y., Yu, J. & Shi, W. (2020). A Survey on Digital Fo.docx
How (Not) to be Secular by James K.A. SmithSecular (1)—the ea.docx
Hopefully, you enjoyed this class on Digital Media and Society.Q.docx
hoose (1) one childhood experience from the list provided below..docx
honesty, hard work, caring, excellence HIS 1110 Dr. .docx
hoose one of the four following visualsImage courtesy o.docx
HomeworkChoose a site used by the public such as a supermark.docx
Homework 2 Please answer the following questions in small paragraph.docx
HomeNotificationsMy CommunityBBA 2010-16J-5A21-S1, Introductio.docx
HomeAnnouncementsSyllabusDiscussionsQuizzesGra.docx
Homeless The Motel Kids of Orange CountyWrite a 1-2 page pa.docx
Home work 8 Date 042220201. what are the different between.docx

Recently uploaded (20)

PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
GDM (1) (1).pptx small presentation for students
PDF
01-Introduction-to-Information-Management.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Cell Structure & Organelles in detailed.
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Presentation on HIE in infants and its manifestations
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Classroom Observation Tools for Teachers
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
GDM (1) (1).pptx small presentation for students
01-Introduction-to-Information-Management.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Cell Structure & Organelles in detailed.
202450812 BayCHI UCSC-SV 20250812 v17.pptx
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
human mycosis Human fungal infections are called human mycosis..pptx
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
102 student loan defaulters named and shamed – Is someone you know on the list?
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
VCE English Exam - Section C Student Revision Booklet
Presentation on HIE in infants and its manifestations
Supply Chain Operations Speaking Notes -ICLT Program
Microbial disease of the cardiovascular and lymphatic systems
Classroom Observation Tools for Teachers

Home work for modifying the syntactic analyzer for the attached comp.docx

  • 1. Home work for modifying the syntactic analyzer for the attached compiler by adding to the existing grammar. The full grammar of the language is shown below. The highlighted portions of the grammar show what you must either modify or add to the existing grammar. function: function_header {variable} body function_header: FUNCTION IDENTIFIER [parameters] RETURNS type ; variable: IDENTIFIER : type IS statement parameters: parameter {, parameter} parameter: IDENTIFIER : type type: INTEGER | REAL | BOOLEAN body: BEGIN statement END ; statement: expression ; |
  • 2. REDUCE operator {statement} ENDREDUCE ; | IF expression THEN statement ELSE statement ENDIF ; | CASE expression IS {case} OTHERS ARROW statement ; ENDCASE ; operator: ADDOP | MULOP case: WHEN INT_LITERAL ARROW statement expression: ( expression ) | REAL_LITERAL NOT expression expression binary_operator expression | | INT_LITERAL | IDENTIFIER | BOOL_LITERAL | binary_operator: ADDOP | MULOP | REMOP | EXPOP | RELOP | ANDOP | OROP In the above grammar, the red symbols are nonterminals, the
  • 3. blue symbols are terminals and the black punctuation are EBNF metasymbols. The braces denote repetition 0 or more times and the brackets denote optional. You must rewrite the grammar to eliminate the EBNF brace and bracket metasymbols and to incorporate the significance of parentheses, operator precedence and associativity for all operators. Among arithmetic operators the exponentiation operator has highest precedence following by the multiplying operators and then the adding operators. All relational operators have the same precedence. Among the binary logical operators, and has higher precedence than or. Of the categories of operators, the unary logical operator has highest precedence, the arithmetic operators have next highest precedence, followed by the relational operators and finally the binary logical operators. All operators except the exponentiation operator are left associative. The directives to specify precedence and associativity, such as %prec and %left, may not be used Your parser should be able to correctly parse any syntactically correct program without any problem. You must modify the syntactic analyzer to detect and recover from additional syntax errors using the semicolon as the synchronization token. To accomplish detecting additional errors an error production must be added to the function header and another to the variable declaration. Your bison input file should not produce any shift/reduce or reduce/reduce errors. Eliminating them can be difficult so the best strategy is not introduce any. That is best achieved by making small incremental additions to the grammar and ensuring that no addition introduces any such errors. An example of compilation listing output containing syntax errors is shown below:
  • 4. 1 -- Multiple errors 2 function main a integer returns real; Syntax Error, Unexpected INTEGER, expecting ':' b: integer is * 2; Syntax Error, Unexpected MULOP c: real is 6.0; begin if a > c then 8 b 3.0; Syntax Error, Unexpected REAL_LITERAL, expecting ';' 9 else 10 b = 4.; 11 endif; 12 ; Syntax Error, Unexpected ';', expecting END Lexical Errors 0 Syntax Errors 4 Semantic Errors 0 ------------------------------------------------------------
  • 5. listing.h // This file contains the function prototypes for the functions that produce the // compilation listing enum ErrorCategories {LEXICAL, SYNTAX, GENERAL_SEMANTIC, DUPLICATE_IDENTIFIER, UNDECLARED}; void firstLine(); void nextLine(); int lastLine(); void appendError(ErrorCategories errorCategory, string message); --------------------------------------------------------------------------- ------- makefile compile: scanner.o parser.o listing.o g++ -o compile scanner.o parser.o listing.o scanner.o: scanner.c listing.h tokens.h g++ -c scanner.c scanner.c: scanner.l flex scanner.l
  • 6. mv lex.yy.c scanner.c parser.o: parser.c listing.h g++ -c parser.c parser.c tokens.h: parser.y bison -d -v parser.y mv parser.tab.c parser.c mv parser.tab.h tokens.h listing.o: listing.cc listing.h g++ -c listing.cc ---------------------------------------------------------- parser.y %{ #include using namespace std; #include "listing.h" int yylex(); void yyerror(const char* message); %}
  • 7. %error-verbose %token IDENTIFIER %token INT_LITERAL %token ADDOP MULOP RELOP ANDOP %token BEGIN_ BOOLEAN END ENDREDUCE FUNCTION INTEGER IS REDUCE RETURNS %% function: function_header optional_variable body ; function_header: FUNCTION IDENTIFIER RETURNS type ';' ; optional_variable: variable | ; variable: IDENTIFIER ':' type IS statement_ ; type: INTEGER |
  • 8. BOOLEAN ; body: BEGIN_ statement_ END ';' ; statement_: statement ';' | error ';' ; statement: expression | REDUCE operator reductions ENDREDUCE ; operator: ADDOP | MULOP ; reductions: reductions statement_ | ; expression:
  • 9. expression ANDOP relation | relation ; relation: relation RELOP term | term; term: term ADDOP factor | factor ; factor: factor MULOP primary | primary ; primary: '(' expression ')' | INT_LITERAL | IDENTIFIER ; %% void yyerror(const char* message)
  • 10. { appendError(SYNTAX, message); } int main(int argc, char *argv[]) { firstLine(); yyparse(); lastLine(); return 0; } ------------------------------------------------------------------------ scanner /* Compiler Theory and Design Dr. Duane J. Jarc */ /* This file contains flex input file */ %{ #include #include
  • 11. using namespace std; #include "listing.h" #include "tokens.h" %} %option noyywrap ws [ tr]+ comment --.*n line [n] id [A-Za-z][A-Za-z0-9]* digit [0-9] int {digit}+ punc [(),:;] %% {ws} { ECHO; } {comment} { ECHO; nextLine();} {line} { ECHO; nextLine();} "<" { ECHO; return(RELOP); } "+" { ECHO; return(ADDOP); }
  • 12. "*" { ECHO; return(MULOP); } begin { ECHO; return(BEGIN_); } boolean { ECHO; return(BOOLEAN); } end { ECHO; return(END); } endreduce { ECHO; return(ENDREDUCE); } function { ECHO; return(FUNCTION); } integer { ECHO; return(INTEGER); } is { ECHO; return(IS); } reduce { ECHO; return REDUCE; } returns { ECHO; return(RETURNS); } and { ECHO; return(ANDOP); } {id} { ECHO; return(IDENTIFIER);} {int} { ECHO; return(INT_LITERAL); } {punc} { ECHO; return(yytext[0]); } . { ECHO; appendError(LEXICAL, yytext); } %% ---------------------------------------------------------------- listing.cc
  • 13. // Compiler Theory and Design // Dr. Duane J. Jarc // This file contains the bodies of the functions that produces the compilation // listing #include #include using namespace std; #include "listing.h" static int lineNumber; static string error = ""; static int totalErrors = 0; static void displayErrors(); void firstLine() { lineNumber = 1; printf("n%4d ",lineNumber); } void nextLine()
  • 14. { displayErrors(); lineNumber++; printf("%4d ",lineNumber); } int lastLine() { printf("r"); displayErrors(); printf(" n"); return totalErrors; } void appendError(ErrorCategories errorCategory, string message) { string messages[] = { "Lexical Error, Invalid Character ", "", "Semantic Error, ", "Semantic Error, Duplicate Identifier: ",
  • 15. "Semantic Error, Undeclared " }; error = messages[errorCategory] + message; totalErrors++; } void displayErrors() { if (error != "") printf("%sn", error.c_str()); error = ""; } ----------------------------------------------------------