(* code to be copied in the scanner module *) (* *) %{ open Types %} (* tokens *) %token MAIN DEF WITH INPUT OUTPUT AS SKIP ASSIGNMENT SEQUENCE IF THEN ELSE WHILE %token FOR DO COMMA LEFTPAR RIGHTPAR %token PLUS MINUS TIMES DIVISION MODULO POWER POWERMOD RAND %token BAND BOR BNOT BCMP BCMPLESS BCMPLESSEQ BCMPGREATER BCMPGREATEREQ %token BOOL %token INT %token VARIABLE %token EOF %type cexpp %type bexpp %type aexpp %type prg (* start nonterminal *) %start prg (* associativity in order of precedence *) %left lowest %left SEQUENCE %left ELSE %left PLUS MINUS BOR BAND %left BNOT %left DIVISION %left MODULO %left TIMES %right POWER %left DO %% (* grammar *) prg: | DEF; MAIN; WITH; INPUT; a = VARIABLE; OUTPUT; b = VARIABLE; AS; t = cexpp; EOF {Main (a, b, t)} // def main with input a output b as t cexpp: | SKIP {Skip} // skip | a = VARIABLE; ASSIGNMENT; body = aexpp {Assignment (a, body)} // a := body | t1 = cexpp; SEQUENCE; t2 = cexpp %prec lowest {Sequence (t1, t2)} // t1; t2 | t = cexpp; SEQUENCE {t} // t; | IF; guard = bexpp; THEN; body1 = cexpp; ELSE; body2 = cexpp {If (guard, body1, body2)} // if ... then ... else ... | WHILE; guard = bexpp; DO; body = cexpp; {While (guard, body)} // while ... do ... | FOR; LEFTPAR; ass = cexpp; COMMA; guard = bexpp; COMMA; iter = cexpp; RIGHTPAR; DO; body = cexpp; {For (ass, guard, iter, body)} // for (..., ..., ...) do ... | LEFTPAR; t = cexpp; RIGHTPAR {t} // (...) bexpp: | b = BOOL {Boolean (b)} // true, false | b1 = bexpp; BAND; b2 = bexpp {BAnd (b1, b2)} // && | b1 = bexpp; BOR; b2 = bexpp {BOr (b1, b2)} // || | BNOT; b = bexpp {BNot (b)} // not | a1 = aexpp; BCMP; a2 = aexpp {BCmp (a1, a2)} // == | a1 = aexpp; BCMPLESS; a2 = aexpp {BCmpLess (a1, a2)} // < | a1 = aexpp; BCMPLESSEQ; a2 = aexpp {BCmpLessEq (a1, a2)} // <= | a1 = aexpp; BCMPGREATER; a2 = aexpp {BCmpGreater (a1, a2)} // > | a1 = aexpp; BCMPGREATEREQ; a2 = aexpp {BCmpGreaterEq (a1, a2)} // >= | LEFTPAR; b = bexpp; RIGHTPAR {b} // (b) aexpp: | a = VARIABLE {Variable (a)} | i = INT {Integer (i)} | t1 = aexpp; PLUS; t2 = aexpp {Plus (t1, t2)} // + | t1 = aexpp; MINUS; t2 = aexpp {Minus (t1, t2)} // - | MINUS; i = INT {Integer (-i)} | t1 = aexpp; TIMES; t2 = aexpp {Times (t1, t2)} // * | t1 = aexpp; DIVISION; t2 = aexpp {Division (t1, t2)} // / | t1 = aexpp; MODULO; t2 = aexpp {Modulo (t1, t2)} // % | t1 = aexpp; POWER; t2 = aexpp {Power (t1, t2)} // ^ | POWERMOD; LEFTPAR; t1 = aexpp; COMMA; t2 = aexpp; COMMA; t3 = aexpp; RIGHTPAR {PowerMod (t1, t2, t3)} // powmod(..., ..., ...) | RAND; LEFTPAR; t = aexpp; RIGHTPAR {Rand (t)} // rand() | LEFTPAR; a = aexpp; RIGHTPAR {a} // (a)