SlideShare a Scribd company logo
1 of 9
Download to read offline
You should be able to use the same function to check a narrowing function return by adding a
similar semantic action on the top level production for the whole function. Be sure that you have
declared that the function_header and body productions carry a type attribute if your receive an
error indicating that they have no declared type. In addition both require semantic actions that
pass the type information up the parse tree.
My issue is that my output says "Type Mismatch on Function Body" when it should say "Illegal
Narrowing Function Return"
heres the test case:
-- Narrowing Function Return
function main returns integer;
b: integer is 6 * 2;
begin
if 8 < 0 then
b + 3.0;
else
b * 4.6;
endif;
end;
heres the expected output:
--Narrowing Function Return
function main returns integer;
b: integer is 6 * 2;
begin
if 8 < 0 then
b + 3.0;
else
b * 4.6;
endif;
end;
Semantic Error, Illegal Narrowing Function Return
Lexical Errors 0
Syntax Errors 0
Semantic Errors 1
Heres the output I'm getting:
-- Narrowing Function Return
function main returns integer;
b: integer is 6 * 2;
begin
if 8 < 0 then
b + 3.0;
else
b * 4.6;
endif;
end;
Semantic Error, Type Mismatch on Function Body
Lexical Errors: 0
Syntax Errors: 0
Semantic Errors 1
heres my parser.y code:
/* Compiler Theory and Design
Duane J. Jarc */
%{
#include
#include
#include
#include
#include
using namespace std;
#include "types.h"
#include "listing.h"
#include "symbols.h"
int yylex();
void yyerror(const char* message);
Symbols symbols;
Types case_return = INT_TYPE;
Types current_function_return = INT_TYPE;
%}
%define parse.error verbose
%union
{
CharPtr iden;
Types type;
}
%token IDENTIFIER
%token INT_LITERAL REAL_LITERAL BOOL_LITERAL CASE ELSE IF ENDIF
%token ADDOP MULOP RELOP ANDOP EXPOP REMOP OROP NOTOP
%token BEGIN_ BOOLEAN END ENDREDUCE FUNCTION INTEGER IS REDUCE
RETURNS
%token ENDCASE OTHERS REAL ARROW THEN WHEN
%type type statement_ statement variable parameter reductions expression binary
relation term factor exponent unary primary case cases
%type function
%type function_header
%type body
%%
function:
function_header optional_variable body ;
function_header:
FUNCTION IDENTIFIER parameters RETURNS type {
current_function_return = $5;
checkAssignment($5, $1, "Function Return"); // Check for illegal narrowing
} ';' |
FUNCTION IDENTIFIER RETURNS type {
current_function_return = $3;
checkAssignment($3, $1, "Function Return"); // Check for illegal narrowing
} ';' |
error ';' {
$$ = MISMATCH;
};
optional_variable:
optional_variable variable | %empty
;
variable:
IDENTIFIER ':' type IS statement_
{checkAssignment($3, $5, "Variable Initialization");
if (symbols.find($1, $3))
appendError(DUPLICATE_IDENTIFIER, $1);
else
symbols.insert($1, $3);} |
error ';' {$$ = MISMATCH;};
parameters:
parameter optional_parameter;
optional_parameter:
optional_parameter ',' parameter | %empty
;
parameter:
IDENTIFIER ':' type {
if(symbols.find($1, $$))
appendError(DUPLICATE_IDENTIFIER, $1);
else
symbols.insert($1, $3);} |
error ';' {$$ = MISMATCH;};
type:
INTEGER {$$ = INT_TYPE;} |
BOOLEAN {$$ = BOOL_TYPE;} |
REAL {$$ = REAL_TYPE;} ;
body:
BEGIN_ statement_ END ';' {
// Check for illegal narrowing in the function body
checkAssignment(current_function_return, $2, "Function Return");
};
statement_:
statement ';' |
error ';' {$$ = MISMATCH;} ;
statement:
expression |
IF expression THEN statement_ ELSE statement_ ENDIF {$$ = checkIfThen($2, $4, $6);} |
CASE expression IS cases OTHERS ARROW statement_ ENDCASE {$$ =
checkExpression($2); $$ = checkReturns(case_return, $7);}; |
REDUCE operator reductions ENDREDUCE {$$ = $3;} ;
cases:
cases case {case_return = checkCases($2, case_return);}|
%empty {$$ = NAN_TYPE;};
case:
WHEN INT_LITERAL ARROW statement_ {$$ = $4;} ;
reductions:
reductions statement_ {$$ = checkArithmetic($1, $2);} |
{$$ = INT_TYPE;} %empty;
operator:
ADDOP |
RELOP |
EXPOP |
MULOP ;
expression:
expression OROP binary {$$ = checkLogical($1, $3);} |
binary ;
binary:
binary ANDOP relation {$$ = checkLogical($1, $3);} |
relation ;
relation:
relation RELOP term {$$ = checkRelational($1, $3);}|
term ;
term:
term ADDOP factor {$$ = checkArithmetic($1, $3);} |
factor ;
factor:
factor MULOP primary {$$ = checkArithmetic($1, $3);} |
factor REMOP exponent {$$ = checkRemainder($1, $3);} |
exponent ;
exponent:
unary |
unary EXPOP primary {$$ = checkArithmetic($1, $3);} ;
unary:
NOTOP primary {$$ = checkNegation($2);} |
primary;
primary:
'(' expression ')' {$$ = $2;} |
INT_LITERAL | BOOL_LITERAL | REAL_LITERAL |
IDENTIFIER {if (!symbols.find($1, $$)) appendError(UNDECLARED, $1);} ;
%%
void yyerror(const char* message)
{
appendError(SYNTAX, message);
}
int main(int argc, char *argv[])
{
firstLine();
yyparse();
lastLine();
return 0;
}
heres my types.cc code:
// Compiler Theory and Design
// Duane J. Jarc
// This file contains the bodies of the type checking functions
#include
#include
using namespace std;
#include "types.h"
#include "listing.h"
void checkAssignment(Types lValue, Types rValue, string message)
{
if(rValue == MISMATCH)
return;
if(lValue == BOOL_TYPE && rValue != BOOL_TYPE || lValue!=BOOL_TYPE && rValue
==BOOL_TYPE){
appendError(GENERAL_SEMANTIC, "Type Mismatch on " + message);
}
else if((lValue == INT_TYPE && rValue == REAL_TYPE) || (lValue == REAL_TYPE &&
rValue == INT_TYPE)){
appendError(GENERAL_SEMANTIC, "Illegal Narrowing " + message);
}
}
Types checkArithmetic(Types left, Types right)
{
if (left == MISMATCH || right == MISMATCH)
return MISMATCH;
if (left == BOOL_TYPE || right == BOOL_TYPE)
{
appendError(GENERAL_SEMANTIC, "Numeric Type Required");
return MISMATCH;
}
if (left == REAL_TYPE || right == REAL_TYPE) {
return REAL_TYPE;
}
return INT_TYPE;
}
Types checkLogical(Types left, Types right)
{
if (left == MISMATCH || right == MISMATCH)
return MISMATCH;
if (left != BOOL_TYPE || right != BOOL_TYPE)
{
appendError(GENERAL_SEMANTIC, "Boolean Type Required");
return MISMATCH;
}
return BOOL_TYPE;
}
Types checkRemainder(Types left, Types right){
if (left == MISMATCH || right == MISMATCH)
return MISMATCH;
if (left == BOOL_TYPE || right == BOOL_TYPE){
appendError(GENERAL_SEMANTIC, "Remainder Operator Requires Integer Operands");
return MISMATCH;
}
if (left == REAL_TYPE || right == REAL_TYPE){
appendError(GENERAL_SEMANTIC, "Remainder Operator Requires Integer Operands");
return MISMATCH;
}
return INT_TYPE;
}
Types checkIfThen(Types expression, Types left, Types right){
if(expression != BOOL_TYPE){
appendError(GENERAL_SEMANTIC, "If Expression Must Be Boolean");
return MISMATCH;
}
if(left != right){
appendError(GENERAL_SEMANTIC, "If-Then Type Mismatch");
return MISMATCH;
}
return expression;
}
Types checkNegation(Types right){
if (right != BOOL_TYPE){
appendError(GENERAL_SEMANTIC, "Boolean Type Required");
return MISMATCH;
}
return BOOL_TYPE;
}
Types checkRelational(Types left, Types right){
if (checkArithmetic(left, right) == MISMATCH)
return MISMATCH;
return BOOL_TYPE;
}
Types checkExpression(Types expression){
if(expression!=INT_TYPE){
appendError(GENERAL_SEMANTIC, " Case expression Not Integer ");
return MISMATCH;
}
return INT_TYPE;
}
Types checkCases(Types case_, Types cases){
if (cases != INT_TYPE){
if( cases != NAN_TYPE && case_ != cases){
appendError(GENERAL_SEMANTIC, "Case Types Mismatch");
return MISMATCH;
}
}
// if (case_ != INT_TYPE){
// appendError(GENERAL_SEMANTIC, "When Expression Not Integer");
// if (cases != NAN_TYPE && case_ == cases){
// return cases;
// }
// return case_;
// }
return NAN_TYPE;
}
Types checkReturns(Types cases, Types others){
if(others != INT_TYPE){
appendError(GENERAL_SEMANTIC, " Other Expression Not Integer");
return others;
}
if(cases != NAN_TYPE){
return cases;
}
return INT_TYPE;
}

