在 Antlr4 中使用 text 属性时如何保留空格 [英] How to preserve whitespace when we use text attribute in Antlr4

查看:40
本文介绍了在 Antlr4 中使用 text 属性时如何保留空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在调用token的text属性时保留空格,有什么办法吗?这是情况:我们有以下代码

I want to keep white space when I call text attribute of token, is there any way to do it? 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 transform it into:

if (!(L>40){

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

Antlr 中的规则是:

The rule in Antlr is that:

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

但结果看起来像:

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

原因是 $stmt 中的空格被删除了.我想知道是否有办法保留这些空白
非常感谢

The reason is that the white space in $stmt was removed. I was wondering if there is anyway to keep these white space
Thank you so much

更新:如果我添加

SPACE: [ ] -> channel(HIDDEN);

空格将被保留,结果如下所示,标记之间有很多空格:

The space will be preserved, and the result would look like below, many spaces between tokens:

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

推荐答案

这是我用于此目的的 C# 扩展方法:

This is the C# extension method I use for exactly 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));
}

由于您使用的是 Java,因此您必须对其进行翻译,但它应该很简单 - API 是相同的.

Since you're using java, you'll have to translate it, but it should be straightforward - 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.

这篇关于在 Antlr4 中使用 text 属性时如何保留空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