Syntax-Directed Translation

A syntax-directed translator reads input and immediately emits output as it goes. In the following image, we see the one-stage application pipeline. Even though it has few moving parts, we can use this for a surprising number of DSLs.

images/trans/syntax-directed.png

Syntax-directed translators consist of a grammar (or equivalent hand-built parser) and output actions. For example, here is a rule that translates a scalar multiply, such as a x b, to Java:

 
mult : a=ID ​'x'​ b=ID {System.out.println($a.text+​"*"​+$b.text);} ;

Because syntax-directed translators make only one pass through the input, they can’t deal with forward references. For example, ...

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.