More Related Content

Similar to You should be able to use the same function to check a narrowing fun.pdf

Let it crash - fault tolerance in Elixir/OTP
Let it crash - fault tolerance in Elixir/OTPLet it crash - fault tolerance in Elixir/OTP
Let it crash - fault tolerance in Elixir/OTPMaciej Kaszubowski
 
PHP7 - Scalar Type Hints & Return Types
PHP7 - Scalar Type Hints & Return TypesPHP7 - Scalar Type Hints & Return Types
PHP7 - Scalar Type Hints & Return TypesEric Poe
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requireTheCreativedev Blog
 
C Programming Language Step by Step Part 5
C Programming Language Step by Step Part 5C Programming Language Step by Step Part 5
C Programming Language Step by Step Part 5Rumman Ansari
 
C Programming Language Part 5
C Programming Language Part 5C Programming Language Part 5
C Programming Language Part 5Rumman Ansari
 
Expressions and Operators.pptx
Expressions and Operators.pptxExpressions and Operators.pptx
Expressions and Operators.pptxJapneet9
 
Operators
OperatorsOperators
OperatorsKamran
 
Operators in c programming
Operators in c programmingOperators in c programming
Operators in c programmingsavitamhaske
 
C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)jahanullah
 
Safer JS Codebases with Flow
Safer JS Codebases with FlowSafer JS Codebases with Flow
Safer JS Codebases with FlowValentin Agachi
 
