Pattern 29Syntax-Directed Translator

Purpose

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

Discussion

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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.