-
Notifications
You must be signed in to change notification settings - Fork 133
How to create a translator
Translator basically converts one AST to another version of AST. The translation process may add, delete, or modify the information stored in AST.
A ROSE-based translator usually has the following steps
- Search for the AST nodes you want to translate.
- Perform the translation action on the found AST nodes. This action can be one of two major variants
- Updating the existing AST nodes
- Creating new AST nodes to replace the original ones. This is usually cleaner approach than patching up existing AST and is better supported by SageBuilder and SageInterface functions.
- Deep copying existing AST subtrees to duplicate the code. May expression subtrees should not be shared. So deep copy them is required to get the correct AST.
- Optionally update other related information for the translation.
Get familiar with the ASTs before and after your translation. So you know for sure what your code will deal with and what AST you code will generate.
The best way is to prepare simplest sample codes and carefully examine the whole dot graphs of them.
More details for visualize AST are available at How to visualize AST.
To make a translator you'll need to call ::frontend (Frontend) to obtain a SgProject node of an AST, then transform the AST as you see fit (Midend), then call ::backend (Backend) to generate new code. All node classes start with the letters "Sg" (short for "Sage"), and the base class SgNode.
The following code will compile the code specified on the command line then run the backend the build an executable and the "new" source code made with no transformations.
// Example ROSE Translator: used for testing ROSE infrastructure
#include "rose.h"
int main( int argc, char * argv[] )
{
// Initialize and check compatibility. See Rose::initialize
ROSE_INITIALIZE;
// Build the AST used by ROSE
SgProject* project = frontend(argc,argv);
// Run internal consistency tests on AST
AstTests::runAllTests(project);
// Insert your own manipulation of the AST here...
// Generate source code from AST and call the vendor's compiler
return backend(project);
}
The following code is the original source code and the Rose generated source.
// Example input file for ROSE tutorial
#include <iostream>
// Main function int main()
typedef float Real;
int main( )
{
int x=0;
bool value = false ;
for (int i=0; i < 4; i++) {
int x;
}
return 0;
}
// Example input file for ROSE tutorial
#include <iostream>
// Main function int main()
typedef float Real;
int main( )
{
int x = 0;
bool value = false;
for (int i = 0; i < 4; i++) {
int x;
}
return 0;
}
While the code is not identical the generated source code is a close reproduction.