Search code examples
compiler-constructionbisonflex-lexer

How to make multiple instructions in own compiler in Bison?


I am trying to implement multiple instructions in my compiler. To make it simple I will give only small example. What is working:

expr1;

What doesn't work:

expr1; expr2;

And the gramma looks like this:

%start expression
%%
expression
    : first ';'
    ;
first
    : first '+' second
    | first '-' second
    | second
    ;
second
    : second '*' number
    | second '/' number
    | number
number
    : NUM_INT
    ;

Solution

  • You need a rule that matches multiple statements and you can define that using recursion like this:

    statements
        : statements statement
        | /* empty */
        ;
    

    This matches zero or more statements. If you want to require at least one, you should replace the empty case with statement.