comparison lab1/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 /* lab1/parser.mly */
2 /* Copyright (c) 2017 J. M. Spivey */
3
4 %{
5 open Keiko
6 open Tree
7 %}
8
9 %token <Tree.ident> IDENT
10 %token <Keiko.op> MONOP MULOP ADDOP RELOP
11 %token <int> NUMBER
12
13 /* punctuation and keywords */
14 %token SEMI DOT COLON LPAR RPAR COMMA MINUS VBAR
15 %token ASSIGN EOF BADTOK
16 %token BEGIN DO ELSE END IF THEN WHILE PRINT NEWLINE
17
18 %type <Tree.program> program
19
20 %start program
21
22 %%
23
24 program :
25 BEGIN stmts END DOT { Program $2 } ;
26
27 stmts :
28 stmt_list { seq $1 } ;
29
30 stmt_list :
31 stmt { [$1] }
32 | stmt SEMI stmt_list { $1 :: $3 } ;
33
34 stmt :
35 /* empty */ { Skip }
36 | name ASSIGN expr { Assign ($1, $3) }
37 | PRINT expr { Print $2 }
38 | NEWLINE { Newline }
39 | IF expr THEN stmts END { IfStmt ($2, $4, Skip) }
40 | IF expr THEN stmts ELSE stmts END { IfStmt ($2, $4, $6) }
41 | WHILE expr DO stmts END { WhileStmt ($2, $4) } ;
42
43 expr :
44 simple { $1 }
45 | expr RELOP simple { Binop ($2, $1, $3) } ;
46
47 simple :
48 term { $1 }
49 | simple ADDOP term { Binop ($2, $1, $3) }
50 | simple MINUS term { Binop (Minus, $1, $3) } ;
51
52 term :
53 factor { $1 }
54 | term MULOP factor { Binop ($2, $1, $3) } ;
55
56 factor :
57 name { Variable $1 }
58 | NUMBER { Constant $1 }
59 | MONOP factor { Monop ($1, $2) }
60 | MINUS factor { Monop (Uminus, $2) }
61 | LPAR expr RPAR { $2 } ;
62
63 name :
64 IDENT { make_name $1 !Lexer.lineno } ;