如何指定 ANTLR 中某个 token 出现的确切次数?

发布于 2024-07-09 03:27:38 字数 419 浏览 8 评论 0原文

我必须定义一个文件的语法,如下所示。

//示例文件
名称计数 = 4
姓名=a
名称 = b
名称 = c
名称 = d
// 文件结束

现在我可以为 NameCountName 定义标记。 但我必须定义文件结构,包括令牌 Name 实例的有效数量,这是 NameCount 之后的值。 我将值解析并转换为整数,并将其存储在语法全局范围内的变量中(例如在变量 nc 中)。

如何在语法中定义 Name 应精确重复 nc 次?

I have to define the grammar of a file like the one shown below.

//Sample file
NameCount = 4
Name = a
Name = b
Name = c
Name = d
//End of file

Now I am able to define tokens for NameCount and Name. But i have to define the file structure including the valid number of instances of token Name , which is the value after NameCount. I have the value parsed and converted into an integer and stored in a variable at global scope of the grammar (say in variable nc).

How to define in grammar that Name should repeat exactly nc times?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

思慕 2024-07-16 03:27:39

这不能用语法本身来表达。 如果数字是固定的,您可以表示预期令牌的数量。 但令牌流会根据值而变化。 您可以做的是将其包含到词法分析器/解析器组合中。 但是您不能仅通过简单的语法来创建此构造。 你可能想要类似的东西

grammar test;

@members {
  private int count = 0;
  private int names = 0;
}

file
    : count (name)+
      {
        if (count != names) throw new Exception("");
      }
    ;

count
    : 'NameCount' EQ Number
      {
        count = Integer.parseInt($Number.text);
      }
    ;

name
    : 'Name' EQ Value
      {
        names++;
      }
...

This cannot be expressed in the grammar itself. If the number was fix you could express the number of expected tokens. But the token stream changes based on the value. What you can do is to include this into the lexer/parser combination. But you cannot create this construct by just the plain grammar syntax. You probably want something along the lines of

grammar test;

@members {
  private int count = 0;
  private int names = 0;
}

file
    : count (name)+
      {
        if (count != names) throw new Exception("");
      }
    ;

count
    : 'NameCount' EQ Number
      {
        count = Integer.parseInt($Number.text);
      }
    ;

name
    : 'Name' EQ Value
      {
        names++;
      }
...
走野 2024-07-16 03:27:39

我不确定这是上下文无关语法。 如果不是,您就无法告诉 ANTLR 解析该语言。

I'm not sure this is a context free grammar. If it isn't, you cannot tell ANTLR to parse the language.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文