comparison lab2/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 /* lab2/parser.mly */
2 /* Copyright (c) 2017 J. M. Spivey */
3
4 %{
5 open Keiko
6 open Dict
7 open Tree
8 %}
9
10 %token <Dict.ident> IDENT
11 %token <Keiko.op> MULOP ADDOP RELOP MONOP
12 %token <int> NUMBER BOOLCONST
13
14 /* punctuation */
15 %token SEMI DOT COLON LPAR RPAR COMMA
16 %token EQUAL MINUS ASSIGN EOF BADTOK
17 %token SUB BUS
18
19 /* keywords */
20 %token BEGIN DO ELSE END IF
21 %token THEN VAR WHILE PRINT NEWLINE
22 %token ARRAY OF
23 %token INTEGER BOOLEAN
24
25 %type <Tree.program> program
26
27 %start program
28
29 %%
30
31 program :
32 decls BEGIN stmts END DOT { Program ($1, $3) } ;
33
34 decls :
35 /* empty */ { [] }
36 | decl decls { $1 :: $2 }
37
38 decl :
39 VAR name_list COLON typexp SEMI { Decl ($2, $4) } ;
40
41 name_list :
42 name { [$1] }
43 | name COMMA name_list { $1 :: $3 } ;
44
45 typexp :
46 INTEGER { Integer }
47 | BOOLEAN { Boolean }
48 | ARRAY NUMBER OF typexp { Array ($2, $4) } ;
49
50 stmts :
51 stmt_list { seq $1 } ;
52
53 stmt_list :
54 stmt { [$1] }
55 | stmt SEMI stmt_list { $1 :: $3 } ;
56
57 stmt :
58 /* empty */ { Skip }
59 | variable ASSIGN expr { Assign ($1, $3) }
60 | PRINT expr { Print $2 }
61 | NEWLINE { Newline }
62 | IF expr THEN stmts END { IfStmt ($2, $4, Skip) }
63 | IF expr THEN stmts ELSE stmts END { IfStmt ($2, $4, $6) }
64 | WHILE expr DO stmts END { WhileStmt ($2, $4) } ;
65
66 expr :
67 simple { $1 }
68 | expr RELOP simple { makeExpr (Binop ($2, $1, $3)) }
69 | expr EQUAL simple { makeExpr (Binop (Eq, $1, $3)) } ;
70
71 simple :
72 term { $1 }
73 | simple ADDOP term { makeExpr (Binop ($2, $1, $3)) }
74 | simple MINUS term { makeExpr (Binop (Minus, $1, $3)) } ;
75
76 term :
77 factor { $1 }
78 | term MULOP factor { makeExpr (Binop ($2, $1, $3)) }
79
80 factor :
81 variable { $1 }
82 | NUMBER { makeExpr (Constant ($1, Integer)) }
83 | BOOLCONST { makeExpr (Constant ($1, Boolean)) }
84 | MONOP factor { makeExpr (Monop ($1, $2)) }
85 | MINUS factor { makeExpr (Monop (Uminus, $2)) }
86 | LPAR expr RPAR { $2 } ;
87
88 variable :
89 name { makeExpr (Variable $1) }
90 | variable SUB expr BUS { makeExpr (Sub ($1, $3)) } ;
91
92 name :
93 IDENT { makeName $1 !Lexer.lineno } ;