-
Notifications
You must be signed in to change notification settings - Fork 9
/
semant.sml
372 lines (337 loc) · 14.5 KB
/
semant.sml
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
signature SEMANT =
sig
val transProg : Absyn.exp -> {exp:Translate.frag list, ty:Types.ty}
end
structure Semant :> SEMANT = struct
structure A = Absyn
structure E = Env
structure Tr = Translate
val err = ErrorMsg.error
exception ErrMsg
val nestLevel = ref 0
fun incLevel () = nestLevel := !nestLevel + 1
fun decLevel () = nestLevel := !nestLevel - 1
fun typelookup tenv n pos=
(case Symbol.look (tenv, n) of
SOME ty2 => ty2
| NONE => (err pos ("type is not defined: " ^ Symbol.name n) ;
Types.UNIT))
fun checkDups([],p) = ()
| checkDups(h,[]) = ()
| checkDups(h::l,p::ps) =
if (List.exists (fn (x) => (h = x)) l) then
(err p (" duplicate entry: " ^ (Symbol.name h)))
else checkDups(l,ps)
fun transTy (tenv, t)=
let
fun recordtys(fields)=
map (fn{name, escape, typ, pos}=>
(case SOME(typelookup tenv typ pos) of
SOME t => (name, t)
| NONE => (name, Types.UNIT))) fields
in
case t of
A.NameTy (n, pos) => typelookup tenv n pos
| A.RecordTy fields => (checkDups((map #name fields), (map #pos fields));
Types.RECORD (recordtys fields, ref()))
| A.ArrayTy (n,pos) => Types.ARRAY(typelookup tenv n pos, ref())
end
fun compare_ty (ty1, ty2, pos)=
case ty1 of
Types.RECORD(_,_) => (ty1 = ty2) orelse ty2 = Types.NIL
| Types.NIL => (ty1 = ty2) orelse
(case ty2 of Types.RECORD(_,_) => true
| _ => (ty2 = Types.NIL))
| _ => (ty1 = ty2)
fun compare_tys ([], trexps, pos) = {exp=Tr.empty, ty=Types.UNIT}
| compare_tys(tys, [], pos) = {exp=Tr.empty, ty=Types.UNIT}
| compare_tys(t1::l1,t2::l2,pos) = (compare_ty(t1,t2,pos); compare_tys(l1,l2,pos))
fun actual_ty (Types.NAME (s,ty)) =
(case !ty of
NONE => raise ErrMsg
| SOME t => actual_ty t)
| actual_ty t = t
fun checkInt ({exp, ty}, pos) =
((if ty = Types.INT then () else err pos "integer required"); exp)
fun checkUnit ({exp, ty}, pos) =
((if ty = Types.UNIT then () else err pos "unit required"); exp)
fun checkString ({exp, ty}, pos) =
((if ty = Types.STRING then () else err pos "string required"); exp)
fun checkRecord (rty, {exp, ty}, pos) =
((if compare_ty(rty, ty, pos) then () else err pos "string required"); exp)
(* Takes venv, tenv, exp *)
fun transExp(venv, tenv, break, level) =
let
fun trexp (A.NilExp) = {exp=Tr.nilExp(), ty=Types.NIL}
| trexp (A.VarExp var) = trvar var
| trexp (A.IntExp i) = {exp=(Tr.intExp(i)), ty=Types.INT}
| trexp (A.StringExp (str, pos)) = {exp=Tr.stringExp(str), ty=Types.STRING}
| trexp (A.OpExp {left, oper, right, pos}) =
let
val left' = trexp left
val right' = trexp right
in
if oper = A.PlusOp orelse oper = A.MinusOp orelse
oper = A.TimesOp orelse oper = A.DivideOp then
(checkInt(left', pos); checkInt(right', pos);
{exp=Tr.intOpExp(oper, #exp left', #exp right'), ty=Types.INT})
else if oper = A.LtOp orelse oper = A.LeOp orelse oper = A.GtOp orelse oper = A.GeOp then
(case #ty left' of
Types.INT =>
(checkInt(right', pos);
{exp=Tr.intOpExp(oper, #exp left', #exp right'), ty=Types.INT})
| Types.STRING =>
(checkString(right', pos);
{exp=Tr.stringOpExp(oper, #exp left', #exp right'), ty=Types.INT})
| _ => (err pos "1can't perform comparisons on this type";
{exp=Tr.nilExp(), ty=Types.INT}))
else if oper = A.EqOp orelse oper = A.NeqOp then
(case #ty left' of
Types.INT =>
(checkInt(right', pos);
{exp=Tr.intOpExp(oper, #exp left', #exp right'), ty=Types.INT})
| Types.STRING =>
(checkString(right', pos);
{exp=Tr.stringOpExp(oper, #exp left', #exp right'), ty=Types.INT})
| Types.RECORD(symtys, uq) =>
(checkRecord(Types.RECORD(symtys, uq), right', pos);
{exp=Tr.recordCompExp(oper, #exp left', #exp right'), ty=Types.INT})
| Types.NIL =>
(checkRecord(Types.NIL, right', pos);
{exp=Tr.recordCompExp(oper, #exp left', #exp right'), ty=Types.INT})
| ty => (print ("-------"^Types.toString(ty));
err pos "2can't perform comparisons on this type";
{exp=Tr.nilExp(), ty=Types.INT}))
else
(err pos "error"; {exp=Tr.nilExp(), ty=Types.INT})
end
| trexp (A.CallExp {func, args, pos}) =
(case Symbol.look (venv, func) of
SOME (E.FunEntry {formals, result, level, label}) =>
let val args' = map trexp args
in
(if length(args) <> length(formals) then (* check argument lengths and compare *)
(err pos "wrong amount of arguments"; {exp=Tr.nilExp(), ty=result})
else
(compare_tys (formals, map #ty args', pos);
{exp=Tr.callExp(level,label,map #exp (map trexp args)),ty=actual_ty result}))
end
| _ => (err pos ("can't call nonexistent function: " ^ Symbol.name func ); {exp=Tr.nilExp(), ty=Types.UNIT}))
(* Should check to make sure return types match, as do argtypes *)
| trexp (A.IfExp {test, then', else', pos}) =
let
val test' = trexp (test)
val then'' = trexp (then')
in
(case else' of
NONE =>
(checkInt (test', pos);
{exp=(Tr.ifThenExp(#exp test', #exp then'')), ty=(#ty then'')})
| SOME else' =>
let val else'' = trexp (else')
in
checkInt(test', pos); checkUnit(then'', pos); checkUnit(else'', pos);
{exp=(Tr.ifThenElseExp(#exp test', #exp then'', #exp else'')), ty=Types.UNIT}
end
)
end
| trexp (A.WhileExp {test, body, pos}) =
let
val _ = incLevel()
val body' = transExp (venv,tenv,break,level) body
val test' = transExp (venv,tenv,break,level) body
val _ = decLevel()
in
(checkInt (test', pos); checkUnit (body', pos);
{exp=Tr.whileExp(#exp test', #exp body', break), ty=Types.UNIT})
end
| trexp (A.RecordExp {fields, typ, pos}) =
let
val typ' = typelookup tenv typ pos
val result = actual_ty typ'
val fnames = map #1 fields
val tyfields = map trexp (map #2 fields)
val types = map #ty tyfields
in
case result of
Types.RECORD(s, u) =>
let
val dfnames = map #1 s
val dftypes = map actual_ty (map #2 s)
in
if fnames = dfnames then
if (ListPair.all
(fn (ty1, ty2) => compare_ty (ty1, ty2, pos))
(types, dftypes)) then
{exp=Tr.recordExp(map #exp tyfields), ty=result}
else
(err pos ("field types not consistent: " ^ Symbol.name typ);
{exp=Tr.nilExp(),ty=result})
else
(err pos ("field types not consistent: " ^ Symbol.name typ);
{exp=Tr.nilExp(),ty=result})
end
| _ => (err pos ("not a valid record type: " ^ Symbol.name typ);
{exp=Tr.nilExp(), ty=Types.UNIT})
end
| trexp (A.SeqExp []) = {exp=Tr.empty, ty=Types.UNIT}
| trexp (A.SeqExp exps) =
let
val (exps', ty) =
foldl (fn ((exp, _), (exps', _)) =>
let val {exp=newExp, ty} =
(transExp(venv, tenv, break, level) exp)
in (exps' @ [newExp], ty) end)
([], Types.UNIT)
exps
in
{exp=Tr.seqExp exps', ty=ty}
end
| trexp (A.AssignExp {var, exp, pos}) =
let
val {exp=left, ty=expect} = trvar (var)
val {exp=right, ty=actual} = trexp (exp)
in
if expect <> actual then
(err pos "assignment mismatch"; {exp=Tr.nilExp(), ty=Types.UNIT})
else
{exp=Tr.assignExp(left, right), ty=Types.UNIT}
end
| trexp (A.ForExp {var, escape, lo, hi, body, pos}) =
let
val access = Tr.allocLocal level (!escape)
val breakpoint = Tr.newbreakpoint()
val {exp=lo', ty=loty} = transExp (venv, tenv, break, level) lo
val {exp=hi', ty=hity} = transExp (venv, tenv, break, level) hi
val venv' = Symbol.enter (venv, var, Env.VarEntry {access=access, ty=Types.INT})
val {exp=bodyExp, ty=body_ty} = transExp (venv', tenv, breakpoint, level) body
in
{exp=Tr.forExp(Tr.simpleVar (access, level), breakpoint, lo', hi', bodyExp), ty=Types.UNIT}
end
| trexp (A.BreakExp pos) =
if !nestLevel > 0 then
{exp=Tr.breakExp(break), ty=Types.UNIT}
else
(err pos "Break not nested correctly";
{exp=Tr.nilExp(), ty=Types.UNIT})
| trexp (A.LetExp {decs, body, pos}) =
let
val (venv', tenv', decList, _) =
foldr (fn (dec, (v, t, e, l)) => transDec(v, t, dec, break, e, l))
(venv, tenv, [], level) decs
val {exp=bodyExp, ty=bodyTy} = transExp (venv',tenv', break, level) body
in
{exp=Tr.letExp(decList,bodyExp), ty=bodyTy}
end
| trexp (A.ArrayExp {typ, size, init, pos}) =
{exp=Tr.nilExp(), ty=Types.UNIT}
and trvar (A.SimpleVar(id,pos)) =
(case Symbol.look(venv, id) of
SOME (E.VarEntry{access, ty}) =>
{exp=Tr.simpleVar(access, level), ty=actual_ty ty}
| _ => (err pos ("undefined variable: " ^ Symbol.name id);
{exp=Tr.nilExp(), ty=Types.INT}))
| trvar (A.FieldVar(var,id,pos)) =
(case trvar var of
{exp, ty=record as Types.RECORD (fields, _)} => {exp=Tr.nilExp(), ty=record}
| _ => (err pos "no var found"; {exp=Tr.nilExp(), ty=Types.UNIT}))
| trvar (A.SubscriptVar(var, exp,pos)) =
(checkInt(trexp exp, pos);
{exp=Tr.nilExp(), ty=Types.UNIT})
in
trexp
end
and transDec (venv, tenv, A.VarDec{name,escape=escape, typ=typ, init, pos=pos1}, break, explist, level) =
let
val {exp, ty} = transExp (venv, tenv, break, level) init
val access = Tr.allocLocal level (!escape)
val explist' = explist @ [Tr.assign (Tr.simpleVar (access, level), exp)]
val _ = case typ of
SOME(s, pos) =>
(case Symbol.look (tenv,s) of
NONE => (err pos ("type not defined: " ^ Symbol.name s))
| SOME ty2 => (compare_ty(ty, ty2, pos1);()))
| NONE => ()
in
(Symbol.enter(venv, name, E.VarEntry{access=access, ty=ty}), tenv, explist', level)
end
| transDec (venv, tenv, A.TypeDec vardecs, break, explist, level) =
let
val names = map #name vardecs
val poss = map #pos vardecs
val typs = map #ty vardecs
fun addt (n,env) = Symbol.enter(env,n,Types.NAME(n,ref(Symbol.look(tenv, n))))
val tenv' = foldr addt tenv names
val nts = map (fn t => transTy (tenv', t)) typs
fun updt (n,nt) =
let val (SOME (Types.NAME(_,r))) = Symbol.look(tenv',n)
in r := SOME nt
end
val _ = app updt (ListPair.zip(names,nts))
in
(venv, tenv', explist, level)
end
| transDec(venv, tenv, A.FunctionDec(fundecs), break, explist, level) =
let
val fundef = ref []
val levels = ref []
fun makeheader (fundec:A.fundec,env) =
let
val r_ty =
(case (#result fundec) of
NONE => Types.UNIT
| SOME(rt,pos) => typelookup tenv rt pos)
val params' = (map (fn ({name,escape,typ,pos}) => {name=name,
ty=typelookup tenv typ pos})
(#params fundec))
val formals = (map (fn ({name,escape,typ,pos}) => (!escape)) (#params fundec))
val funlabel = Temp.newlabel()
val new_level = Tr.newLevel{parent=level,
name=funlabel,
formals=formals}
val _ = levels := new_level::(!levels)
in
Symbol.enter(env,
(#name fundec),
E.FunEntry({formals=(map #ty params'),
result=r_ty,
label=funlabel,
level=new_level}))
end
fun enterparam (param:A.field,venv) =
let
val access = Tr.allocLocal (hd(!levels)) (!(#escape param))
val ty = typelookup tenv (#typ param) (#pos param)
in
Symbol.enter(venv, (#name param), E.VarEntry{access=access,ty=ty})
end
val venv' = (foldl makeheader venv fundecs)
fun check (fundec:A.fundec) =
let
val venv'' = (foldl enterparam venv' (#params fundec))
val {exp, ty} = transExp(venv'',tenv,break,level) (#body fundec)
val check_level = hd ((!levels))
val _ = (levels := tl ((!levels)))
val _ = Tr.procEntryExit({level=check_level, body=exp})
in
fundef := (!fundef) @ [exp]
end
val checkres = (map check fundecs)
val fundef' = !fundef
val explist' = (explist@fundef')
in
(venv', tenv, explist', level)
end
fun transProg(exp) =
let
val _ = Tr.init()
val firstlevel = Translate.newLevel {
name=Temp.namedlabel "firstlevel",
parent=Tr.outermost,
formals=[]}
val {exp, ty} = transExp (Env.base_venv, Env.base_tenv, Temp.newlabel(), firstlevel) exp
in
(Tr.procEntryExit {level=firstlevel, body=exp};
{exp=Tr.getResult(), ty=ty})
end
end