Search code examples
bisonyacclex

$1 of nonterminal has no declared type


%{
    #include<stdio.h>
%}

%start INPUT
%union {int num}
%token <num> val
%type <num>SUM

%%
INPUT: SUM

SUM: '('SUM '+' SUM')'  {$$ = $1 + $2}
    | val               {$$ = $1}

%%

int main(){
    return yyparse();
}

I am trying to make a parser. Although I declare the type for SUM nonterminal, it gives me the warning:

error: $1 of ‘SUM’ has no declared type
 SUM: '('SUM '+' SUM')'  {$$ = $1 + $2}

How can I solve this problem?


Solution

  • SUM: '('SUM '+' SUM')'  {$$ = $1 + $2}
    

    Here $1 refers to '(' and $2 refers to SUM. So when bsion complains that $1 has no declared type, that means that the '(' token has no declared type, which is true.

    Of course you don't want to add the '(' token to anything, you want to add the two sums. For that you should add $2 and $4.

    To avoid these kind of indexing mistakes, you could also consider using named references like this:

    SUM: '(' SUM[left] '+' SUM[right] ')'  { $$ = $left + $right; }