Dti2143 chap 4 control statement part 2
Dti2143 chap 4 control statement part 2Dti2143 chap 4 control statement part 2
Dti2143 chap 4 control statement part 2alish sha
 
Are statecharts the next big UI paradigm?
Are statecharts the next big UI paradigm? Are statecharts the next big UI paradigm?
Are statecharts the next big UI paradigm? Luca Matteis
 
Introduction to golang
Introduction to golangIntroduction to golang
Introduction to golangwww.ixxo.io
 

Similar to You should be able to use the same function to check a narrowing fun.pdf (20)

Let it crash - fault tolerance in Elixir/OTP
Let it crash - fault tolerance in Elixir/OTPLet it crash - fault tolerance in Elixir/OTP
Let it crash - fault tolerance in Elixir/OTP
 
PHP7 - Scalar Type Hints & Return Types
PHP7 - Scalar Type Hints & Return TypesPHP7 - Scalar Type Hints & Return Types
PHP7 - Scalar Type Hints & Return Types
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
 
C Programming Language Step by Step Part 5
C Programming Language Step by Step Part 5C Programming Language Step by Step Part 5
C Programming Language Step by Step Part 5
 
C Programming Language Part 5
C Programming Language Part 5C Programming Language Part 5
C Programming Language Part 5
 
Expressions and Operators.pptx
Expressions and Operators.pptxExpressions and Operators.pptx
Expressions and Operators.pptx
 
Operators
OperatorsOperators
Operators
 
Web Technology_10.ppt
Web Technology_10.pptWeb Technology_10.ppt
Web Technology_10.ppt
 
Operators in c programming
Operators in c programmingOperators in c programming
Operators in c programming
 
C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)
 
C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)
 
Safer JS Codebases with Flow
Safer JS Codebases with FlowSafer JS Codebases with Flow
Safer JS Codebases with Flow
 
Dti2143 chap 4 control statement part 2
Dti2143 chap 4 control statement part 2Dti2143 chap 4 control statement part 2
Dti2143 chap 4 control statement part 2
 
Operators in PHP
Operators in PHPOperators in PHP
Operators in PHP
 
Php basics
Php basicsPhp basics
Php basics
 
Basic PHP
Basic PHPBasic PHP
Basic PHP
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Are statecharts the next big UI paradigm?
Are statecharts the next big UI paradigm? Are statecharts the next big UI paradigm?
Are statecharts the next big UI paradigm?
 
Introduction to golang
Introduction to golangIntroduction to golang
Introduction to golang
 
SPL, not a bridge too far
SPL, not a bridge too farSPL, not a bridge too far
SPL, not a bridge too far
 

Recently uploaded

Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
latest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answerslatest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answersdalebeck957
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 

