Card 08/ 08

RecapDifficulty: Advanced1 min

Recap: Interpreter Pattern

One class per rule and a tree per sentence; the parsing is someone else's job.

Interpreter represents a small language as classes and evaluates its sentences as trees.

  • Intent. Represent a grammar as classes, and interpret sentences in it.
  • Participants. An abstract expression with interpret(context), terminal expressions for the leaves, non-terminal expressions that combine others, and a context to evaluate against.
  • The tree. Non-terminals hold other expressions, so the structure is Composite's; evaluation runs from the leaves up.
  • In the wild. Python's ast module builds the same kind of tree for its own code, and then compiles it rather than walking it.
  • The trap. The pattern does not parse; text becomes a tree through a parser, written or generated.
  • When not. A large grammar, evaluation that must be fast, or a language that already exists.