Card 06/ 08
The Interpreter Pattern Does Not Parse
The pattern evaluates a tree; turning text into that tree is a separate job it does not cover.
The Interpreter pattern says how to represent and evaluate a sentence once it is a tree of objects, and says nothing about how text becomes that tree. That step, parsing, is a separate job, and for any grammar beyond a few rules it is the larger one. This card separates the two, and says where parsing comes from.
A tree built by hand as Add(Number(1), Multiply(Number(2), Variable("x"))) is evaluated. Which class reads the text 1 + 2 * x? Decide, then look.
None. The tree is built by hand, and no class in it ever sees the characters of the sentence. To accept rules typed by a user, the program needs a parser in front of the classes.
A parser has to decide that * binds tighter than +, handle brackets, and report a useful error for 1 + * 2. For a grammar of a handful of rules, a small hand-written parser is enough. For more, a parser generator, a tool that writes the parser from a description of the grammar, such as ANTLR or Lark, does the job, and the Interpreter classes become the tree it builds.
The mistake is to expect the pattern to cover input from users, and then to grow the string handling it was meant to replace in front of it. Plan the parser as its own component, with its own tests.
← → move through sections and cards