Question
This is a c++ program please run the code in the visual studio code and complete the project. The tester code is given below the
This is a c++ program please run the code in the visual studio code and complete the project. The tester code is given below the code in bold format. // Project 0: Inheritance in C++, Parsing/ASTs, S-expressions, Polish notation
// Write a library for converting between (Polish + S-expr) notation and an AST, and for evaluating these ASTs recursively.
// This notation is normal, binary-operator prefix (Polish) notation, but allowing for parentheses to indicate a k-ary use of an operation. Parse these using the normal precedence and associativity, into (strictly) binary operations and literals (natural numbers).
// You must support +, -, *, and ^ operators and for each a binary usage where parentheses are optional, and k-ary usage with parentheses required and some caveats below.
// These are some examples of equivalent inputs:
// + 1 25 => (+ 1 25)
// - + 3 2 1 => (- (+ 3 2) 1)
// (- 3 2 1) => (- (- 3 2) 1)
// (- 2) => (- 0 2)
// (+ 3) => 3
// Treat contiguous sequences of digits as a single natural-number token, but all others as single-character symbol tokens.
// Parse errors: return null from the parseExp function
// e.g.,
// (* 4) error, * and ^ cannot be used as unary operators
// (^ 5) ditto
// () error, parens cannot go alone
// (+) ditto, operators must have 1 or more operands in all cases
// x ditto, only numeric 0-9 characters, whitespace, (, ), +, -, *, ^, are valid input characters
// Ignore runtime errors, return any integer
// We'll include some STL libraries. We don't need/want any other libraries.
#include
#include
#include
// Exp is an purely abstract type (or Interface) for Expressions
class Exp
{
public:
virtual ~Exp() { }
virtual void print() = 0;
virtual int eval() = 0;
// Must parse an expression from std::cin and return a pointer to an AST, or null to indicate failure
static Exp* parseExp();
};
// PlusExp is a concrete type for a (+ ... ...) binary-operation subexpression
class PlusExp : public Exp
{
private:
Exp* lhs;
Exp* rhs;
public:
PlusExp(Exp* _lhs, Exp* _rhs) : lhs(_lhs), rhs(_rhs)
{
}
virtual ~PlusExp()
{
delete lhs;
delete rhs;
}
virtual void print()
{
// Print as an s-expr
std::cout << "(";
std::cout << "+ ";
lhs->print();
std::cout << " ";
rhs->print();
std::cout << ")";
}
virtual int eval()
{
return lhs->eval() + rhs->eval();
}
};
// LitExp is a concrete type for a (+ ... ...) binary-operation subexpression
class LitExp : public Exp
{
private:
int nat; // A literal is a small natural number, but we'll use int so (-) is closed over this type.
public:
LitExp(int _n) : nat(_n)
{
}
virtual ~LitExp()
{
}
virtual void print()
{
std::cout << nat;
}
virtual int eval()
{
return nat;
}
};
// A static function that builds an expression from Polish notation read from STDIN
Exp* Exp::parseExp()
{
std::string token;
std::cin >> token;
if (token == "+")
{
Exp* lhs = parseExp();
Exp* rhs = parseExp();
if (lhs && rhs)
return new PlusExp(lhs, rhs);
if (lhs) delete lhs;
if (rhs) delete rhs;
return 0;
}
else try
{
int n = stoi(token);;
return new LitExp(n);
}
catch (...)
{
// std::cout << "'" << token << "' not recognized." << std::endl;
return 0; // Return null to indicate stoi() failure
}
}
TESTER CODE: please save the code as tester.py and test with the above code whether it is passing all the conditions or not.
#!/usr/bin/python3
# #######################
#
# This file runs tests for this coding assignment.
# Read the file but do not modify.
#
# #######################
#
# Autograde test.py runner
# Some code taken from test.py from submit
#
import os, sys, subprocess, json, argparse, signal
from subprocess import Popen, PIPE, STDOUT, TimeoutExpired
TIMEOUT = 15
#####################
# Start Test Utilities
#####################
def preparefile(file):
pass
def runcmdsafe(binfile):
b_stdout, b_stderr, b_exitcode = runcmd(binfile)
return b_stdout, b_stderr, b_exitcode
def runcmd(cmd):
#executed = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
#stdout, stderr = executed.communicate()
#return stdout, stderr, executed.returncode
stdout, stderr = None, None
if os.name != 'nt':
cmd = "exec " + cmd
with Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) as process:
try:
stdout, stderr = process.communicate(timeout=TIMEOUT)
except TimeoutExpired:
if os.name == 'nt':
Popen("TASKKILL /F /PID {pid} /T".format(pid=process.pid))
else:
process.kill()
exit()
return stdout, stderr, process.returncode
def assertequals(expected, actual, info=''):
if expected == actual:
passtest('')
else:
if (info): info = f' {info}'
failtest(f'Expected {expected}, but got {actual}.{info}')
def failtest(message):
testmsg('failed', message)
def passtest(message):
testmsg('passed', message)
def testmsg(status, message):
x = {
"status": status,
"message": message
}
print(json.dumps(x))
sys.exit()
#####################
# End Test Utilities
#####################
verbose = False
def runtest(name):
global verbose
print('---------------------')
print(f' Running test: {name}')
try:
python_bin = sys.executable
output = subprocess.check_output(f'{python_bin} driver.py', cwd=f'test/{name}', shell=True)
y = json.loads(output)
status = y["status"]
message = y["message"]
stdout = output
if verbose and len(message) > 0:
print(" STDOUT: ")
print(message)
if status == "failed":
print(' FAILED')
return False
if status == "passed":
print(' PASSED')
return True
except:
print(' TIMED OUT')
return False
def runtests():
tests = listtests()
num_passed = 0
for test in tests:
if runtest(test):
num_passed += 1
print(' ===========================')
print(f'Summary: {num_passed} / {len(tests)} tests passed')
print('===========================')
def listtests():
tests = [test for test in os.listdir("test/") if not test.startswith(".")]
tests.sort()
return tests
def main():
global verbose
parser = argparse.ArgumentParser()
parser.add_argument('--list', '-l', help='List available tests', action='store_true')
parser.add_argument("--all", "-a", help='Perform all tests', action='store_true')
parser.add_argument('--verbose', '-v', help='View test stdout, verbose output', action='store_true')
parser.add_argument('--test', '-t', help='Perform a specific testname (case sensitive)')
args = parser.parse_args()
if args.verbose:
verbose = True
if args.all:
runtests()
return
if args.test:
if not os.path.exists(f'test/{args.test}'):
print(f'Test "{args.test}" not found')
return
runtest(args.test)
return
if args.list:
print("Available tests: ")
print(*listtests(), sep=' ')
return
parser.print_help()
if __name__ == "__main__": main()
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