0
votes

In a yacc+lex program, with these rules (and more) in the yacc file,

stmt    : ';'
        | expr ';'      { /*code*/ }
        | IF '(' expr ')' stmt  { /*code*/ }
        | IF '(' expr ')' stmt ELSE stmt { /*code*/ }
.
.
.
.

If the input is something like:

if(1<2) {return 5;}

being "(1<2)" an expr and "{return 5}" a stmt, it matches. Otherwise, if the input is something like:

if(1<2) {return 5;} else {return 2;}

it doesn't match...

I have tried changing the associativity of ELSE and IF... and it says "syntax error".

EDIT1:

expr is defined as:

expr    : ID   '=' expr { emit(dup); emit2(istore, $1->localvar); }
    | ID   PA  expr { emit2(iload, $1->localvar); emit(iadd); emit(dup); emit2(istore, $1->localvar); }
    | ID   NA  expr { emit2(iload, $1->localvar); emit(isub); emit(dup); emit2(istore, $1->localvar); }
    | ID   TA  expr { emit2(iload, $1->localvar); emit(imul); emit(dup); emit2(istore, $1->localvar); }
    | ID   DA  expr { emit2(iload, $1->localvar); emit(idiv); emit(dup); emit2(istore, $1->localvar); }
    | ID   MA  expr { emit2(iload, $1->localvar); emit(irem); emit(dup); emit2(istore, $1->localvar); }
    | expr EQ  expr { emit3(if_icmpeq, 7); emit(iconst_0); emit3(goto_, 4); emit(iconst_1); }
    | expr NE  expr { emit3(if_icmpne, 7); emit(iconst_0); emit3(goto_, 4); emit(iconst_1); }
    | expr '<' expr { emit3(if_icmplt, 7); emit(iconst_0); emit3(goto_, 4); emit(iconst_1); }
    | expr '>' expr { emit3(if_icmpgt, 7); emit(iconst_0); emit3(goto_, 4); emit(iconst_1); }
    | expr LE  expr { emit3(if_icmple, 7); emit(iconst_0); emit3(goto_, 4); emit(iconst_1); }
    | expr GE  expr { emit3(if_icmpge, 7); emit(iconst_0); emit3(goto_, 4); emit(iconst_1); }
    | expr '+' expr { emit(iadd); }
    | expr '-' expr { emit(isub); }
    | expr '*' expr { emit(imul); }
    | expr '/' expr { emit(idiv); }
    | expr '%' expr { emit(irem); }
    | '(' expr ')'
    | '$' INT8      { emit(aload_1); emit2(bipush, $2); emit(iaload); }
    | ID            { emit2(iload, $1->localvar); }
    | INT8          { emit2(bipush, $1); }
    | INT16         { emit3(sipush, $1); }
    | INT32         { emit2(ldc, constant_pool_add_Integer(&cf, $1)); }
    | FLT       { error("float constant not supported in Pr3"); }
    | STR       { error("string constant not supported in Pr3"); }
    ;
1
How is expr defined?Bob Jarvis - Reinstate Monica
@BobJarvis I've just added the expr definitionDoasy

1 Answers

1
votes

In a yacc script I have the if statement defined as follows:

if_statement : IF  b_expr   
                   statement
               else_part
             ;

else_part    : ELSE
                statement
             | empty
             ;