DEV Community

Cover image for Making a Math Interpreter: The Setup
John Nyingi
John Nyingi

Posted on • Updated on

Making a Math Interpreter: The Setup

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 expression 2+5*4 can be represented in the below AST graph
    AST TREE
    The expression 5*4 is processed first then the result is added to 2

  • Tokens: These are objects used to represent each element in a program. Given our expression 2+5*4, the tokens are NUMBER 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.

  • Expression, Factor and Terms are as shown below;
    Expression

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 image
  • Give it a name
    image

  • Select a .Net core version. I'll be using 3.1
    image

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);
            }
        }
Enter fullscreen mode Exit fullscreen mode

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);
            }

Enter fullscreen mode Exit fullscreen mode

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

Discussion (0)