Programming Project in C++ - Homework 2 | ECS 140A, Assignments of Programming Languages

Material Type: Assignment; Class: Programming Languages; Subject: Engineering Computer Science; University: University of California - Davis; Term: Winter 2006;

Typology: Assignments

Pre 2010

Uploaded on 07/31/2009

koofers-user-6gh
koofers-user-6gh 🇺🇸

10 documents

1 / 5

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Homework 2: Programming Project (C++)
Due: 26 Jan 2006, 11:59 PM
Overview
The primary goal of this assignment is to help you develop a better understanding of parsing and compiling, and to
enable some familiarity and practical programming experience with C and C++.
The X programming language is similar to C, C++, Pascal, and Modula-2, but it differs syntactically and seman-
tically, and is considerably simpler. You are to write a C++ program that translates X programs to their semantically
equivalent C programs. For instance, as shown in Figure 1, the translator transforms a program, PX, written in X, into
an equivalent program, PC, written in C.
Translator
PX
PC
Figure 1: X to C translator
To verify that your translator works correctly, you are to compile and execute the generated program.
The X Language
The following grammar partially describes X’s syntax. In the EBNF below, non-terminal symbols start with capital
letters whereas terminals start with small letters. Certain terminal symbols are quoted to avoid confusion with the
meta-symbols.
Program ::= Block
Block ::= {Declaration} {Statement}
Declaration ::= VariableDeclaration | ConstantDeclaration
VariableDeclaration ::= var Id {‘,’ Id}
ConstantDeclaration ::= const Id ‘=’ Number
Statement ::= Assignment | Print | GuardedIf | GuardedDo
Assignment ::= Id ‘:=’ Expression
Print ::= print Expression
GuardedIf ::= if { do Expression ‘->’ Block end} end
GuardedDo ::= loop {do Expression ‘->’ Block end} forever
Expression ::= Simple [ Relop Simple ]
Simple ::= Term { Addop Term }
Term ::= Factor { Multop Factor }
Factor ::= ‘(’ Expression ‘)’ | Id | Number
Relop ::= ‘=’ | ’<’ | ’>’ | ‘/=’ | ‘<=’ | ‘>=’
Addop ::= ‘+’ | ‘-’
Multop ::= ‘*’ | ‘/’
The following rules complete the syntactic definition of X:
An X program is followed by an end-of-file character. Extra text is not legal.
The non-terminal Id represents a nonempty sequence of letters other than one of the keywords. The non-
terminal Number represents a nonempty sequence of digits.
ECS 140A -1- Winter 2006
pf3
pf4
pf5

Partial preview of the text

Download Programming Project in C++ - Homework 2 | ECS 140A and more Assignments Programming Languages in PDF only on Docsity!

Homework 2: Programming Project (C++) Due: 26 Jan 2006, 11:59 PM

Overview

The primary goal of this assignment is to help you develop a better understanding of parsing and compiling, and to enable some familiarity and practical programming experience with C and C++. The X programming language is similar to C, C++, Pascal, and Modula-2, but it differs syntactically and seman- tically, and is considerably simpler. You are to write a C++ program that translates X programs to their semantically equivalent C programs. For instance, as shown in Figure 1, the translator transforms a program, PX , written in X, into an equivalent program, PC , written in C.

Translator

PX

PC

Figure 1: X to C translator

To verify that your translator works correctly, you are to compile and execute the generated program.

The X Language

The following grammar partially describes X’s syntax. In the EBNF below, non-terminal symbols start with capital letters whereas terminals start with small letters. Certain terminal symbols are quoted to avoid confusion with the meta-symbols.

Program ::= Block Block ::= {Declaration} {Statement} Declaration ::= VariableDeclaration | ConstantDeclaration VariableDeclaration ::= var Id {‘,’ Id} ConstantDeclaration ::= const Id ‘=’ Number Statement ::= Assignment | Print | GuardedIf | GuardedDo Assignment ::= Id ‘:=’ Expression Print ::= print Expression GuardedIf ::= if { do Expression ‘->’ Block end} end GuardedDo ::= loop {do Expression ‘->’ Block end} forever Expression ::= Simple [ Relop Simple ] Simple ::= Term { Addop Term } Term ::= Factor { Multop Factor } Factor ::= ‘(’ Expression ‘)’ | Id | Number Relop ::= ‘=’ | ’<’ | ’>’ | ‘/=’ | ‘<=’ | ‘>=’ Addop ::= ‘+’ | ‘-’ Multop ::= ‘*’ | ‘/’

The following rules complete the syntactic definition of X:

  • An X program is followed by an end-of-file character. Extra text is not legal.
  • The non-terminal Id represents a nonempty sequence of letters other than one of the keywords. The non- terminal Number represents a nonempty sequence of digits.
  • Tokens are formed by taking the longest possible sequences of constituent characters. White spaces (blanks, tabs, or newlines) may precede or follow any token. For instance, ‘x=10’ and ‘x = 10’ are equivalent. Note that white space delimits tokens; e.g., “abc” is one token whereas “a bc” is two.
  • A comment in X begins with a “#” and consists of all characters up to, but not including, a newline, or end-of- file.

Semantics

