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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
|
module FlatCurry.AddTypes (
AProg(..), AFuncDecl(..), ARule(..), AExpr(..), ABranchExpr(..),
annOfAExpr, mapAExpr, fromAProg, fromAFuncDecl, fromAExpr,
TypeInfo, typeInfo, tiTypedVars, tiType,
annProg2Prog, annFunc2Func,
addTypesInProg, addTypesInProgWithImports, addTypesInFunc, addTypesInBody
) where
import Data.List ( init, isPrefixOf, last, maximum )
import Control.Monad.Trans.State
import qualified Data.Map as Map
import FlatCurry.Files ( readFlatCurryInt )
import FlatCurry.Goodies
import FlatCurry.Types
data AProg a = AProg String [String] [TypeDecl] [AFuncDecl a] [OpDecl]
deriving (Eq, Show)
data AFuncDecl a = AFunc QName Arity Visibility TypeExpr (ARule a)
deriving (Eq, Show)
data ARule a
= ARule [VarIndex] (AExpr a)
| AExternal String
deriving (Eq, Show)
data AExpr a
= AVar a VarIndex
| ALit a Literal
| AComb a CombType QName [AExpr a]
| ALet a [(VarIndex, TypeExpr, AExpr a)] (AExpr a)
| AFree a [(VarIndex, TypeExpr)] (AExpr a)
| AOr a (AExpr a) (AExpr a)
| ACase a CaseType (AExpr a) [ABranchExpr a]
| ATyped a (AExpr a) TypeExpr
deriving (Eq, Show)
data ABranchExpr a = ABranch Pattern (AExpr a)
deriving (Eq, Show)
annOfAExpr :: AExpr a -> a
annOfAExpr (AVar a _) = a
annOfAExpr (ALit a _) = a
annOfAExpr (AComb a _ _ _) = a
annOfAExpr (ALet a _ _) = a
annOfAExpr (AFree a _ _) = a
annOfAExpr (AOr a _ _) = a
annOfAExpr (ACase a _ _ _) = a
annOfAExpr (ATyped a _ _) = a
mapAExpr :: (a -> b) -> AExpr a -> AExpr b
mapAExpr f (AVar a v) = AVar (f a) v
mapAExpr f (ALit a l) = ALit (f a) l
mapAExpr f (AComb a ct qn es) = AComb (f a) ct qn (map (mapAExpr f) es)
mapAExpr f (ALet a bs e) = ALet (f a)
(map (\ (v,vt,be) -> (v,vt,mapAExpr f be)) bs)
(mapAExpr f e)
mapAExpr f (AFree a vts e) = AFree (f a) vts (mapAExpr f e)
mapAExpr f (AOr a e1 e2) = AOr (f a) (mapAExpr f e1) (mapAExpr f e2)
mapAExpr f (ACase a ct ce brs) =
ACase (f a) ct (mapAExpr f ce)
(map (\ (ABranch p be) -> ABranch p (mapAExpr f be)) brs)
mapAExpr f (ATyped a e te) = ATyped (f a) (mapAExpr f e) te
fromAProg :: AProg _ -> Prog
fromAProg (AProg mn imps tds fds ops) =
Prog mn imps tds (map fromAFuncDecl fds) ops
fromAFuncDecl :: AFuncDecl _ -> FuncDecl
fromAFuncDecl (AFunc qn ar vis te rl) = Func qn ar vis te (fromAR rl)
where fromAR (ARule vs ae) = Rule vs (fromAExpr ae)
fromAR (AExternal s) = External s
fromAExpr :: AExpr _ -> Expr
fromAExpr (AVar _ v) = Var v
fromAExpr (ALit _ l) = Lit l
fromAExpr (AComb _ ct qn es) = Comb ct qn (map fromAExpr es)
fromAExpr (ALet _ bs e) = Let (map (\ (v,vt,be) -> (v,vt,fromAExpr be)) bs)
(fromAExpr e)
fromAExpr (AFree _ vts e) = Free vts (fromAExpr e)
fromAExpr (AOr _ e1 e2) = Or (fromAExpr e1) (fromAExpr e2)
fromAExpr (ACase _ ct ce brs) =
Case ct (fromAExpr ce)
(map (\ (ABranch p be) -> Branch p (fromAExpr be)) brs)
fromAExpr (ATyped _ e te) = Typed (fromAExpr e) te
data TypeInfo = TypeInfo [(VarIndex,TypeExpr)] TypeExpr
deriving (Eq, Show)
typeInfo :: [(VarIndex,TypeExpr)] -> TypeExpr -> TypeInfo
typeInfo = TypeInfo
tiTypedVars :: TypeInfo -> [(VarIndex,TypeExpr)]
tiTypedVars (TypeInfo tvs _) = tvs
tiType :: TypeInfo -> TypeExpr
tiType (TypeInfo _ te) = te
applyTS2TypeInfo :: TSub -> TypeInfo -> TypeInfo
applyTS2TypeInfo ts (TypeInfo tvars texp) =
TypeInfo (map (\ (v,tv) -> (v, applyTS ts tv)) tvars) (applyTS ts texp)
annProg2Prog ::
(AExpr TypeInfo -> Expr)
-> AProg TypeInfo
-> Prog
annProg2Prog fromae (AProg mname imps tdecls fdecls ops) =
Prog mname imps tdecls (map (annFunc2Func fromae) fdecls) ops
annFunc2Func ::
(AExpr TypeInfo -> Expr)
-> AFuncDecl TypeInfo
-> FuncDecl
annFunc2Func fromae (AFunc qn ar vis te rule) =
Func qn ar vis te
(case rule of ARule vs rhs -> Rule vs (fromae rhs)
AExternal s -> External s)
addTypesInProg ::
Prog
-> IO (AProg TypeInfo)
addTypesInProg prog = do
impints <- mapM readFlatCurryInt (progImports prog)
return $ addTypesInProgWithImports impints prog
addTypesInProgWithImports ::
[Prog]
-> Prog
-> AProg TypeInfo
addTypesInProgWithImports impprogs prog@(Prog mname imps tdecls fdecls ops) =
AProg mname imps tdecls
(map (addTypesInFunc (typeOfQN ctypes) (typeOfQN ftypes))
(
fdecls))
ops
where
ctypes = Map.fromList (concatMap consTypesOfProg (prog:impprogs))
ftypes = Map.fromList (concatMap funcTypesOfProg (prog:impprogs))
typeOfQN qnts qn =
maybe (error $ "Type of entity " ++ show qn ++ " not found!")
id
(Map.lookup qn qnts)
consTypesOfProg :: Prog -> [(QName,TypeExpr)]
consTypesOfProg prog =
concatMap consTypes (progTypes prog)
where
consTypes (Type tn _ tvs cdecls) = map consTypeOfCDecl cdecls
where
consTypeOfCDecl (Cons cn _ _ texps) =
(cn, stripForall (foldr FuncType (resultType tn tvs) texps))
consTypes (TypeSyn _ _ _ _) = []
consTypes (TypeNew tn _ tvs (NewCons cn _ texp)) =
[(cn, stripForall (FuncType texp (resultType tn tvs)))]
resultType tn tvks = TCons tn (map (TVar . fst) tvks)
funcTypesOfProg :: Prog -> [(QName,TypeExpr)]
funcTypesOfProg prog =
map (\fd -> (funcName fd, stripForall (funcType fd))) (progFuncs prog)
data TIState = TIState
{ tiVars :: [(VarIndex,TypeExpr)]
, tiMaxTVar :: Int
, tiTSub :: TSub
}
deriving Show
initTIState :: TypeExpr -> TIState
initTIState te = TIState [] (maximum (0 : allTVarsInTExp te)) idTSub
type TransState a = State TIState a
getVarType :: VarIndex -> TransState TypeExpr
getVarType v = do
ti <- get
maybe (error $ "Variable " ++ show v ++ " not found in " ++ show ti)
return
(lookup v (tiVars ti))
getTypedVars :: TransState [(VarIndex,TypeExpr)]
getTypedVars = do
ti <- get
return (tiVars ti)
setTypedVars :: [(VarIndex,TypeExpr)] -> TransState ()
setTypedVars tvars = do
ti <- get
put $ ti { tiVars = tvars }
addTypedVars :: [(VarIndex,TypeExpr)] -> TransState ()
addTypedVars tvs = do
ti <- get
put $ ti { tiVars = tvs ++ tiVars ti
, tiMaxTVar = maximum (tiMaxTVar ti :
concatMap (allTVarsInTExp . snd) tvs)
}
getFreshTVar :: TransState TVarIndex
getFreshTVar = do
ti <- get
let newtvi = tiMaxTVar ti + 1
put ti { tiMaxTVar = newtvi }
return newtvi
getFreshTExp :: TypeExpr -> TransState TypeExpr
getFreshTExp texpr = do
ti <- get
let ftexpr = freshTE (tiMaxTVar ti + 1) texpr
put $ ti { tiMaxTVar = maximum (tiMaxTVar ti : allTVarsInTExp ftexpr) }
return ftexpr
freshTE :: Int -> TypeExpr -> TypeExpr
freshTE mtv texp = case texp of
TVar v -> TVar (v + mtv)
FuncType t1 t2 -> FuncType (freshTE mtv t1) (freshTE mtv t2)
TCons tc tes -> TCons tc (map (freshTE mtv) tes)
ForallType tvs fte -> ForallType (map (\(v,k) -> (v+mtv,k)) tvs)
(freshTE mtv fte)
addTSub :: TSub -> TransState ()
addTSub tsub
| tsub == []
= return ()
| otherwise
= do ti <- get
put $ ti { tiTSub = compTSub tsub (tiTSub ti)
, tiVars = map (\ (v,tv) -> (v, applyTS tsub tv)) (tiVars ti)
}
applyCurrentTSub :: TypeExpr -> TransState TypeExpr
applyCurrentTSub te = do
ti <- get
return (applyTS (tiTSub ti) te)
returnAExpr :: TypeExpr -> (TypeInfo -> AExpr TypeInfo)
-> TransState (AExpr TypeInfo)
returnAExpr rtype presult = do
ti <- get
return (presult (TypeInfo (tiVars ti) rtype))
allTVarsInTExp :: TypeExpr -> [Int]
allTVarsInTExp te = trTypeExpr (:) tcomb (.) forall te []
where
tcomb _ = foldr (.) id
forall tvs texp = (map fst tvs ++) . texp
addTypesInFunc ::
(QName -> TypeExpr)
-> (QName -> TypeExpr)
-> FuncDecl
-> AFuncDecl TypeInfo
addTypesInFunc ctm ftm (Func qf ar vis ftype rule) =
AFunc qf ar vis ftype
(case rule of
External s -> AExternal s
Rule args rhs ->
ARule args
(addTypesInBody ctm ftm qf (zip args argtypes) rhs rhstype))
where
(argtypes,rhstype) = splitFuncType ar (stripForall ftype)
addTypesInBody :: (QName -> TypeExpr) -> (QName -> TypeExpr) -> QName
-> [(VarIndex,TypeExpr)] -> Expr -> TypeExpr -> AExpr TypeInfo
addTypesInBody ctypemap ftypemap _ typedvars expr resulttype =
let (aexp0,rstate) = runState
(addTypedVars typedvars >> annExp expr resulttype)
(initTIState resulttype)
aexp = mapAExpr (applyTS2TypeInfo (tiTSub rstate)) aexp0
in
aexp
where
annExp exp rt = do
case exp of
Var v -> do vt <- getVarType v
if rt == vt
then returnAExpr rt $ \ti -> AVar ti v
else do
let tsub = unifyTExps rt vt
addTSub tsub
returnAExpr (applyTS tsub rt) $ \ti-> AVar ti v
Lit l -> if rt == typeOfLit l
then returnAExpr rt $ \ti -> ALit ti l
else do
let tsub = unifyTExps rt (typeOfLit l)
addTSub tsub
returnAExpr (applyTS tsub rt) $ \ti -> ALit ti l
Comb ct qn es -> annComb ct qn es rt
Let bs e -> annLet bs e rt
Free vs e -> do addTypedVars vs
aexp <- annExp e rt
returnAExpr rt $ \tie -> AFree tie vs aexp
Or e1 e2 -> do aexp1 <- annExp e1 rt
aexp2 <- annExp e2 rt
returnAExpr rt $ \tie -> AOr tie aexp1 aexp2
Case ct ce bs -> annCase ct ce bs rt
Typed e t -> do aexp <- annExp e rt
returnAExpr rt $ \tie -> ATyped tie aexp t
annComb ct qn args rtype = do
qntype <- getFreshTExp $ case ct of FuncCall -> ftypemap qn
ConsCall -> ctypemap qn
FuncPartCall _ -> ftypemap qn
ConsPartCall _ -> ctypemap qn
let (ats,rt) = splitFuncType (length args) qntype
iats <- if rt == rtype
then return ats
else do let tsubst = unifyTExps rt rtype
addTSub tsubst
return $ map (applyTS tsubst) ats
aes <- mapM (\ (e,te) -> annExp e te) (zip args iats)
returnAExpr rtype $ \ti -> AComb ti ct qn aes
annLet bs e rtype = do
addTypedVars (map (\ (v,t,_) -> (v,t)) bs)
abs <- mapM (\ (v,t,be) -> annExp be t >>= \abe -> return (v,t,abe)) bs
ae <- annExp e rtype
returnAExpr rtype $ \ti -> ALet ti abs ae
annCase ct ce brs rtype = do
ctype <- case ce of Var v -> getVarType v
_ -> fmap TVar getFreshTVar
ace <- annExp ce ctype
ptype <- applyCurrentTSub ctype
abs <- mapM (annBranch ptype) brs
returnAExpr rtype $ \tie -> ACase tie ct ace abs
where
annBranch ptype (Branch pt be) = do
tvs <- patVars ptype pt
addTypedVars tvs
aexp <- annExp be rtype
return $ ABranch pt aexp
patVars _ (LPattern _) = return []
patVars ptype (Pattern qn vs) = do
ctype <- getFreshTExp (ctypemap qn)
let (ats,rt) = splitFuncType (length vs) ctype
tsub = unifyTExps rt ptype
addTSub tsub
return $ zip vs (map (applyTS tsub) ats)
checkAnnExpr :: (QName -> TypeExpr) -> (QName -> TypeExpr) -> QName
-> AExpr TypeInfo -> Bool
checkAnnExpr ctypemap ftypemap qf aexp = checkAExp aexp
where
checkError msg = error $ "Check error in function '" ++ snd qf ++ "':\n" ++
msg ++ "\n\n" ++ show aexp
checkAExp exp =
let checkMsg msg c = c ||
(checkError $ "Annotated subexpression inconsistent:\n" ++ show exp ++
(if null msg then "" else "\nProblem: " ++ show msg))
checkET t1 t2 = checkMsg ("Types differ: " ++ show t1 ++ " " ++ show t2)
(t1 == t2)
TypeInfo tvs rt = annOfAExpr exp in
case exp of
AVar _ v -> maybe (checkError $ "Variable " ++ show v ++
" not in list of typed variables!")
(\vt -> checkET vt rt)
(lookup v tvs)
ALit _ l -> checkET rt (typeOfLit l)
AComb _ ct qn es -> let qntype = freshTE 1000 $
case ct of FuncCall -> ftypemap qn
ConsCall -> ctypemap qn
FuncPartCall _ -> ftypemap qn
ConsPartCall _ -> ctypemap qn
ctype = foldr (FuncType . annTypeOfAExpr) rt es
tsub = unifyTExps qntype ctype
in checkMsg "comb type wrong" (length tsub >= 0) &&
all checkAExp es
ALet _ bs e -> checkET (annTypeOfAExpr e) rt &&
all (\ (v,t,be) ->
checkMsg "not all let vars contained"
((v,t) `elem` annVarsOfAExpr e) &&
checkAExp be &&
checkET t (annTypeOfAExpr be)) bs &&
checkAExp e
AFree _ vs e -> checkET (annTypeOfAExpr e) rt &&
checkMsg "not all free vars contained"
(all (`elem` annVarsOfAExpr e) vs) &&
checkAExp e
AOr ta e1 e2 -> checkAExp e1 && checkAExp e2 &&
checkET ta (annOfAExpr e1) &&
checkET ta (annOfAExpr e2)
ACase _ _ ce bs -> checkAExp ce &&
all (\ (ABranch pt be) ->
checkMsg "not all pattern vars contained"
(all (`elem` map fst (annVarsOfAExpr be))
(patVars pt)) &&
checkAExp be &&
checkET rt (annTypeOfAExpr be))
bs
ATyped ta e t -> checkET ta (annOfAExpr e) && checkET rt t &&
checkAExp e
patVars (LPattern _) = []
patVars (Pattern _ vs) = vs
annVarsOfAExpr = tiTypedVars . annOfAExpr
annTypeOfAExpr = tiType . annOfAExpr
type TSub = [(TVarIndex,TypeExpr)]
idTSub :: TSub
idTSub = []
applyTS :: TSub -> TypeExpr -> TypeExpr
applyTS tvtexps te = subst te
where
subst texp = case texp of
TVar v -> maybe texp id (lookup v tvtexps)
FuncType t1 t2 -> FuncType (subst t1) (subst t2)
TCons tc tes -> TCons tc (map subst tes)
ForallType tvs fte -> ForallType tvs (subst fte)
compTSub :: TSub -> TSub -> TSub
compTSub s1 s2 = s1 ++ map (\ (v,t) -> (v, applyTS s1 t)) s2
unifyTExps :: TypeExpr -> TypeExpr -> TSub
unifyTExps texp1 texp2 = unify [] texp1 texp2
where
unify tsub te1 te2 =
unifyST tsub (simpTop (applyTS tsub te1)) (simpTop (applyTS tsub te2))
unifyST tsub te1 te2 = case (te1, te2) of
(TVar v, te) -> case te of
TVar v' | v == v' -> tsub
| v > v' -> (v, TVar v') : tsub
| v < v' -> (v', TVar v) : tsub
_ -> (v,te) : tsub
(_, TVar _) -> unifyST tsub te2 te1
(FuncType at1 rt1, FuncType at2 rt2) ->
unify (unify tsub at1 at2) rt1 rt2
(TCons tc1 tes1, TCons tc2 tes2)
| tc1 == tc2 -> unifyTEs tsub (zip tes1 tes2)
| tc1 == tcApply && tc2 == tcApply -> unifyTEs tsub (zip tes1 tes2)
| tc1 == tcApply
-> unifyTEs tsub (zip tes1 [TCons tc2 (init tes2), last tes2])
| tc2 == tcApply
-> unifyTEs tsub (zip tes2 [TCons tc1 (init tes1), last tes1])
(TCons tca [TVar tf, te], FuncType fte1 fte2)
| tca == tcApply -> unify ((tf, TCons tcFunc [fte1]):tsub) te fte2
(FuncType fte1 fte2, TCons tca [TVar tf, te])
| tca == tcApply -> unify ((tf, TCons tcFunc [fte1]):tsub) te fte2
_ -> error $ "unifyTExps: types not unifiable:\n" ++
show texp1 ++ "\n" ++ show texp2 ++ "\n"
unifyTEs tsub [] = tsub
unifyTEs tsub ((te1,te2):tes) = unifyTEs (unify tsub te1 te2) tes
simpTop texp = case texp of
TCons tc [TCons tc1 tes1, te2] | tc == tcApply
-> simpTop (TCons tc1 (tes1 ++ [te2]))
TCons tc [te1, te2] | tc == tcFunc -> FuncType te1 te2
_ -> texp
tcApply = pre "Apply"
tcFunc = pre "(->)"
pre :: String -> QName
pre f = ("Prelude",f)
typeOfLit :: Literal -> TypeExpr
typeOfLit l = TCons (pre ltype) []
where ltype = case l of Intc _ -> "Int"
Floatc _ -> "Float"
Charc _ -> "Char"
splitFuncType :: Int -> TypeExpr -> ([TypeExpr],TypeExpr)
splitFuncType ar te
| ar < 0 = error "splitFuncType with negative arity"
| ar == 0 = ([],te)
| otherwise = case te of
FuncType t1 t2 -> let (ts,rt) = splitFuncType (ar-1) t2
in (t1:ts, rt)
_ -> error "splitFuncType without function type"
stripForall :: TypeExpr -> TypeExpr
stripForall texp = case texp of
ForallType _ te -> stripForall te
FuncType t1 t2 -> FuncType (stripForall t1) (stripForall t2)
TCons tc tes -> TCons tc (map stripForall tes)
TVar v -> TVar v
|