ANTLRMorph grammar follows the format of ANTLR grammar except several definitions:
- There's no tokens definition in morph, instead we use labels definition to set up label reference for token or rule.
- Options definition has the same syntax as ANTLR, but different option setting. conforms is the only option morph accepts currently.
- No global scope definition in morph.
- No lexer header definition. Therefore, if you're using a package setting, just put it once into the header definition.
Please check Morph grammar options and actions for more detail.
There are several distinct characteristics in morph rule definition:
- Unique grammatical context syntax.
- No grammar options.
- Morph rule has dynamic scope which is able to refer to elements with the stack of rules context.
- Only accept initial action block currently.
- No catch and finally definitions
ANTLRMorph allows you define rewrite alternatives in the context of the specified rule context. The context here means that which rule you're matching. Therefore, you can utilize it to do something different based on different context. For instance, you might have to rewrite something different for variable declarations matched at block level (locals) and for variable declarations matched in methods (parameters) and default rewrite for variables:
In the above example, please note that you have to put the context variable after the other two because the morph rule specified first would be given precedence over those specified later. To avoid ambiguity, morph is implemented by a simple law: winner is always the one matched first.
Grammatical context syntax
- "..." here is a keyword which means anything on the rule invocation stack.
- if you would like to match input in the context of single rule:[rule-name], just use the basic form: rule-name
ANTLRMorph implements its dynamic scope within a parse tree structure instead of a stack used in ANTLR. The syntax and the usage of dynamic scope are same as those in ANTLR grammar. However, morph provides you a 2-way reference of scope attributes in the parse tree. In other words, morph can not only search attributes downward until reaching the bottom of tree but also do searches upward until reaching the top of tree. We'll address this more in the other section.
Remember to initialize your scope attributes in the @init block if necessary. Also note that when you're using the scope attributes in the action blocks including @init block, you must use the form $rule-name::attribute-name to access the scope attributes you've set up within the scope block.
Each rule alternative contains an input pattern and an output pattern. ANTLRMorph takes the token stream matched on the input pattern, and prepares those matched elements for the attributes of the template defined by the output pattern. Currently, morph generates text instead of a token stream; therefore, the grammar output pattern would actually be a StringTemplate.