Definition
Let's start by breaking down some few phrases and terms used
- Interpreter: An interpreter is a program that interprets code to machine code. Basically, in our case the interpreter will take math expressions and convert them to C# code then to Machine code.
AST: An Abstract Syntax Tree is a graph representation of statements or expressions.
In our case, a simple math expression2+5*4
can be represented in the below AST graph
The expression5*4
is processed first then the result is added to2
Tokens: These are objects used to represent each element in a program. Given our expression
2+5*4
, the tokens areNUMBER ADD NUMBER MULTIPLY NUMBER
Lexer: This is a function that converts the expression into Tokens
Parser: This is a function that converts the Lexer'ed tokens into AST. This function sets up the hiereachy of execution.
What will I be using?
- Visual Studio
- Dotnet Runtime
3.1
- Git and Github
- Travis-CI
The Setup
- Open visual studio and create a console application
Init
So lets give our console application a REPL like interface. To achieve this we will capture user inputs and output the same. So in the Program.cs
change the main method to the below code
static void Main(string[] args)
{
Console.WriteLine("Welcome to Calcy, a nifty and easy to use math interpreter.");
while(true)
{
Console.Write(">> ");
string input = Console.ReadLine();
Console.WriteLine(">> {0}", input);
}
}
So we add the above code to achieve this, it gets a user input and outputs the same.
It would be nice if we could allow users to exit the console using the exit()
phrase.We can do this by adding the below code.
Console.WriteLine("Welcome to Calcy, a nifty and easy to use math interpreter.");
while(true)
{
Console.Write(">> ");
string input = Console.ReadLine();
if(input == "exit()")
{
break;
}
Console.WriteLine(">> {0}", input);
}
So now we have fully functional REPL interface.
In the next chapter #Part2 - Lexer we are going to
- Add Tokens
- Add a Lexer
- Add Unit Tests
Top comments (0)