Thursday, March 3, 2011

ANTLR v3 C# namespaces

Hopefully this is a really quick one ;) I have written a lexer / parser specification in ANTLR3, and am targeting the CSharp2 target. The generated code works correctly, but I can't get ANTLR to put the C# output into a namespace.

The relevant section of the Grammar file is as follows:

grammar MyGrammar;

options
{
    language = CSharp2;
    output = AST;
    ASTLabelType = CommonTree;
}

To generate the correct namespace, I have tried:

@namespace { MyNamespace }

and

@lexer::namespace { MyNamespace }
@parser::namespace { MyNamespace }

but both of these generate errors, claiming that the file has no rules.

Any help is appreciated.

From stackoverflow
  • I use this for a combined lexer and parser (and it generates the namespace correctly):

    grammar Test;
    
    options
    {
        language=CSharp2;
    }
    
    @lexer::namespace {
        My.Name.Space
    }
    
    @parser::namespace {
        My.Name.Space
    }
    
    
    DIGIT   : '0'..'9';
    
    simple  :  DIGIT EOF;
    

    So i wonder why your version didn't work - maybe you want to try this simple example and see if it works for you.

  • It seems that the @namespace directive needs to be placed AFTER the tokens{} block. All good now...

0 comments:

Post a Comment