Enhance the P2 interpreter we wrote in class to perform automatic type conversions between integers and booleans:
When an integer is needed, a boolean will automatically convert to 0 (if false) or 1 (if true). For example, 4 + true will evaluate to 5.
When a boolean is needed, an integer will
automatically convert to false (if 0) or true (if non-zero). For
example, if x is 4 then if (x) { print(x); }
will output 4.
Suppose that we would like to add the boolean
operators && (AND) and ||
(OR) to the P2 interpreter that we wrote in class.
a) Should these operators have the same precedence? What should their precedence be relative to the other operators that P2 already supports?
b) Enhance the P2 grammar to include these operators.
c) Enhance the P2 parser to handle these operators.
d) Enhance the P2 interpreter to handle these operators.
As an extension to the previous exercise, add the ! (NOT) operator to the P2 interpreter. This is a unary operator, unlike all other existing operators which are binary, so you will need to extend the grammar and abstract syntax accordingly.
Assuming that we have not implemented the
automatic type conversions from a previous exercise, a P2 program
might produce an error at run time, for example if we try to add two
values, one of which is the Boolean constant false.
Enhance the P2 interpreter so that it performs static type checking: before a program starts to run, the interpreter should verify that all the operations in the program are type-correct.
A P2 program cannot read input, so every time you run a P2 program you will get the same result.
Let T(N) be the maximum time for running any P2 program whose length is N characters. Is T(N) a polynomial function of N? If so, prove it. If not, describe how to write a series of P2 programs whose running times increase non-polynomially (e.g. exponentially) in the length of the programs.