【问题标题】:How to add attribute to ANTLR generated C parser?如何向 ANTLR 生成的 C 解析器添加属性?
【发布时间】:2011-10-24 15:33:43
【问题描述】:

我在我的 C++ 程序中使用 ANTLR 生成的 c 解析器,我希望在解析器中使用我的帮助程序类来编写如下内容:

constant_declaration 
:   'const' type_specifier ID ('[' constant_expression ']')? '=' initializer
    {
        parserHelper->addConstant($type_specifier.text, $ID.text);
    }
;

parserHelper 是我的 C++ 辅助对象。但我坚持将这个助手传递给 C 解析器。在面向对象的语言中,简单的方法是使用基本解析器类。这在 C 中是不可能的。我现在唯一的解决方案是在 @members 部分定义全局变量并在解析之前对其进行初始化:

@members
{
    ParserHelper* parserHelper;
}

由于某些原因,这对我来说很不方便。有没有办法把这个变量放入ANTLR生成的C解析器结构中?

【问题讨论】:

    标签: antlr parser-generator


    【解决方案1】:

    一种可能的解决方案是使用 ANTLR 命名范围而不是全局成员部分。

    以下实现应该与您要查找的内容相对应:

    scope GlobalScope
    {
        ParserHelper* parserHelper;
    }
    
    rootRule
    scope GlobalScope
    @init {
      // Initialize the scope attributes
      // Somehow retrieve or create a PointerHelper (you can eventually pass it by an argument of the rootRule)
      $GlobalScope::parserHelper = ...;
    }
    :
    ...
    ;
    
    constant_declaration 
    :   'const' type_specifier ID ('[' constant_expression ']')? '=' initializer
        {
            $GlobalScope::parserHelper->addConstant($type_specifier.text, $ID.text);
        }
    ;
    

    【讨论】:

    • 谢谢,将助手添加到全局范围并将其作为参数传递给规则正是我所寻找的。​​span>
    猜你喜欢
    • 1970-01-01
    • 2012-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 2013-03-01
    • 2010-10-15
    • 1970-01-01
    相关资源
    最近更新 更多