Rohan Prabhu
Rohan Prabhu

Reputation: 7302

A rather unusual bison error

I was teaching myself Bison and headed over to wikipedia for the same and copy-pasted the entire code from the example that was put there [ http://en.wikipedia.org/wiki/GNU_Bison ]. It compiled and works perfect. Then, I OOPed it by adding in a bit of C++. Here's is my new Parser.y file:

%{

#include "TypeParser.h"
#include "ParserParam.h"
#include "addition.h"

%}

%define api.pure

%left '+' TOKEN_PLUS
%left '*' TOKEN_MULTIPLY
%left '-' TOKEN_SUBTRACT
%left '/' TOKEN_DIVIDE
%left '^' TOKEN_EXP

%token TOKEN_LPAREN
%token TOKEN_RPAREN
%token TOKEN_PLUS
%token TOKEN_MULTIPLY

%token <value> TOKEN_NUMBER

%type <expression> expr

%%

input: 
        expr { ((SParserParam*)data)->expression = $1; }
        ;

expr:
      expr TOKEN_PLUS expr { $$ = new Addition($1, $2); }
    | expr TOKEN_MULTIPLY expr { $$ = new Multiplication($1, $2); }
    | expr TOKEN_SUBTRACT expr { $$ = new Addition($1, $2); }
    | expr TOKEN_DIVIDE expr { $$ = new Multiplication($1, $2); }
    | expr TOKEN_EXP expr  { $$ = new Addition($1, $2); }
    | TOKEN_LPAREN expr TOKEN_RPAREN { $$ = $2; }
    | TOKEN_NUMBER { $$ = new Value($1); }
;

%%

But then I keep getting the following errors:

Parser.y:33.52-53: $2 of `expr' has no declared type
Parser.y:34.62-63: $2 of `expr' has no declared type
Parser.y:35.56-57: $2 of `expr' has no declared type
Parser.y:36.60-61: $2 of `expr' has no declared type
Parser.y:37.52-53: $2 of `expr' has no declared type

How do I resolve it? I mean, what have I changed that is causing this? I haven't changed anything from the wikipedia code, the %type% declaration is still there [The union has the same members, with type changed from SExpression to Expression.]. All classes i.e. Addition, Expression, Multiplication are defined and declared. I don't think that is what is causing the problem here, but just saying.

And why exactly does it have a problem only with $2. Even $1 is of type expr, then why do I not get any errors for $1?

Any help is appreciated...

Upvotes: 3

Views: 457

Answers (1)

user786653
user786653

Reputation: 30460

In the rule expr TOKEN_PLUS expr $1 is the first expression, $2 is TOKEN_PLUS, and $3 is the second expression. See the bison manual.

So the semantic action needs to change from your { $$ = new Addition($1, $2); } to { $$ = new Addition($1, $3); }.

Upvotes: 3

Related Questions