sqram
sqram

Reputation: 7201

How to use declared c++ variable inside bison grammar

I am trying to keep an error count in a variable called 'mismatches', in which i declare in the first part of the bison file.

In my bison grammar, i set a value to that variable.

Then in the 3rd part of the bison file, in the main() function i cout its value, and it's 0.

A very modified/cut down version of my bison file:

%{
extern "C" FILE *yyin;
extern int yylineno;
extern int yynerrs;

int yylex();

// Declare 'mismatches'
int mismatches;

%}

%error-verbose


%%

expression:
          expression ADDOP term
          {
                     cout << "Parser is now here. Going to set `mismatches` to 6";
                     mismatches = 6;
          }
          | term
          ;

%%

int  main()
{         
          // Outputs 0
          cout << mismatches;

          yyparse();

          return 1;

}

What should i do so that the variable 'mismatches' can be used in all parts of the bison file?

Upvotes: 1

Views: 3885

Answers (2)

akim
akim

Reputation: 8759

If you want to count syntax errors, an obvious place to insert your counter update is yyerror.

Also, you should not use

%{
int counter;
%}

as you will get as many copies of "counter" as you have files including your header. If you display "counter" from another file, then it's no surprise you display 0, since you display another variable named counter.

Provided you use Bison (and recent enough), you'd rather do something like this:

%code provides
{
  extern int counter;

}
%code
{
  int counter;
}

Alternatively, use %{...%} to declare it (i.e., with extern), and define it (i.e., without extern) after the second %%.

Upvotes: 3

Dan
Dan

Reputation: 13160

I think you want to output the variable after you run the parser, like so

int  main()
{         
      yyparse();
      cout << mismatches;

      return 1;
}

Upvotes: 2

Related Questions