Search code examples
c++parsingcompiler-constructionabstract-syntax-treebisonc++

bisonc++ inheritance with polymorphic


I'm trying to construct an AST from a bison grammar. Bison generates the parser correctly but when I try to parse an example code with some math operations the following error its printed:

[Fatal] calling `.get<Tag__::EXPR>()', but Tag INT is encountered.

After debugging I notice that the issue is in the expr non-terminal with the following production:

expr:
      ...
    | operator
      {
         $$ = $1;
      }

And operator has the following production itself:

operator:
   ...
| INTEGER
  {
    $$ = new ast::expression::IntASTNode(std::stoi(d_scanner.matched()));
  }

I'm using polymorphic semantic types, expr and operator are tagged with EXPR that respond to ExprASTNode type witch is the base class for IntASTNode with the tag INT. I'm guessing that bison is getting the type from the tag and checking the tags before making any cast. Is there any way that I can resolve this?


Solution

  • If you substitute the assignment by this:

    operator:
         ...
            | INTEGER
              {
                $$(ast::expression::IntASTNode(std::stoi(d_scanner.matched())));
              }
    

    then bisonc++ makes a static_cast between the the $$'s semantic value and the one from the $$(expr). Further information in the bisonc++ manual.