Search code examples
antlrparser-generator

How to add attribute to ANTLR generated C parser?


I'm using ANTLR generated c parser in my C++ program and I wish to use my helper class in parser to write something like the following:

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

Where parserHelper is my C++ helper object. But I'm stuck with passing this helper to the C parser. In object oriented languages the simple way is to use base parser class. It is not possible in C. The only solution I came for now is to define global variable in @members section and initialize it before parsing:

@members
{
    ParserHelper* parserHelper;
}

For some reasons this is inconvenient for me. Isn't there a way to put this variable into C parser structure generated by ANTLR?


Solution

  • One possible solution is to use ANTLR named scopes instead of a global member section.

    The following implementation should correspond to what you are looking for:

    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);
        }
    ;