0
votes

I am trying to add some custom code in my ANTLR4 grammar to do some processing on the tokens before they are handed off. What I am trying to do is strip leading/trailing quotes from the token. I tried converting the answer found here, but get the following error:

Lexer.cs(110,24): error CS0103: The name `getText' does not exist in the current context

Lexer.cs(112,16): error CS0103: The name `setText' does not exist in the current context

I then read on another StackOverflow post that someone had to use $text instead of setText(), but that leads to this error:

error(128): Grammar.g4:105:22: attribute references not allowed in lexer actions: $text

Is there a way to put custom code in an ANTLR4 grammar? Here is the relevant grammar rule:

STRING_LITERAL : '"' (~["\r\n\\])* '"'
                 {
                   var s = $text;
                   s = s.Substring(1, s.Length - 2);
                   $text = s;
                 };

Or likewise with getText() and setText() in the place of $text.

EDIT

I am using ANTLR 4.6.

1

1 Answers

1
votes

I was close. I figured out in C# they use a Text property instead of getText() and setText() method. So the above grammar rule becomes:

STRING_LITERAL : '"' (~["\r\n\\])* '"'
                 {
                   var s = Text;
                   s = s.Substring(1, s.Length - 2);
                   Text = s;
                 };