0% found this document useful (0 votes)
112 views

Project Report

This document contains the parser definition for the COOL programming language. It defines Bison grammar rules and actions for parsing COOL source code. Key points: - It includes header files for the COOL abstract syntax tree and string table. - Locations (line numbers) are tracked using the current line number from the lexer. - Non-terminals set the line number global before constructing nodes to attach line numbers. - The parser builds an AST and also collects classes for semantic analysis. - Actions construct AST nodes from the parser results and perform semantic checks.

Uploaded by

Raj Nayyar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
112 views

Project Report

This document contains the parser definition for the COOL programming language. It defines Bison grammar rules and actions for parsing COOL source code. Key points: - It includes header files for the COOL abstract syntax tree and string table. - Locations (line numbers) are tracked using the current line number from the lexer. - Non-terminals set the line number global before constructing nodes to attach line numbers. - The parser builds an AST and also collects classes for semantic analysis. - Actions construct AST nodes from the parser results and perform semantic checks.

Uploaded by

Raj Nayyar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Solution:

Cool.flex
/*
* The scanner definition for COOL.
*/

/*
* Stuff enclosed in %{ %} in the first section is copied verbatim to the
* output, so headers and global definitions are placed here to be visible
* to the code in the file. Don't remove anything that was here initially
*/
%{

#include <cool-parse.h>
#include <stringtab.h>
#include <utilities.h>
#include <stdint.h>

/* The compiler assumes these identifiers. */


#define yylval cool_yylval
#define yylex cool_yylex

/* Max size of string constants */


#define MAX_STR_CONST 1025
#define YY_NO_UNPUT /* keep g++ happy */

extern FILE *fin; /* we read from this file */

/* define YY_INPUT so we read from the FILE fin:


* This change makes it possible to use this scanner in
* the Cool compiler.
*/
#undef YY_INPUT
#define YY_INPUT(buf,result,max_size) \
if ( (result = fread( (char*)buf, sizeof(char), max_size, fin)) < 0) \
YY_FATAL_ERROR( "read() in flex scanner failed");

char string_buf[MAX_STR_CONST]; /* to assemble string constants */


char *string_buf_ptr;
extern int curr_lineno;
extern int verbose_flag;

extern YYSTYPE cool_yylval;

/*
* Add Your own definitions here
*/

char string_const[MAX_STR_CONST];
int string_const_len;
bool str_contain_null_char;

%}

/*
* Define names for regular expressions here.
*/

%option noyywrap
%x LINE_COMMENT BLOCK_COMMENT STRING

DARROW =>
ASSIGN <-
LE <=

%%

\n { curr_lineno++; }
[ \t\r\v\f]+ {}

/*
* Nested comments
*/

"--" { BEGIN LINE_COMMENT; }


"(\*" { BEGIN BLOCK_COMMENT; }
"\*)" {
strcpy(cool_yylval.error_msg, "Unmatched *)");
return (ERROR);
}

<LINE_COMMENT>\n { BEGIN 0; curr_lineno++; }


<BLOCK_COMMENT>\n { curr_lineno++; }
<BLOCK_COMMENT>"\*)" { BEGIN 0; }
<BLOCK_COMMENT><<EOF>> {
strcpy(cool_yylval.error_msg, "EOF in comment");
BEGIN 0; return (ERROR);
}

<LINE_COMMENT>. {}
<BLOCK_COMMENT>. {}

/*
* The multiple-character operators.
*/

{DARROW} { return (DARROW); }


{ASSIGN} { return (ASSIGN); }
{LE} { return (LE); }

/*
* The single-character operators.
*/

"{" { return '{'; }


"}" { return '}'; }
"(" { return '('; }
")" { return ')'; }
"~" { return '~'; }
"," { return ','; }
";" { return ';'; }
":" { return ':'; }
"+" { return '+'; }
"-" { return '-'; }
"*" { return '*'; }
"/" { return '/'; }
"%" { return '%'; }
"." { return '.'; }
"<" { return '<'; }
"=" { return '='; }
"@" { return '@'; }

