0

This is my grammar file


exp
    : exp operatorMulDivMod exp                 #expMulDivMod
    | exp operatorAddSub exp                    #expAddSub
    ;

varAssign
    : variable '=' exp
    | variable '+=' exp
    | variable '-=' exp
    | variable '*=' exp
    | variable '/=' exp
    | variable '.=' exp

I can process varAssign rules separately using my visitors, however I'd like to rewrite those rules such that I won't need to create separate visitor from them. I would like if I can do vaAssign -> equivalent exp expression. For example, if input is var += 2, can I rewrite it as var = var + 2 so that it is caught by my exp rule? I am using C# and antlr 4.4.5.3

Thank you

Grimson
  • 540
  • 1
  • 5
  • 21
  • There's no built-in mechanism for this. Rewrite these expressions with a visitor, and the other visitors you'll apply afterwards won't need to worry about these anymore. – Lucas Trzesniewski Oct 23 '16 at 12:35
  • How should I rewrite the expressions? Should it be like, both case of addition together, subtraction together and so on? – Grimson Oct 23 '16 at 15:25
  • You reshape the tree so instead of `variable '+=' exp` you get `variable '=' variable '+' exp`, that's a *lowering* operation, which is easily done with a visitor. I'd go through an intermediate AST step for lowering, as manipulating ANTLR's CST directly is less than convenient. See [my answer here](http://stackoverflow.com/questions/29971097/how-to-create-ast-with-antlr4/29996191#29996191) for an example of how to build an AST from the CST. You can even do it directly at the AST genetarion step, avoiding the need for dedicated operation/assignation nodes. – Lucas Trzesniewski Oct 23 '16 at 22:44
  • that's quite informative. Thanks a ton! – Grimson Oct 25 '16 at 06:38

0 Answers0