forked from ManuelCPinto/mini-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.mly
More file actions
121 lines (102 loc) · 2.05 KB
/
Copy pathparser.mly
File metadata and controls
121 lines (102 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/* Parser for Mini-Python */
%{
open Ast
%}
%token <Ast.constant> CST
%token <Ast.binop> CMP
%token <string> IDENT
%token DEF IF ELSE RETURN PRINT FOR IN AND OR NOT LAMBDA
%token WHILE
%token EOF
%token LP RP LSQ RSQ COMMA EQUAL COLON BEGIN END NEWLINE
%token PLUS MINUS TIMES DIV MOD
/* priorities and associativities */
%left OR
%left AND
%nonassoc NOT
%nonassoc CMP
%left PLUS MINUS
%left TIMES DIV MOD
%nonassoc unary_minus
%nonassoc LSQ
%start file
%type <Ast.file> file
%%
file:
| NEWLINE? dl = list(def) b = nonempty_list(stmt) NEWLINE? EOF
{ dl, Sblock b }
;
def:
| DEF f = ident LP x = separated_list(COMMA, ident) RP
COLON s = suite
{ f, x, s }
;
expr:
| c = CST
{ Ecst c }
| e1 = expr LSQ e2 = expr RSQ
{ Eget (e1, e2) }
| MINUS e1 = expr %prec unary_minus
{ Eunop (Uneg, e1) }
| NOT e1 = expr
{ Eunop (Unot, e1) }
| e1 = expr o = binop e2 = expr
{ Ebinop (o, e1, e2) }
| LSQ l = separated_list(COMMA, expr) RSQ
{ Elist l }
| LAMBDA x = separated_list(COMMA, ident) COLON e = expr
{ Elambda (x, e) }
| e = expr2
{ e }
;
expr2:
| id = ident
{ Eident id}
| LP e = expr RP
{ e }
| f = expr2 LP e = separated_list(COMMA, expr) RP
{ Ecall (f, e) }
;
suite:
| s = simple_stmt NEWLINE
{ s }
| NEWLINE BEGIN l = nonempty_list(stmt) END
{ Sblock l }
;
stmt:
| s = simple_stmt NEWLINE
{ s }
| IF c = expr COLON s = suite
{ Sif (c, s, Sblock []) }
| IF c = expr COLON s1 = suite ELSE COLON s2 = suite
{ Sif (c, s1, s2) }
| FOR x = ident IN e = expr COLON s = suite
{ Sfor (x, e, s) }
| WHILE c = expr COLON s = suite
{ Swhile (c, s) }
;
simple_stmt:
| RETURN e = expr
{ Sreturn e }
| id = ident EQUAL e = expr
{ Sassign (id, e) }
| e1 = expr LSQ e2 = expr RSQ EQUAL e3 = expr
{ Sset (e1, e2, e3) }
| PRINT LP e = expr RP
{ Sprint e }
| e = expr
{ Seval e }
;
%inline binop:
| PLUS { Badd }
| MINUS { Bsub }
| TIMES { Bmul }
| DIV { Bdiv }
| MOD { Bmod }
| c=CMP { c }
| AND { Band }
| OR { Bor }
;
ident:
id = IDENT { { loc = ($startpos, $endpos); id } }
;