Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Syntax-directed interpreter for the Pie language

Pattern: A syntax-directed interpreter directly executes source code without building an intermediate representation and without translating it to another language.

This page provides a sample implementation for a dynamically-typed Python-like language called Pie. It's a wee bit complicated because the memory spaces do dual duty as scopes and variable storage. It also has to switch between immediate and deferred execution (like PostScript does). The source is available as an attachment to this page.

A syntax-directed interpreter mimics what we do when we trace source code manually. As we step through the code, we parse, validate, and execute instructions. Everything happens in the parser because a syntax-directed interpreter doesn't create an AST or translate the source code to bytecodes or machine code. The interpreter directly feeds off of syntax to execute statements.

...

This interpreter isn't the simplest one around. Because we're
executing source code not machine code, we have to deal with:
immediate versus deferred mode execution, exceptions to implement
return, and the combined notion of scopes and memory spaces. The
more we process code towards machine code, the simpler the actual
interpreter component (and the more it looks like a CPU emulator).

Before getting there, let's look at a similar interpreter pattern that constructs an AST and drives execution with a tree visitorDon't forget that the source is available as an attachment to this page.