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 ( ... |
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.