Pattern 29Syntax-Directed Translator


This pattern generates text using a grammar, or equivalent hand-built parser, embedded with actions.


Syntax-directed translators are little more than grammars salted with actions (code snippets). They don’t build internal models and then walk them to generate output.

Putting actions directly in a grammar sometimes makes the grammar difficult to read. It also locks the grammar into a single bit of translator functionality. It’s often a good idea to disentangle actions from the grammar by following what we did in Pattern 26, Bytecode Assembler (another example of a syntax-directed translator). The assembler grammar defined placeholder methods that describe the translator functionality:

Get Language Implementation Patterns now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.