comparison lab3/parser.mly @ 0:bfdcc3820b32

Basis
author Mike Spivey <mike@cs.ox.ac.uk>
date Thu, 05 Oct 2017 08:04:15 +0100
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:bfdcc3820b32
1 /* lab3/parser.mly */
2 /* Copyright (c) 2017 J. M. Spivey */
3
4 %token<string> IDENT
5 %token<int> NUMBER
6 %token<Keiko.op> MONOP MULOP ADDOP RELOP
7 %token MINUS LPAR RPAR COMMA SEMI DOT ASSIGN EOF BADTOK
8 %token BEGIN END VAR PRINT IF THEN ELSE WHILE DO PROC RETURN NEWLINE
9
10 %start program
11 %type<Tree.program> program
12
13 %{
14 open Keiko
15 open Tree
16 %}
17
18 %%
19
20 program :
21 block DOT { Program $1 } ;
22
23 block :
24 var_decl proc_decls BEGIN stmts END { Block ($1, $2, $4) } ;
25
26 var_decl :
27 /* empty */ { [] }
28 | VAR ident_list SEMI { $2 } ;
29
30 ident_list :
31 IDENT { [$1] }
32 | IDENT COMMA ident_list { $1::$3 } ;
33
34 proc_decls :
35 /* empty */ { [] }
36 | proc_decl proc_decls { $1::$2 } ;
37
38 proc_decl :
39 PROC name formals SEMI block SEMI { Proc ($2, $3, $5) } ;
40
41 formals :
42 LPAR RPAR { [] } ;
43 | LPAR ident_list RPAR { $2 } ;
44
45 stmts :
46 stmt_list { seq $1 } ;
47
48 stmt_list :
49 stmt { [$1] }
50 | stmt SEMI stmt_list { $1::$3 } ;
51
52 stmt :
53 /* empty */ { Skip }
54 | name ASSIGN expr { Assign ($1, $3) }
55 | RETURN expr { Return $2 }
56 | IF expr THEN stmts END { IfStmt ($2, $4, Skip) }
57 | IF expr THEN stmts ELSE stmts END { IfStmt ($2, $4, $6) }
58 | WHILE expr DO stmts END { WhileStmt ($2, $4) }
59 | PRINT expr { Print $2 }
60 | NEWLINE { Newline } ;
61
62 actuals :
63 LPAR RPAR { [] }
64 | LPAR expr_list RPAR { $2 } ;
65
66 expr_list :
67 expr { [$1] }
68 | expr COMMA expr_list { $1::$3 } ;
69
70 expr :
71 simple { $1 }
72 | expr RELOP simple { Binop ($2, $1, $3) } ;
73
74 simple :
75 term { $1 }
76 | simple ADDOP term { Binop ($2, $1, $3) }
77 | simple MINUS term { Binop (Minus, $1, $3) } ;
78
79 term :
80 factor { $1 }
81 | term MULOP factor { Binop ($2, $1, $3) } ;
82
83 factor :
84 NUMBER { Constant $1 }
85 | name { Variable $1 }
86 | name actuals { Call ($1, $2) }
87 | MONOP factor { Monop ($1, $2) }
88 | MINUS factor { Monop (Uminus, $2) }
89 | LPAR expr RPAR { $2 } ;
90
91 name :
92 IDENT { makeName $1 !Lexer.lineno } ;