Blog moved to http://www.andrevdm.com/

Sunday 11 August 2013

Upgrading to ANTLR 4 with C#

Upgrading from ANTLR 3.x to ANTLR 4 was pretty painless. Here are the changes I needed to make to get it all working

  1. Get ANTLR 4 from nuget (you will need to allow pre-release versions for now)
  2. Change your ANTLR build script to reference the new ANTLR JAR. The JAR is included in the nuget. This what my build script looks like
        set classpath=C:\xxx\packages\Antlr4\tools\antlr4-csharp-4.1-SNAPSHOT-complete.jar
        java org.antlr.v4.Tool xxx.g4 -Dlanguage=CSharp_v4_0
  3. Rename grammars from .g to .g4
  4. Remove the options block or change it to match your C# version selection
       options
       {
          language=CSharp_v4_0;
       }
  5. Tokens should be comma delimited not semicolon delimited
  6. Always use a $ when referring to parameters, return variables, tokens etc. ANTLR 3.4 did not always enforce this so if you forgot it in a few places you will need to fix them
  7. You can still check if a optional token exists just be sure to use the .ctx. E.g. use this
       if( $i.ctx != null )
  8. You may get errors when using properties on matched tokens. Parentheses will fix this. E.g.
       ($i).Text
  9. Use “-> skip” rather than “{$channel=HIDDEN}”
  10. Use “.*?” rather than “options {greedy=false;}”

Hope this helps someone