2
votes

I have created a simple .g4 (Antlr4) grammar & lexer file.

It generates my lexer/parser code fine. But after adding some custom code that require Linq extensions I now need to get the custom statement "using System.Linq;" injected at the top of my generated lexer code file.

I am aware that there are some options for injecting code (from the .g4 file), e.g.

@lexer::members {
     ... {custom lexer code goes here}

Can someone please point me to the correct (.g4) syntax that will render the necessary "using" statements in the rendered lexer/parser.

UPDATE: LexLi made a good point .. why do I need that? I'm supposed to write my code in visitor or listener. Answer to that: I am trying to implement INDENT and DEDENT tokens in C# (analogue to the the Java code posted here under "ANTLR4": ANTLR What is simpliest way to realize python like indent-depending grammar?

Thanks!

1
Why do you need that? You are supposed to write your code in visitor or listener, and no more "actions" in your grammar file like ANTLR 2 or 3 (though they are still supported).Lex Li

1 Answers

3
votes

You can control what is written to your file in the classic way,

@parser::header
{
#pragma warning disable 3001, 3003, 3005, 3009, 1591 
}

@lexer::header
{
#pragma warning disable 3001, 3003, 3005, 3009, 1591 
}

@parser::namespace { Lextm.Namespace }
@lexer::namespace { Lextm.Namespace }

@parser::footer
{
#pragma warning restore 3001, 3003, 3005, 3009, 1591 
}

@lexer::footer
{
#pragma warning restore 3001, 3003, 3005, 3009, 1591 
}

So in your case, add the using statements to header.