/*
* Keywords are case-insensitive except for the values true and false,
* which must begin with a lower-case letter.
*/

(?i:CLASS) { return (CLASS); }


(?i:ELSE) { return (ELSE); }
(?i:FI) { return (FI); }
(?i:IF) { return (IF); }
(?i:IN) { return (IN); }
(?i:INHERITS) { return (INHERITS); }
(?i:LET) { return (LET); }
(?i:LOOP) { return (LOOP); }
(?i:POOL) { return (POOL); }
(?i:THEN) { return (THEN); }
(?i:WHILE) { return (WHILE); }
(?i:CASE) { return (CASE); }
(?i:ESAC) { return (ESAC); }
(?i:OF) { return (OF); }
(?i:NEW) { return (NEW); }
(?i:LE) { return (LE); }
(?i:NOT) { return (NOT); }
(?i:ISVOID) { return (ISVOID); }

t[rR][uU][eE] {
cool_yylval.boolean = 1;
return (BOOL_CONST);
}

f[aA][lL][sS][eE] {
cool_yylval.boolean = 0;
return (BOOL_CONST);
}

/*
* String constants (C syntax)
* Escape sequence \c is accepted for all characters c. Except for
* \n \t \b \f, the result is c.
*
*/

\" {
memset(string_const, 0, sizeof string_const);
string_const_len = 0; str_contain_null_char = false;
BEGIN STRING;
}

<STRING><<EOF>> {
strcpy(cool_yylval.error_msg, "EOF in string constant");
BEGIN 0; return (ERROR);
}

<STRING>\\. {
if (string_const_len >= MAX_STR_CONST) {
strcpy(cool_yylval.error_msg, "String constant too long");
BEGIN 0; return (ERROR);
}
switch(yytext[1]) {
case '\"': string_const[string_const_len++] = '\"'; break;
case '\\': string_const[string_const_len++] = '\\'; break;
case 'b' : string_const[string_const_len++] = '\b'; break;
case 'f' : string_const[string_const_len++] = '\f'; break;
case 'n' : string_const[string_const_len++] = '\n'; break;
case 't' : string_const[string_const_len++] = '\t'; break;
case '0' : string_const[string_const_len++] = 0;
str_contain_null_char = true; break;
default : string_const[string_const_len++] = yytext[1];
}
}

<STRING>\\\n { curr_lineno++; }
<STRING>\n {
curr_lineno++;
strcpy(cool_yylval.error_msg, "Unterminated string constant");
BEGIN 0; return (ERROR);
}
<STRING>\" {
if (string_const_len > 1 && str_contain_null_char) {
strcpy(cool_yylval.error_msg, "String contains null character");
BEGIN 0; return (ERROR);
}
cool_yylval.symbol = stringtable.add_string(string_const);
BEGIN 0; return (STR_CONST);
}

<STRING>. {
if (string_const_len >= MAX_STR_CONST) {
strcpy(cool_yylval.error_msg, "String constant too long");
BEGIN 0; return (ERROR);
}
string_const[string_const_len++] = yytext[0];
}

/*
* Integers and identifiers.
*/

[0-9]+ {
cool_yylval.symbol = inttable.add_string(yytext);
return (INT_CONST);
}

[A-Z][A-Za-z0-9_]* {
cool_yylval.symbol = idtable.add_string(yytext);
return (TYPEID);
}

[a-z][A-Za-z0-9_]* {
cool_yylval.symbol = idtable.add_string(yytext);
return (OBJECTID);
}

/*
* Other errors.
*/
. {
strcpy(cool_yylval.error_msg, yytext);
return (ERROR);
}

