Is it possible to return a AST built using Bison without using a global variable?

StackOverflow https://stackoverflow.com/questions/21502425

  •  05-10-2022
  •  | 
  •  

Question

I have an AST ( Abstract Syntax Tree), for a grammer,built using Flex/Bison. Currently, I access the data structure using a global variable.

parser.y

%{
      mynamespace::AST * ast;
%}

%%
PARSER
%%

I currently build the tree and use it in the following way:

A.hpp

#include "ast.hpp"

extern mynamespace::AST * ast;

namespace mynamespace{

extern "C" int yyparse();
extern "C" FILE * yyin;
MyClass A 
{
  void readGrammer( FILE * file)
  {
    yyin = file;
    do{
      yyparse();
    }while(!feof(file))
  }
  void method1()
  {
    //do something with the ast
  }
};
}
  1. Is there a way of making ast a data member of my class and not depend on the global variable ?
  2. Also, is it possible to hide Bison/FLex code from the user ?

Thank you for your time and help.

Was it helpful?

Solution

1. Is there a way of making ast a data member of my class and not depend on the global variable ?

You can use the %parse-param to add one (or more) parameters to the yyparse prototype. In particular, you could pass a pointer to yyparse and fill it in with the parse result. You probably also want to make yyparse "pure" (reentrant). See the sections "The Parser Function" and "A Pure Parser" in the bison manual (also possibly available as info bison)

Alternatively, you can use the ability of bison to generate C++ code, which will effectively do all of that.

2. Also, is it possible to hide Bison/Flex code from the user ?

You can insert namespace { blocks into the generated code, but it requires a bit of manual (or scriptable) post-generation manipulation. (Concatenating the bison and flex output into a single translation unit, for example.) Not at all difficult, though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top