DEV Community

Discussion on: ELI5: How does someone write a new computer language?

Collapse
 
deciduously profile image
Ben Lovy • Edited

A programming language interpreter is just a program itself that can understand strings of text and semantically tag them, and then evaluate that result.

I'll include a snippet of my latest post, which talks about a problem I had making my first programming language interpreter:

For a small concrete example, let's look at the input string + 2 (* 3 4) 5. To work with this input, we need to build a Abstract Syntax Tree structure like the following:

S-Expression(
    Symbol("+"),
    Number(2),
    S-Expression(
        Symbol("*"),
        Number(3),
        Number(4),
    ),
    Number(5),
)

The whole program is represented as an S-Expression. When our program sees one of these with multiple elements, it's going to try to execute it as a function call, looking up the function from the symbol in the first position. First, though, it's going to recursively evaluate all of its children - so if any of them are themselves s-expressions, we'll get them into values we can work with first. In this example, the inner S-Expression (* 3 4) will be evaluated first:

S-Expression(
    Symbol("*"),
    Number(3),
    Number(4),
)

This will be interpreted as a function call, and evaluates to:

S-Expression(
    Symbol("+"),
    Number(2),
    Number(12),
    Number(5),
)

Now we have an operation as the first element of the S-expression and some numbers with which to apply it. When this evaluates, we're left with just Number(19), which can be displayed to the user as the result of the computation. To get the Symbol("+") to mean "addition", the program will keep track of an environment which associates names like "+" with functions.

Not all interpreters use S-Expressions like this, but its one of the simplest ways to get started. Writing an interpreter means writing functions that can turn text into a tree like the above, and then evaluate that tree.