%%
Solution:
Cool.y
/*
* cool.y
* Parser definition for the COOL language.
*
*/
%{
#include <iostream>
#include "cool-tree.h"
#include "stringtab.h"
#include "utilities.h"

extern char *curr_filename;

/* Locations */
#define YYLTYPE int /* the type of locations */
#define cool_yylloc curr_lineno /* use the curr_lineno from the lexer
for the location of tokens */

extern int node_lineno; /* set before constructing a tree node


to whatever you want the line number
for the tree node to be */

#define YYLLOC_DEFAULT(Current, Rhs, N) \


Current = Rhs[1]; \
node_lineno = Current;

#define SET_NODELOC(Current) \
node_lineno = Current;

/* IMPORTANT NOTE ON LINE NUMBERS


*********************************
* The above definitions and macros cause every terminal in your grammar
to
* have the line number supplied by the lexer. The only task you have to
* implement for line numbers to work correctly, is to use SET_NODELOC()
* before constructing any constructs from non-terminals in your grammar.
* Example: Consider you are matching on the following very restrictive
* (fictional) construct that matches a plus between two integer constants.
* (SUCH A RULE SHOULD NOT BE PART OF YOUR PARSER):

plus_consts : INT_CONST '+' INT_CONST

* where INT_CONST is a terminal for an integer constant. Now, a correct


* action for this rule that attaches the correct line number to plus_const
* would look like the following:

plus_consts : INT_CONST '+' INT_CONST


{
// Set the line number of the current non-terminal:
// ***********************************************
// You can access the line numbers of the i'th item with @i, just
// like you acess the value of the i'th exporession with $i.
//
// Here, we choose the line number of the last INT_CONST (@3) as the
// line number of the resulting expression (@$). You are free to pick
// any reasonable line as the line number of non-terminals. If you
// omit the statement @$=..., bison has default rules for deciding which
// line number to use. Check the manual for details if you are interested.
@$ = @3;

// Observe that we call SET_NODELOC(@3); this will set the global


variable
// node_lineno to @3. Since the constructor call "plus" uses the value of
// this global, the plus node will now have the correct line number.
SET_NODELOC(@3);

// construct the result node:


$$ = plus(int_const($1), int_const($3));
}

*/
void yyerror(char *s); /* defined below; called for each parse error */
extern int yylex(); /* the entry point to the lexer */

/***************************************************************
*********/
/* DONT CHANGE ANYTHING IN THIS SECTION */

Program ast_root; /* the result of the parse */


Classes parse_results; /* for use in semantic analysis */
int omerrs = 0; /* number of errors in lexing and parsing */
%}

/* A union of all the types that can be the result of parsing actions. */
%union {
Boolean boolean;
Symbol symbol;
Program program;
Class_ class_;
Classes classes;
Feature feature;
Features features;
Formal formal;
Formals formals;
Case case_;
Cases cases;
Expression expression;
Expressions expressions;
char *error_msg;
}

/*
Declare the terminals; a few have types for associated lexemes.
The token ERROR is never used in the parser; thus, it is a parse
error when the lexer returns it.

The integer following token declaration is the numeric constant used


to represent that token internally. Typically, Bison generates these
on its own, but we give explicit numbers to prevent version parity
problems (bison 1.25 and earlier start at 258, later versions -- at
257)
*/
%token CLASS 258 ELSE 259 FI 260 IF 261 IN 262
%token INHERITS 263 LET 264 LOOP 265 POOL 266 THEN 267 WHILE 268
%token CASE 269 ESAC 270 OF 271 DARROW 272 NEW 273 ISVOID 274
%token <symbol> STR_CONST 275 INT_CONST 276
%token <boolean> BOOL_CONST 277
%token <symbol> TYPEID 278 OBJECTID 279
%token ASSIGN 280 NOT 281 LE 282 ERROR 283

/* DON'T CHANGE ANYTHING ABOVE THIS LINE, OR YOUR PARSER WONT


WORK */

/***************************************************************
***********/

