Files
lci/lib/miniImp/Parser.mly

86 lines
3.0 KiB
OCaml

(* code to be copied in the scanner module *)
(*
*)
%{
open Types
%}
(* tokens *)
%token MAIN SKIP ASSIGNMENT SEQUENCE IF ELSE WHILE FOR DO COMMA
%token LEFTGPAR RIGHTGPAR
%token <bool> BOOL
%token BAND BOR BNOT BCMP BCMPLESS BCMPLESSEQ BCMPGREATER BCMPGREATEREQ
%token <string> VARIABLE
%token <int> INT
%token LEFTPAR RIGHTPAR
%token PLUS MINUS TIMES DIVISION MODULO POWER POWERMOD RAND
%token EOF
%type <c_exp> cexpp
%type <b_exp> bexpp
%type <a_exp> aexpp
%type <p_exp> prg
(* start nonterminal *)
%start prg
(* associativity in order of precedence *)
%left twoseq
%left SEQUENCE
%left ELSE
%left PLUS MINUS BOR BAND
%left BNOT
%left DIVISION
%left MODULO
%left TIMES
%left POWER
%%
(* grammar *)
prg:
| MAIN; a = VARIABLE; b = VARIABLE; LEFTGPAR; t = cexpp; RIGHTGPAR; EOF
{Main (a, b, t)} // main a b {...}
cexpp:
| SKIP {Skip} // skip
| a = VARIABLE; ASSIGNMENT; body = aexpp
{Assignment (a, body)} // a := ...
| t1 = cexpp; SEQUENCE; t2 = cexpp %prec twoseq
{Sequence (t1, t2)} // ...; ...
| t = cexpp; SEQUENCE {t} // ...;
| IF; LEFTPAR; guard = bexpp; RIGHTPAR; body1 = cexpp; ELSE; body2 = cexpp
{If (guard, body1, body2)} // if (...) ... else ...
| WHILE; guard = bexpp; DO; LEFTGPAR; body = cexpp; RIGHTGPAR
{While (guard, body)} // while ... do {...}
| FOR; LEFTPAR; ass = cexpp; COMMA; guard = bexpp; COMMA; iter = cexpp; RIGHTPAR;
DO; LEFTGPAR; body = cexpp; RIGHTGPAR
{For (ass, guard, iter, body)} // for (..., ..., ...) do {...}
| LEFTGPAR; t = cexpp; RIGHTGPAR {t} // {...}
bexpp:
| b = BOOL {Boolean (b)}
| b1 = bexpp; BAND; b2 = bexpp {BAnd (b1, b2)}
| b1 = bexpp; BOR; b2 = bexpp {BOr (b1, b2)}
| BNOT; b = bexpp {BNot (b)}
| 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}
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)}
| LEFTPAR; a = aexpp; RIGHTPAR {a}