How to preserve spaces when using text attribute in Antlr4

I want to preserve the space when I call the text attribute of the token, is there a way to do this? Here is the situation: We have the following code

IF L > 40 THEN;

ELSE

  IF A = 20 THEN
      PUT "HELLO";

      

In this case, I want to convert it to:

if (!(L>40){

      if (A=20)
          put "hello";
}

      

The rule in Antlr is as follows:

stmt_if_block: IF expr
               THEN x=stmt
               (ELSE y=stmt)?
               {
                 if ($x.text.equalsIgnoreCase(";"))
                 {
                   WriteLn("if(!(" + $expr.text +")){");
                   WriteLn($stmt.text);
                   Writeln("}");
                 }
               }

      

But the result looks like this:

if(!(L>40))
{
   ifA=20put"hello";
}

      

The reason is that the white space in has $stmt

been removed. I was wondering if these spaces are preserved anyway
Thank you so much.

Update: if I add

SPACE: [ ] -> channel(HIDDEN);

      

Space will be saved and the result looks like below, lots of spaces between tokens:

 IF SUBSTR(WNAME3,M-1,1) = ')'             THEN                                        M = L;                                  ELSE                                        M = L - 1;

      

+3


source to share


1 answer


This is the C # extension method I use for this purpose:

public static string GetFullText(this ParserRuleContext context)
{
    if (context.Start == null || context.Stop == null || context.Start.StartIndex < 0 || context.Stop.StopIndex < 0)
        return context.GetText(); // Fallback

    return context.Start.InputStream.GetText(Interval.Of(context.Start.StartIndex, context.Stop.StopIndex));
}

      



Since you are using java you will have to translate it, but it should be simple - the API is the same.

Explanation: Get the first token, get the last token and get the text from the input stream between the first char of the first token and the last char of the last token.

+5


source







All Articles