The preceding project followed a CFG to construct a parser. This is very nice, but there is a big problem: the Calc language is not context-free. In fact, there are two problems, as follows:
- Any use of a variable in input statements, output statements, and assignments must be preceded by a declaration of that variable.
- Any variable must not be declared more than once.
Such requirements cannot be expressed in a context-free language.
In addition, Calc has just one data type—that is, floating-point numbers—but consider if it also had a string type. You can add subtract two numbers, but you cannot subtract two strings. If a variable named a is declared of type number and a variable named b is declared of type string, you cannot assign a to b, or vice versa.
In general, the operations allowed on a variable depend on the type used to declare that variable. And also, this constraint cannot be expressed in a CFG.
Instead of defining a formal context...