An implementation of a Context Free Grammar for a command-line-based calculator with variable storage, created in C++. Implementing a Lexer for tokenization, a Parser to construct an Abstract Syntax Tree and finally the calculator/interpreter which parses the tree and outputs the result of the equation.
After running the program there should be some output to the terminal matching:
Welcome to the CFG Calculator!
Enter an expression to calculate
Type 'exit' at any time to quit
>Note
">" Here represents the user input
The user is then able to enter a mathematical expression, the parsed expression and the result will be displayed
> 2 + 2 * 2
Parsed expression: (2+(2*2))
Result: 6
To set a variable the input should start with a string followed by a "=" then the expression to set your variable to
> myVariable = 3 + 4 + 6 * (7 - 3)
Parsed expression: (myVariable=((3+4)+(6*(7-3))))
result: 31Warning
Constants can be overwritten.
If the user sets a variable, like pi this will overwrite the constant value of pi.
Now if we want to access the value of myVariable we can just put it into our expressions, like it's a number.
> 3 / myVariable
Parsed expression: (3/myVariable)
Result: 0.0967742To clear the variables, and the terminal the user can simply type clear
> 3 / myVariable
Parsed expression: (3/myVariable)
Result: 0.0967742
> clearThis will clear the terminal and prompt the user to clear their variables
Would you like to clear the variables? (y/n)
> clear - Clears the terminal and will prompt user to also clear variables
exit - Exits the program
vars - Lists all set variables in the calculator