Skip to Main Content
Language Implementation Patterns
book

Language Implementation Patterns

by Terence Parr
December 2009
Intermediate to advanced content levelIntermediate to advanced
380 pages
9h 2m
English
Pragmatic Bookshelf
Content preview from Language Implementation Patterns

Using a Tree Grammar to Create Templates

A surprising number of translators spit out the same language that they read in. There are lots of useful things we can do such as refactoring, reformatting, instrumenting, or simplifying source code. In this section, we’re going to build a translator that reads in some Cymbol code (the C++ subset from Pattern 19, Symbol Table for Classes) and spits it back out in more or less the same shape. For example, here’s a sample Cymbol file:

trans/ast-st/s.cymbol
 
void​ f(​int​ a[], ​int​ x) {
 
if​ ( x>0 ) ​return​;
 
else​ x = 10;
 
a[3] = 2;
 
}

We want to read that in and send it back out using our translator program:

 
$ ​java Test s.cymbol
 
void f(int *a, int x) { // "int a[]" becomes "int *a"
 
if ( ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Implementation Patterns

Implementation Patterns

Kent Beck

Publisher Resources

ISBN: 9781680500097Errata Page