Recently uploaded (20)

Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
latest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answerslatest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answers
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 

You should be able to use the same function to check a narrowing fun.pdf

  • 1. You should be able to use the same function to check a narrowing function return by adding a similar semantic action on the top level production for the whole function. Be sure that you have declared that the function_header and body productions carry a type attribute if your receive an error indicating that they have no declared type. In addition both require semantic actions that pass the type information up the parse tree. My issue is that my output says "Type Mismatch on Function Body" when it should say "Illegal Narrowing Function Return" heres the test case: -- Narrowing Function Return function main returns integer; b: integer is 6 * 2; begin if 8 < 0 then b + 3.0; else b * 4.6; endif; end; heres the expected output: --Narrowing Function Return function main returns integer; b: integer is 6 * 2; begin if 8 < 0 then b + 3.0; else b * 4.6; endif; end; Semantic Error, Illegal Narrowing Function Return Lexical Errors 0 Syntax Errors 0 Semantic Errors 1 Heres the output I'm getting: -- Narrowing Function Return
  • 2. function main returns integer; b: integer is 6 * 2; begin if 8 < 0 then b + 3.0; else b * 4.6; endif; end; Semantic Error, Type Mismatch on Function Body Lexical Errors: 0 Syntax Errors: 0 Semantic Errors 1 heres my parser.y code: /* Compiler Theory and Design Duane J. Jarc */ %{ #include #include #include #include #include using namespace std; #include "types.h" #include "listing.h" #include "symbols.h" int yylex(); void yyerror(const char* message); Symbols symbols; Types case_return = INT_TYPE; Types current_function_return = INT_TYPE; %} %define parse.error verbose
  • 3. %union { CharPtr iden; Types type; } %token IDENTIFIER %token INT_LITERAL REAL_LITERAL BOOL_LITERAL CASE ELSE IF ENDIF %token ADDOP MULOP RELOP ANDOP EXPOP REMOP OROP NOTOP %token BEGIN_ BOOLEAN END ENDREDUCE FUNCTION INTEGER IS REDUCE RETURNS %token ENDCASE OTHERS REAL ARROW THEN WHEN %type type statement_ statement variable parameter reductions expression binary relation term factor exponent unary primary case cases %type function %type function_header %type body %% function: function_header optional_variable body ; function_header: FUNCTION IDENTIFIER parameters RETURNS type { current_function_return = $5; checkAssignment($5, $1, "Function Return"); // Check for illegal narrowing } ';' | FUNCTION IDENTIFIER RETURNS type { current_function_return = $3; checkAssignment($3, $1, "Function Return"); // Check for illegal narrowing } ';' | error ';' { $$ = MISMATCH; }; optional_variable: optional_variable variable | %empty ; variable:
  • 4. IDENTIFIER ':' type IS statement_ {checkAssignment($3, $5, "Variable Initialization"); if (symbols.find($1, $3)) appendError(DUPLICATE_IDENTIFIER, $1); else symbols.insert($1, $3);} | error ';' {$$ = MISMATCH;}; parameters: parameter optional_parameter; optional_parameter: optional_parameter ',' parameter | %empty ; parameter: IDENTIFIER ':' type { if(symbols.find($1, $$)) appendError(DUPLICATE_IDENTIFIER, $1); else symbols.insert($1, $3);} | error ';' {$$ = MISMATCH;}; type: INTEGER {$$ = INT_TYPE;} | BOOLEAN {$$ = BOOL_TYPE;} | REAL {$$ = REAL_TYPE;} ; body: BEGIN_ statement_ END ';' { // Check for illegal narrowing in the function body checkAssignment(current_function_return, $2, "Function Return"); }; statement_: statement ';' | error ';' {$$ = MISMATCH;} ; statement: expression | IF expression THEN statement_ ELSE statement_ ENDIF {$$ = checkIfThen($2, $4, $6);} | CASE expression IS cases OTHERS ARROW statement_ ENDCASE {$$ =
  • 5. checkExpression($2); $$ = checkReturns(case_return, $7);}; | REDUCE operator reductions ENDREDUCE {$$ = $3;} ; cases: cases case {case_return = checkCases($2, case_return);}| %empty {$$ = NAN_TYPE;}; case: WHEN INT_LITERAL ARROW statement_ {$$ = $4;} ; reductions: reductions statement_ {$$ = checkArithmetic($1, $2);} | {$$ = INT_TYPE;} %empty; operator: ADDOP | RELOP | EXPOP | MULOP ; expression: expression OROP binary {$$ = checkLogical($1, $3);} | binary ; binary: binary ANDOP relation {$$ = checkLogical($1, $3);} | relation ; relation: relation RELOP term {$$ = checkRelational($1, $3);}| term ; term: term ADDOP factor {$$ = checkArithmetic($1, $3);} | factor ; factor: factor MULOP primary {$$ = checkArithmetic($1, $3);} | factor REMOP exponent {$$ = checkRemainder($1, $3);} | exponent ; exponent: unary | unary EXPOP primary {$$ = checkArithmetic($1, $3);} ;
  • 6. unary: NOTOP primary {$$ = checkNegation($2);} | primary; primary: '(' expression ')' {$$ = $2;} | INT_LITERAL | BOOL_LITERAL | REAL_LITERAL | IDENTIFIER {if (!symbols.find($1, $$)) appendError(UNDECLARED, $1);} ; %% void yyerror(const char* message) { appendError(SYNTAX, message); } int main(int argc, char *argv[]) { firstLine(); yyparse(); lastLine(); return 0; } heres my types.cc code: // Compiler Theory and Design // Duane J. Jarc // This file contains the bodies of the type checking functions #include #include using namespace std; #include "types.h" #include "listing.h" void checkAssignment(Types lValue, Types rValue, string message) { if(rValue == MISMATCH) return; if(lValue == BOOL_TYPE && rValue != BOOL_TYPE || lValue!=BOOL_TYPE && rValue ==BOOL_TYPE){
  • 7. appendError(GENERAL_SEMANTIC, "Type Mismatch on " + message); } else if((lValue == INT_TYPE && rValue == REAL_TYPE) || (lValue == REAL_TYPE && rValue == INT_TYPE)){ appendError(GENERAL_SEMANTIC, "Illegal Narrowing " + message); } } Types checkArithmetic(Types left, Types right) { if (left == MISMATCH || right == MISMATCH) return MISMATCH; if (left == BOOL_TYPE || right == BOOL_TYPE) { appendError(GENERAL_SEMANTIC, "Numeric Type Required"); return MISMATCH; } if (left == REAL_TYPE || right == REAL_TYPE) { return REAL_TYPE; } return INT_TYPE; } Types checkLogical(Types left, Types right) { if (left == MISMATCH || right == MISMATCH) return MISMATCH; if (left != BOOL_TYPE || right != BOOL_TYPE) { appendError(GENERAL_SEMANTIC, "Boolean Type Required"); return MISMATCH; } return BOOL_TYPE; } Types checkRemainder(Types left, Types right){ if (left == MISMATCH || right == MISMATCH) return MISMATCH; if (left == BOOL_TYPE || right == BOOL_TYPE){
  • 8. appendError(GENERAL_SEMANTIC, "Remainder Operator Requires Integer Operands"); return MISMATCH; } if (left == REAL_TYPE || right == REAL_TYPE){ appendError(GENERAL_SEMANTIC, "Remainder Operator Requires Integer Operands"); return MISMATCH; } return INT_TYPE; } Types checkIfThen(Types expression, Types left, Types right){ if(expression != BOOL_TYPE){ appendError(GENERAL_SEMANTIC, "If Expression Must Be Boolean"); return MISMATCH; } if(left != right){ appendError(GENERAL_SEMANTIC, "If-Then Type Mismatch"); return MISMATCH; } return expression; } Types checkNegation(Types right){ if (right != BOOL_TYPE){ appendError(GENERAL_SEMANTIC, "Boolean Type Required"); return MISMATCH; } return BOOL_TYPE; } Types checkRelational(Types left, Types right){ if (checkArithmetic(left, right) == MISMATCH) return MISMATCH; return BOOL_TYPE; } Types checkExpression(Types expression){ if(expression!=INT_TYPE){ appendError(GENERAL_SEMANTIC, " Case expression Not Integer "); return MISMATCH;
  • 9. } return INT_TYPE; } Types checkCases(Types case_, Types cases){ if (cases != INT_TYPE){ if( cases != NAN_TYPE && case_ != cases){ appendError(GENERAL_SEMANTIC, "Case Types Mismatch"); return MISMATCH; } } // if (case_ != INT_TYPE){ // appendError(GENERAL_SEMANTIC, "When Expression Not Integer"); // if (cases != NAN_TYPE && case_ == cases){ // return cases; // } // return case_; // } return NAN_TYPE; } Types checkReturns(Types cases, Types others){ if(others != INT_TYPE){ appendError(GENERAL_SEMANTIC, " Other Expression Not Integer"); return others; } if(cases != NAN_TYPE){ return cases; } return INT_TYPE; }