# ROSE Compiler Framework/Abstract Syntax Tree

The main intermediate representation of ROSE is its abstract syntax tree (AST). To use a programming language, you have to get familiar with the language syntax, semantics, etc. To use ROSE, you have to get familiar with its internal representation of an input code.
The best way to know AST is to visualize it using simplest code samples.

## Visualization of AST
### Overview

Three things are needed to visualize ROSE AST:
* Sample input code: you provide it
* a dot graph generator to generate a dot file from AST: ROSE provides dot graph generators
* a visualization tool to open the dot graph: ZGRViewer and Graphviz are used by ROSE developers
If you don't want to install ROSE+ZGRview + Graphvis from scratch, you can directly use ROSE virtual machine image, which has everything you need installed and configured so you can just visualize your sample code.

### Sample input code

Please prepare simplest input code without including any headers so you can get a small enough AST to digest.

### Dot Graph Generator

We provide ROSE_INSTALLATION_TREE/bin/dotGeneratorWholeASTGraph (complex graph) and dotGenerator (a simpler version) to generate a dot graph of the detailed AST of input code.
Tools to generate AST graph in dot format. There are two versions
* dotGenerator: simple AST graph generator showing essential nodes and edges
* dotGeneratorWholeASTGraph: whole AST graph showing more details. It provides filter options to show/hide certain AST information.
command line:
To skip builtin functions
* dotGeneratorWholeASTGraph -DSKIP_ROSE_BUILTIN_DECLARATIONS yourcode.c

### Dot Graph Visualization

To visualize the generated dot graph, you have to install
* Graphviz: http://www.graphviz.org/Download.php .
* ZGRViewer: http://zvtm.sourceforge.net/zgrviewer.html#download. (Version 0.8.x is recommended since 0.9.x has a bugs like inversed (reversed) direction to drag a graph around.)
Please note that you have to configure ZGRViewer to have correct paths to some commands it uses. You can do it from its configuration/setting menu item. Or directly modify the text configuration file (.zgrviewer).
One example configuration is shown below (cat .zgrviewer)
You have to configure the run.sh script to have correct path also
cat run.sh

### Example session

A complete example

### example output

We put some example source files and their AST dump files into: https://github.com/chunhualiao/rose-ast
* for example: https://github.com/chunhualiao/rose-ast/blob/master/func1.c_WholeAST.dot.png
* https://github.com/chunhualiao/rose-ast/blob/master/parallelfor.c_WholeAST.dot.png

### Print AST as horizontal tree

SageInterface functions
A translator (textASTGenerator) is also available, with its source code under exampleTranslators/defaultTranslator .
* make install-tools will install this tool
* textASTGenerator input.c will generate a text output of the entire AST

#### Example use inside of gdb

* to print a portion of AST to the screen
* to print a portion of AST into a text file

#### textASTGenerator

Example command line use:
textASTGenerator -c test_qualifiedName.cpp
cat test_qualifiedName.cpp.AST.txt

### Render the AST in HTML

The repo errington1/ast-to-html contains a tool for rendering the Rose abstract syntax "graph" as collapsible HTML with shared nodes and cycles represented by HTML links. For now, it's available only from the command line. The plan is to add command-line options to omit parts of the tree and to make the tool available as a library. For now, it somewhat arbitrarily omit portions of the tree that originate from the file rose_edg_required_macros_and_functions.h.
The command:
will produce file.C.html which can be viewed with a browser:

## Sanity Check

We provide a set of sanity check for AST. We use them to make sure the AST is consistent. It is also highly recommended that ROSE developers add a sanity check after their AST transformation is done. This has a higher standard than just correctly unparsed code to compilable code. It is common for an AST to unparse correctly but then fail on the sanity check.
The recommend sanity check is
* AstTests::runAllTests(project); from src/midend/astDiagnostics. Internally, it calls the following checks:
** TestAstForProperlyMangledNames
** TestAstCompilerGeneratedNodes
** AstTextAttributesHandling
** AstCycleTest
** TestAstTemplateProperties
** TestAstForProperlySetDefiningAndNondefiningDeclarations
** TestAstSymbolTables
** TestAstAccessToDeclarations
** TestExpressionTypes
** TestMangledNames::test
** TestParentPointersInMemoryPool::test
** TestChildPointersInMemoryPool::test
** TestMappingOfDeclarationsInMemoryPoolToSymbols::test
** TestLValueExpressions
** TestMultiFileConsistancy::test //2009
** TestAstAccessToDeclarations::test(*i); // named type test
There are some other functions floating around. But they should be merged into AstTests::runAllTests(project)
* FixSgProject(*project); //in Qing's AST interface
* Utility::sanityCheck(SgProject* )
* Utility::consistencyCheck(SgProject*) // SgFile*

