Question
The purpose of this exercise is to write a syntax generator for a subset of the C++ programming language that will write random C++ programs
The purpose of this exercise is to write a syntax generator for a subset of the C++ programming language that will write random C++ programs to a file. By writing these random syntactically correct programs, you will further develop your understanding of the difference between syntax and semantics.
Consider the following set of productions that define a subset of the C++ programming language:
|
| if (
| if (
| if (
| if (
| while (
|
| double
|
|
|
You will notice that this grammar is a combined phrase and lexical grammar. This is for simplification purposes.
If you are interested in seeing an exhaustive BNF formulation of the C programming language, please view the following: http://www.cs.man.ac.uk/~pjj/bnf/c_syntax.bnf. This contains over 60 productions and may be a little much for the purposes of this exercise.
Problem 1. Write a program in C++ that starts with the root non-terminal
Hint 1: The following is a sample random program that was generated by my solution. I added some white spaces to make it more readable:
int main()
{
int F0Z = 0262;
if (22682 / 525)
double S1;
else
S = U;
while (8 - 594873)
{
while (97942 / 6871573097 * 7261055)
{
while (9307 * M / 4 / 2 + 4 - 7 / K)
{
double A;
}
}
}
return 0;
}
Hint 2: I solved this problem both in C++ and Python. In Python, I was able to write the solution in less than 100 lines of code (it is a really great language). My C++ solution makes use of a class called Production whose instances represent the various productions that define the C/C++ grammar subset above. My definition of the class is shown below:
class Production
{
private:
string lhs;
vector
vector
public:
Production();
Production(string);
void add_rhs(string, double); // adds new rhs to the production
string expand() const; // returns one of the rhs choices using
// a random number generator
};
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started