DEV Community

loading...

Lets build a simple interpreter from scratch in python, pt.01

smadev profile image sma Updated on ・2 min read

Hi!.
In this blog series we will see that will i be sucessful or not in my attempt to build a programming language, an interpreter, a parser, a compiler and a virtual machine. For any questions starting with 'why' the answer is always 'why not?' except theese:

  • Why Python? Python lets you focus on problem rather than fighting with language itself.
  • Why not Rust? Rust is causing hair loss while fighting against it.
  • Why not C? It explodes many times in your hands. You lose your hands.

If code that i write is not idiomatic and tastefull for you please ignore it.
Lets get started.

class Interpreter:
    def __init__(self):
        pass

    def run(self,code):
        for xs in code:
            self.eval(xs)


    # This is our magic function. It evauates xs parameter 
    # according to its first element  and calls appropriate 
    # member function and passes the parameter to that function.
    # If xs is not a list then returns xs itself:

    def eval(self,xs):
        if isinstance(xs,list):
            return self.__getattribute__(xs[0])(xs)
        return xs


    # Our first function (or opcode) is Print. If last item 
    # is a comma it doesn't print newline:  

    def Print(self,xs):
        if len(xs)==1:
            print()
            return
        l=len(xs)-1
        for i,x in enumerate(xs[1:]):
            e=self.eval(x)
            if i<l-1:
                print(e,end="")
            else:
                if e!=",":
                    print(e)
                else:
                    print(e,end="")

# This is AST (Abstract Syntax Tree) generated by 
# parser. Consisting of recursive lists
# (No, not lisp :P )
code=[
    ["Print","Hello World!","Sky is blue"],
    ["Print",1,","],
    ["Print",2,","],
    ["Print",3],
    ["Print","a"],
    ["Print","b"],
    ["Print"],
    ["Print","c"],
]

interpreter=Interpreter()

interpreter.run(code)
Enter fullscreen mode Exit fullscreen mode

Output is:

Hello World!Sky is blue
1,2,3
a
b

c
Enter fullscreen mode Exit fullscreen mode

Follow me on Twitter

Part 2: Basic Arithmetic Functions

Discussion (0)

pic
Editor guide