Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 20, 2021 12:49 pm GMT

Implementing a Math Interpreter using C: Part1

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

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 we are going to

  • Add Tokens
  • Add a Lexer
  • Add Unit Tests

Original Link: https://dev.to/j0nimost/implementing-a-math-interpreter-using-c-part1-2mf

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To