Sourav Kannantha B
Sourav Kannantha B

Reputation: 3299

Bison - why this is producing syntax error for all inputs

I have written a simple grammer:


expr:
    INT { $$ = intc($1); }
    | FLOAT { $$ = floatc($1); }
    | STR { $$ = strc($1); }
    | ID { $$ = id($1, false); }
    | ID '=' expr { $$ = operate('=', id($1, false), $3); }
    | VAR ID { $$ = id($2, true); }
    | VAR ID '=' expr { $$ = operate('=', id($2, true), $4); }
    | '-' expr %prec NEG { $$ = operate(NEG, $2, NULL); }
    | expr '+' expr { $$ = operate('+', $1, $3); }
    | expr '-' expr { $$ = operate('-', $1, $3); }
    | expr '*' expr { $$ = operate('*', $1, $3); }
    | expr '/' expr { $$ = operate('/', $1, $3); }
    | '(' expr ')' { $$ = $2; }
    ;

stmt:
    ';' {}
    | expr ';' { compile($1); }
    ;

prog:
    prog stmt {}
    |
    ;

where INT, FLOAT and STR are lexical tokens corresponding integer, floating-point and string literals respectively, ID is an valid identifier and VAR is a declarator for first use of an identifier.

But this bison file is showing these warnings:

lang.y: warning: 2 nonterminals useless in grammar [-Wother]
lang.y: warning: 4 rules useless in grammar [-Wother]
lang.y:73.1-4: warning: nonterminal useless in grammar: stmt [-Wother]
 stmt:
 ^^^^
lang.y:78.1-4: warning: nonterminal useless in grammar: prog [-Wother]
 prog:
 ^^^^
lang.y:74.9-14: warning: rule useless in grammar [-Wother]
        ';' {}
         ^^^^^^
lang.y:75.11-35: warning: rule useless in grammar [-Wother]
        | expr ';' { compile($1); }
           ^^^^^^^^^^^^^^^^^^^^^^^^^
lang.y:79.9-20: warning: rule useless in grammar [-Wother]
        prog stmt {}
         ^^^^^^^^^^^^
lang.y:80.10: warning: rule useless in grammar [-Wother]
        |
          ^
lang.y: warning: 19 shift/reduce conflicts [-Wconflicts-sr]

It also produces syntax error, unexpected ';' error whenever I input a statement ending with semicolon. If I do not use a semicolon in first line, then when I input second line, it produces syntax error, unexpected <FIRST_TOKEN_IN_SECOND_LINE>.

So someone please help me, pointing where I gone wrong.

Upvotes: 0

Views: 90

Answers (1)

sepp2k
sepp2k

Reputation: 370162

Parsing starts with the start non-terminal of the grammar. If you don't set a start rule using %start, the first non-terminal defined in the grammar will be your start rule.

So in your grammar the start non-terminal will be expr. So your inputs produce syntax errors because they do not match expr and your other non-terminals are useless because they're never used by expr.

If you want parsing to start with prog, you'll either need to add the directive %start prog or move prog to the beginning of the grammar.

Upvotes: 1

Related Questions