[antlr-interest] Integrating Antlr-3.0b5 with VS2005 C# projects

Benoit Miller fulg at iname.com
Fri Jan 5 08:03:22 PST 2007


Hello,

I am evaluating antlr3.0b5 for a C# project under VS2005. Unfortunately, 
when using C#, there is no support for custom build tools (there is when 
using C++).

Initially I was using a pre-build step to have antlr generate the code, 
however this step is performed /after/ the source dependencies have been 
calculated, so your executable lags behind your source (ie, every 
grammar change needs two recompiles to get in). Clearly that's no way to 
work!

After getting over the fact that Microsoft requires one to hand-edit the 
project file to add custom build commands (!!), here's what I came up with:

   <ItemGroup>
     <Antlr3 Include="SimpleCalc.g">
       <OutputFiles>
         SimpleCalcLexer.cs;SimpleCalcParser.cs
       </OutputFiles>
     </Antlr3>
   </ItemGroup>

   <Target Name="GenerateAntlrCode"
           Inputs="@(Antlr3)"
           Outputs="%(Antlr3.OutputFiles)">
     <Exec Command="java org.antlr.Tool -message-format vstudio @(Antlr3)"/>
   </Target>

   <PropertyGroup>
     <CompileDependsOn>
       GenerateAntlrCode;$(CompileDependsOn)
     </CompileDependsOn>
   </PropertyGroup>

(Excuse the odd XML formatting, I tried to make it list-friendly.)

Unload your project, edit your .csproj, and paste this at the end (still 
inside the <project> tag). Change according to taste.

In order to have VS2005/MSBuild detect errors (and enable 
double-clicking on error messages from the IDE), I made a simple VS-like 
message formatter, vstudio.stg:

   group vstudio;
   location(file, line, column) ::= "<file>(<line>,<column>):"
   message(id, text) ::= "<id>: <text>"
   report(location, message, type) ::= "<location> <type> <message>"
   wantsSingleLineMessage() ::= "false"

Until an official format file makes it in 3.0b6, add vstudio.stg to your 
antlr-3.0b5.jar file in org/antlr/tool/templates/messages/formats, next 
to the existing antlr.stg and gnu.stg.

It's not perfect because sometimes antlr gives an empty location field, 
or non-translated locations, such as this example:

   SimpleCalc.g(39,7): error 100: syntax error: antlr: 
SimpleCalc.g:39:7: unexpected token: foo

Also, antlr can generate output files even though the grammar has errors 
in it, so further dependency checks fail and the grammar won't be 
recompiled until changed. I think no output should be produced on 
errors... (otherwise, perhaps the error should have been a warning? :))

In any case, this may be obvious to some, but I wasted an evening 
figuring this out so I thought I'd contribute. Perhaps it can go on the 
wiki, as I could not find this kind of info anywhere.

Hope this helps,
Ben.


More information about the antlr-interest mailing list