Implementing a Programming Language in Swift — Part 5: The Main function
This is the fifth part in a tutorial series on “Writing a Programming Language in Swift.” Be sure to check out Part 4.
In the previous tutorials, we completed implementing a Lexer and Parser for our calculator. Now all there is left i tos simply traverse our AST and “interpret” some output.
So… almost there 💪🏻!
You might have noticed that the Nodes
we created when parsing (Float
& InfixOperation
) evaluate both quite easily to Float
values. So all we have to do to be able to evaluate our AST is to add a protocol method to our Node
protocol for interpreting each single Node
and implement it in our Node
structs:
protocol Node { func interpret() throws -> Float}// ...extension Float: Node { func interpret() throws -> Float { return self }}struct InfixOperation: Node {// ... func interpret() throws -> Float { let left = try lhs.interpret() let right = try rhs.interpret() switch op { case .divideBy: return left / right case .times: return left * right case .minus: return left - right case .plus: return left + right } }
}
That’s it, now we our ready create our main function, let’s call it run
:
func run(code: String) throws { let tokens = Lexer(code: code).tokens let parser = Parser(tokens: tokens) let ast = try parser.parse() print(ast.interpret())}let code = "4 + 2 * 5 + 3 * (1 + 4)"run(code: code) // OUTPUTS: 29
Congratulations! We now have a working calculator.
It doesn’t look like much, but as you will notice in future tutorials, adding programming language features such as variables and functions isn’t especially hard.
Next Steps
A logical next step to this is to wrap this into a command line tool. Every programming language has one.
Swift star John Sundell published a very good tutorial on this, and I’ll leave a link to it here for you to follow. Without much effort, you will be able to run our code with a command in the terminal:
> myinterpreter "(2 + 3) * 5"
> 25
Our next step however, will be to turn our simple calculator language into something that resembles a programming language. Starting by adding variables.
Stay tuned!
I hope you guys found this tutorial interesting and as always, don’t be shy to give feedback e.g. by clapping or writing a response.
P.S. Remember that you can follow me here on Medium for notifications on future tutorials.