/* Complete the nonterminal list below, giving a type for the semantic
value of each non terminal. (See section 3.6 in the bison
documentation for details). */

/* Declare types for the grammar's non-terminals. */


%type <program> program
%type <classes> class_list
%type <class_> class

/* You will want to change the following line. */


%type <expressions> expression_block_list
%type <expressions> expression_dummy_list
%type <expressions> expression_list
%type <expression> expression
%type <expression> let

%type <features> dummy_feature_list


%type <features> feature_list
%type <feature> feature

%type <formals> dummy_formal_list


%type <formals> formal_list
%type <formal> formal;
%type <cases> case_list
%type <case_> case_;

/* Precedence declarations go here. */


%right IN
%right LET
%right ASSIGN
%right NOT
%nonassoc LE '<' '='
%left '+' '-'
%left '*' '/'
%right ISVOID
%right '~'
%right '@'
%left '.'
%%
/*
Save the root of the abstract syntax tree in a global variable.
*/
program : class_list { @$ = @1; ast_root = program($1); }
;
class_list
: class /* single class */
{ $$ = single_Classes($1);
parse_results = $$; }
| class_list class /* several classes */
{ $$ = append_Classes($1,single_Classes($2));
parse_results = $$; }
;

/* If no parent is specified, the class inherits from the Object class. */


class : CLASS TYPEID '{' dummy_feature_list '}' ';'
{ @$ = @1; $$ = class_($2,idtable.add_string("Object"),$4,
stringtable.add_string(curr_filename)); }
| CLASS TYPEID '{' feature_list '}' ';'
{ @$ = @1; $$ = class_($2,idtable.add_string("Object"),$4,
stringtable.add_string(curr_filename)); }
| CLASS TYPEID INHERITS TYPEID '{' dummy_feature_list '}' ';'
{ @$ = @1; $$ = class_($2,$4,$6,stringtable.add_string(curr_filename)); }
| CLASS TYPEID INHERITS TYPEID '{' feature_list '}' ';'
{ @$ = @1; $$ = class_($2,$4,$6,stringtable.add_string(curr_filename)); }
| error ';' {}
;

/* Feature list may be empty, but no empty features in list. */


dummy_feature_list: /* empty */
{ $$ = nil_Features(); }
;

feature_list: feature
{ $$ = single_Features($1); }
| feature_list feature
{ $$ = append_Features($1, single_Features($2)); }
;

feature : OBJECTID ':' TYPEID ';'


{ @$ = @1; $$ = attr($1, $3, no_expr()); }
| OBJECTID ':' TYPEID ASSIGN expression ';'
{ @$ = @1; $$ = attr($1, $3, $5); }
| OBJECTID '(' dummy_formal_list ')' ':' TYPEID '{' expression '}' ';'
{ @$ = @1; $$ = method($1, $3, $6, $8); }
| OBJECTID '(' formal_list ')' ':' TYPEID '{' expression '}' ';'
{ @$ = @1; $$ = method($1, $3, $6, $8); }
| error ';' {}
;

dummy_formal_list: /* empty */
{ $$ = nil_Formals(); }
;

formal_list: formal
{ $$ = single_Formals($1); }
| formal_list ',' formal
{ $$ = append_Formals($1, single_Formals($3)); }
;

formal: OBJECTID ':' TYPEID


{ @$ = @1; $$ = formal($1, $3); }
case_list: case_ ';'
{ $$ = single_Cases($1); }
| case_list case_ ';'
{ $$ = append_Cases($1, single_Cases($2)); }
;

case_: OBJECTID ':' TYPEID DARROW expression


{ @$ = @1; $$ = branch($1, $3, $5); }
;

let: OBJECTID ':' TYPEID IN expression


