CS 280 Programming Language Concepts Design Notes

Transcription

CS 280 Programming Language Concepts Design Notes
3/9/15
CS 280
Programming Language
Concepts
Design Notes
Programming Assignment 3
1
3/9/15
High Level Questions
•  Do I understand the requirements?
•  Do I understand how to meet the
requirements?
Observations
•  You will be given an implementation of a
lexical analyzer: a header file, a getToken()
function, and a pushback token function
•  The lexical analyzer will keep track of line
numbers for you
•  The key to the assignment is deciding how to
represent the data and how to structure the
functions
2
3/9/15
Recursive Descent Parsing
•  Production rules will need to be implemented
in functions
•  Functions for production rules will call
getToken() or other functions for other rules
•  Functions will return a parse tree – so you
need to come up with some kind of class
definition for parse tree
Grammar Rules
Program ::= StmtList
StmtList ::= Stmt | Stmt StmtList
Stmt ::=
PRINT Expr SC | SET ID Expr SC
Expr ::=
Expr PLUS Term | Expr MINUS Term | Term
Term ::=
Term STAR Primary | Term SLASH Primary | Primary
Primary ::= ID | INT | STRING
•  You need a function per rule
•  The functions take a pointer to the input stream to read
•  The functions return a pointer to a parse tree
3
3/9/15
Getting Started
•  Decide how you will represent the result of a parse
•  Declare all your functions, then define them
•  You will probably need a global error counter to
keep track of the number of errors
•  Think about the idea of an error strategy: if I find an
error, what should I do besides just printing out an
error message?
Parse Tree
•  Common members in a PTree base class
–  type
–  left and right child
•  Common methods in base class
–  getType(), getValue(), traversals
•  Probably want to think about a class
inheritance hierarchy. Several classes that
are subclasses of Ptree
– 
– 
– 
– 
Class for “list of statements”
Class for “print” and “set”
Classes for different expressions
Class for identifier, integer, string
4
3/9/15
If I were you I would reuse this main
int
main( int argc, char *argv[] )
{
istream *br;
ifstream infile;
// check args and open the file
if( argc == 1 )
br = &cin;
else if( argc != 2 ) {
return 1; // print an error msg
} else {
infile.open(argv[1]);
if( infile.is_open() )
br = &infile;
else {
cout << argv[1] << " can't be opened" << endl;
return 1;
}
}
// pass br as the first argument to Program()
5