X’s semantics follow for the most part C’s semantics, but there are significant differences:

  • X has only two types of variables: integer. Unlike local variables in C, the initial value of an integer variable in X is defined to be 4837. As in C, variables must be declared before use, and re-declaration of variables in the same block is an error. The declaration of a variable in an inner block hides the declaration of variable(s) of the same name declared in outer blocks; i.e., X has the same scope rules as C.
  • A conditional expression (that is, an expression following GuardedIf, or an expression used in a GuardedDO statement) is considered true if it is nonzero and false otherwise.
  • An expression containing relational operators has the same meaning as in C; e.g. the value of a < b is 0 if false and 1 if true.
  • A GuardedIf statement looks like the following:

if do e1 -> s1 end do e2 -> s2 end do e3 -> s3 end : do en -> sn end end

This is a conditional statement. During the execution of an statement, expressions e1, e2, ... are evaluated sequentially until an expression ei is found to be true. For this expression, its associated statement si is evaluated next. After evaluating si, the control transfers to the next statement after the GuardedIf statement.

  • A GuardedDo statement looks like the following:

loop do e1 -> s1 end do e2 -> s2 end do e3 -> s3 end : do en -> sn end forever

This is a loop statement. It is repeated until all ei’s are false. At each step, expressions e1, e2, ... are evaluated sequentially until an expression ei is found to be true. For this expression, its associated statement si is evaluated next. After evaluating si, the control of execution is returned to the top and the loop is executed again.

if do 1 -> var N N := i +1; end end print N end

When parsing the inner block, the most recent symbol table entry for N indicates that N is a variable, whereas the older symbol table entry for N indicates that N is a constant. Thus, N’s most recent entry is the correct one to use. For a re-declared variable, give an appropriate error message, and then continue by ignoring the re-declaration. For an undeclared variable or an attempted assignment to a constant, give an appropriate error message, and then stop your program by using C’s exit(1) statement. Since the number of variables in the program is neither known in advance nor bounded, your program must use a dynamically allocated data structure.

Part 4: Generating Code

Modify your parser so that it outputs appropriate C code. Feel free to use any C expression to represent X expressions into corresponding C expression. Print statement can similarly be implemented using printf functions. However, there is a constraint on the usage of statements of C: you can only use assignment, if-then-else, and while constructs of C to implement X statements. For instance, for the X program

int i i := 1 if do i/= 0 -> print 99 end # this is a comment end

your translator might produce a program that looks like the following:

main() {

int x_i = 4837; x_i = 1; if (x_i != 0) { printf("%d \n", 99); } }

Note that since the scanner discards white spaces and comments, the output is not as neatly formatted as the X program. In fact, the actual output from your translator will probably be less formatted than shown above; e.g., it is fine to output a single C token per line. Also note that the translator has prepended each X variable name with x in order to avoid conflicts with C reserved words. To test your translator, examine its C output (GC). Then, compile the GC and execute the resulting program. Verify that it does indeed execute as the source X program specifies.

Notes

  • Do not be overly concerned with efficiency. On the other hand, do not write a grossly in-efficient program.
  • Strive for simplicity in your programming. Do not try to be fancy. For example, the syntax graph translates directly into code. Learn and use that technique —- do not spend your time trying to improve that code. You will find it most helpful to use the names of the non-terminals as the names of your parsing procedures (except for the reserved words such as “if”).
  • Express your program neatly. Part of your grade will be based on presentation. Indentation and comments are important. Be sure to define each variable used with a concise comment describing its purpose. In general, each procedure should have a comment at its beginning describing its purpose. In this program, however, the parsing procedures do not need such introductory comments; a single explanatory comment before the first parsing procedure should suffice.
  • Write your program so that it works on standard output. Do not bother trying to get it to work on a file whose name is specified on the command line. Thus, your program, say named prog, will be invoked as prog if you want input to come from the keyboard, or as prog <t1.e if you want input to come from the file t1.e; use prog <t1.e >t1.c to take input from t1.e and to output to t1.c. The provided scanner uses getchar for input; use cout to output the generated code. So as not to intermix generated code and error/warning messages, output error messages to cerr (see the provided scanner for examples of how to do so.) Shell scripts will be provided that will help you test your program.
  • Create several of your own X test programs. Your will probably want different test data for the different parts. Be sure that your program works for boundary conditions; e.g., the shortest legal X program (empty).
  • if you haven’t used g++ before, note that some “Undefined” errors from the link-editor, ld, are caused by giving an inconsistent or missing forward declaration of a function, e.g., as in:

#include <iostream.h> main() { cout << "hi there" << g() << endl; } int g() { return 3; }

  • A Makefile will be provided along with the scanner. If you are not already familiar with make, it is well worth the effort to learn it. The make tool can greatly simplify the compilation and linking process. The manual page for make will provide you with enough information to get started; the first example is very similar to what you will need for your program.
  • Your program will be exercised by some shell scripts, which will be provided. These scripts depend on the exit status of your program. If your program detects a serious error, your program should exit as described earlier. If your program finishes normally, your main procedure should at the end return 0 or, equivalently, exit(0).
  • You must develop your program in parts as outlined above. Grading will be divided as follows:

Part Percentage 1 20 2 30 3 20 4 30 If your program does not fully work, hand in a listing of the last working part along with your attempt at the next part, and indicate clearly which is which. No credit will be given if the last working part is turned in. Points will be deducted for not following instructions, such as the above.

  • A message giving exact details of what to turn in, where the provided source and test files are, etc, will be posted to the newsgroup.
  • Get started now to avoid the last minute rush.