## Text Output of an AST

Just call: SgNode::unparseToString. You can call it from any SgLocatedNode within the AST to dump partial AST's text format.

### print AST as horizontal tree

SageInterface functions
A translator (textASTGenerator) is also available, with its source code under exampleTranslators/defaultTranslator .
Example use inside of gdb:
* to print a portion of AST to the screen
* to print a portion of AST into a text file
Example command line use:
textASTGenerator -c test_qualifiedName.cpp
cat test_qualifiedName.cpp.AST.txt

## AST Iterator

1) The iterator class: The iterator follows the STL iterator pattern and is implemented as pre-order traversal and maintains its own stack. The iterator performs the exact same traversal as the traversal classes in ROSE (it is using the same underlying information):
Some more features:
* By default it is not traversing null pointers (you won't see them). However, if you want to see&traverse also all the null pointers, you can use the begin function with: ast.begin.withNullValues
* It also has a feature to exclude subtrees from traversing during the traversal: You can simply call on the *iterator*:
** i.skipChildrenOnForward; ++i; // skips the children of current node and goes to the next node that follows in the traversal after all those children
Relevant sourcefiles
* https://github.com/rose-compiler/rose-develop/blob/master/src/midend/astMatching/RoseAst.h
* https://github.com/rose-compiler/rose-develop/blob/master/src/midend/astMatching/RoseAst.C

## Content of AST
### SgType

Some useful member functions
* get_base_type :member function on some IR nodes derived from SgType and returns the non-recursively striped (immediate) type under the typedefs, reference, pointers, arrays, modifiers, etc.
* findBaseType recursively strip away all
* SgType * stripType (unsigned char bit_array=STRIP_MODIFIER_TYPE|STRIP_REFERENCE_TYPE|STRIP_POINTER_TYPE|STRIP_ARRAY_TYPE|STRIP_TYPEDEF_TYPE) const
Returns hidden type beneath layers of typedefs, pointers, references, modifiers, array representation, etc.
* SgType * stripTypedefsAndModifiers const

### File location information

All AST nodes with file location information derive from SgLocatedNode, which has start and end Sg_File_Info to indicate begin and end location information.
You can obtain and printout the pair of location information by calling
The output for display may look like
As you can see, there are AST nodes generated by ROSE's frontends or by a translator. A transformation generated located node may not have line or column numbers.
You can get file name, line, column numbers

### Preprocessing Information

See more at ROSE Compiler Framework/PreprocessingInfo
In addition to nodes and edges, ROSE AST may have attributes in addition to nodes and edges that are attached for preprocessing information like #include or #if .. #else. They are attached before, after, or within a nearby AST node (only the one with source location information.)
An example translator will traverse the input code's AST and dump information which may include preprocessing information.
* https://github.com/rose-compiler/rose/blob/master/exampleTranslators/defaultTranslator/preprocessingInfoDumper.C
For example
Source: http://www.rosecompiler.org/ROSE_Tutorial/ROSE-Tutorial.pdf (Chapter 29 - Handling Comments, Preprocessor Directives, And Adding Arbitrary Text to Generated Code)

## AST matching

ROSE Compiler Framework/AST Matching

## AST Construction

SageBuilder and SageInterface namespaces provide functions to create ASTs and manipulate them. Doxygen docs
* http://rosecompiler.org/ROSE_HTML_Reference/namespaceSageBuilder.html
* http://rosecompiler.org/ROSE_HTML_Reference/namespaceSageInterface.html