{ @$ = @1;$$ = let($1, $3, no_expr(), $5); }
| OBJECTID ':' TYPEID ASSIGN expression IN expression
{ @$ = @1; $$ = let($1, $3, $5, $7); }
| OBJECTID ':' TYPEID ',' let
{ @$ = @1; $$ = let($1, $3, no_expr(), $5); }
| OBJECTID ':' TYPEID ASSIGN expression ',' let
{ @$ = @1; $$ = let($1, $3, $5, $7); }
| error IN expression {}
| error ',' let {}
;

expression : OBJECTID
{ @$ = @1; $$ = object($1); }
| STR_CONST
{ @$ = @1; $$ = string_const($1); }
| INT_CONST
{ @$ = @1; $$ = int_const($1); }
| BOOL_CONST
{ @$ = @1; $$ = bool_const($1); }
| NOT expression
{ @$ = @1; $$ = comp($2); }
| '~' expression
{ @$ = @1; $$ = neg($2); }
| expression '+' expression
{ @$ = @1; $$ = plus($1, $3); }
| expression '-' expression
{ @$ = @1; $$ = sub($1, $3); }
| expression '*' expression
{ @$ = @1; $$ = mul($1, $3); }
| expression '/' expression
{ @$ = @1; $$ = divide($1, $3); }
| expression LE expression
{ @$ = @1; $$ = leq($1, $3); }
| expression '<' expression
{ @$ = @1; $$ = lt($1, $3); }
| expression '=' expression
{ @$ = @1; $$ = eq($1, $3); }
| OBJECTID ASSIGN expression
{ @$ = @1; $$ = assign($1, $3); }
| NEW TYPEID
{ @$ = @1; $$ = new_($2); }
| ISVOID expression
{ @$ = @1; $$ = isvoid($2); }
| '(' expression ')'
{ @$ = @1; $$ = $2; }
| '{' expression_block_list '}'
{ @$ = @1; $$ = block($2); }
| OBJECTID '(' expression_list ')'
{ @$ = @1; $$ = dispatch(object(idtable.add_string("self")), $1, $3); }
| expression '.' OBJECTID '(' expression_list ')'
{ @$ = @1; $$ = dispatch($1, $3, $5); }
| expression '@' TYPEID '.' OBJECTID '(' expression_list ')'
{ @$ = @1; $$ = static_dispatch($1, $3, $5, $7); }
| OBJECTID '(' expression_dummy_list ')'
{ @$ = @1; $$ = dispatch(object(idtable.add_string("self")), $1, $3); }
| expression '.' OBJECTID '(' expression_dummy_list ')'
{ @$ = @1; $$ = dispatch($1, $3, $5); }
| expression '@' TYPEID '.' OBJECTID '(' expression_dummy_list ')'
{ @$ = @1; $$ = static_dispatch($1, $3, $5, $7); }
| IF expression THEN expression ELSE expression FI
{ @$ = @1; $$ = cond($2, $4, $6); }
| WHILE expression LOOP expression POOL
{ @$ = @1; $$ = loop($2, $4); }
| CASE expression OF case_list ESAC
{ @$ = @1; $$ = typcase($2, $4); }
| LET let
{ @$ = @1;$$ = $2; }
;
expression_dummy_list: /* empty */
{ $$ = nil_Expressions(); }
;

expression_list: expression
{ $$ = single_Expressions($1); }
| expression_list ',' expression
{ $$ = append_Expressions($1, single_Expressions($3)); }
;

expression_block_list: expression ';'


{ $$ = single_Expressions($1); }
| expression_block_list expression ';'
{ $$ = append_Expressions($1, single_Expressions($2)); }
| error ';' {}
;

/* end of grammar */
%%

/* This function is called automatically when Bison detects a parse error. */


void yyerror(char *s)
{
extern int curr_lineno;

cerr << "\"" << curr_filename << "\", line " << curr_lineno << ": " \
<< s << " at or near ";
print_cool_token(yychar);
cerr << endl;
omerrs++;

if(omerrs>50) {fprintf(stdout, "More than 50 errors\n"); exit(1);}


}

You might also like