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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
|
module FlatCurry.Annotated.TypeInference
( TypeEnv, getTypeEnv, getTypeEnvFromProgEnv
, inferProg, inferProgFromProgEnv, inferProgEnv
, inferFunction, inferFunctionEnv
, inferNewFunctions, inferNewFunctionsEnv
, inferExpr, inferExprEnv
) where
import FiniteMap
import List (find)
import qualified Pretty as P
import ErrorState
import FlatCurry.Types
import FlatCurry.Files
import FlatCurry.Goodies (branchExpr, funcName)
import FlatCurry.Annotated.Types
import qualified FlatCurry.Annotated.Goodies as AFC (annExpr, funcName)
import FlatCurry.Annotated.Pretty (ppQName, ppExp, ppTypeExp
, ppVarIndex)
import FlatCurry.Annotated.TypeSubst
import SCC
import Rewriting.Term
import Rewriting.Unification
import Unsafe
inferProg :: Prog -> IO (Either String (AProg TypeExpr))
inferProg p = getTypeEnv p >>= \te -> return (inferProgEnv te p)
inferProgFromProgEnv :: [(String, Prog)] -> Prog
-> Either String (AProg TypeExpr)
inferProgFromProgEnv env p = case getTypeEnvFromProgEnv env p of
Left err -> Left err
Right tyEnv -> inferProgEnv tyEnv p
inferFunction :: Prog -> QName -> IO (Either String (AFuncDecl TypeExpr))
inferFunction p f = getTypeEnv p >>= \te -> return (inferFunctionEnv te p f)
inferNewFunctions :: Prog -> [FuncDecl]
-> IO (Either String [AFuncDecl TypeExpr])
inferNewFunctions p@(Prog mid _ _ _ _) fs
= getTypeEnv p >>= \te -> return (inferNewFunctionsEnv te mid fs)
inferExpr :: Prog -> Expr -> IO (Either String (AExpr TypeExpr))
inferExpr p e = getTypeEnv p >>= \te -> return (inferExprEnv te e)
inferProgEnv :: TypeEnv -> Prog -> Either String (AProg TypeExpr)
inferProgEnv te p = evalES (annProg p >+= inferAProg) (initTIM te)
inferFunctionEnv :: TypeEnv -> Prog -> QName
-> Either String (AFuncDecl TypeExpr)
inferFunctionEnv te (Prog _ _ _ fs _) f = case find ((== f) . funcName) fs of
Nothing -> Left $ P.pretty 80 $ P.text "No such function:" P.<+> ppQName f
Just fd -> evalES (annFunc fd >+= inferFunc) (initTIM te)
inferNewFunctionsEnv :: TypeEnv -> String -> [FuncDecl]
-> Either String [AFuncDecl TypeExpr]
inferNewFunctionsEnv te mid fs = evalES (infer (depGraph mid fs)) (initTIM te)
where
infer fss = concatMapES inferGroup fss >+= \fs' ->
mapES (flip extract fs') fs
inferGroup g = annFuncGroup g >+= inferFuncGroup >+= \afs ->
extendTypeEnv [(f, ty) | AFunc f _ _ ty _ <- afs] >+
returnES afs
extract f afs = case find ((== funcName f) . AFC.funcName) afs of
Just af -> returnES af
Nothing -> failES "Internal error: extract"
inferExprEnv :: TypeEnv -> Expr -> Either String (AExpr TypeExpr)
inferExprEnv te e = evalES (annExpr e >+= inferAExpr) (initTIM te)
depGraph :: String -> [FuncDecl] -> [[FuncDecl]]
depGraph mid = scc def use
where
def (Func f _ _ _ _) = [f]
use (Func _ _ _ _ r) = case r of
Rule _ e -> called e
_ -> []
called (Var _) = []
called (Lit _) = []
called (Comb ct f@(m, _) es)
| m == mid = (case ct of
FuncCall -> [f]
FuncPartCall _ -> [f]
_ -> []) ++ concatMap called es
| otherwise = concatMap called es
called (Let bs e) = concatMap called (map snd bs ++ [e])
called (Free _ e) = called e
called (Or a b) = concatMap called [a, b]
called (Case _ e bs) = concatMap called (e : map branchExpr bs)
called (Typed e _) = called e
type TypeEnv = FM QName TypeExpr
lookupType :: TypeEnv -> QName -> Maybe TypeExpr
lookupType = lookupFM
getTypeEnv :: Prog -> IO TypeEnv
getTypeEnv p = do
is <- extractImported p
return (extractKnownTypes $ p : is)
extractImported :: Prog -> IO [Prog]
extractImported (Prog _ is _ _ _) = mapIO readFlatCurryInt is
getTypeEnvFromProgEnv :: [(String, Prog)] -> Prog -> Either String TypeEnv
getTypeEnvFromProgEnv env prog@(Prog _ imps _ _ _) = case extract imps of
Left err -> Left err
Right mods -> Right (extractKnownTypes $ prog : mods)
where
extract [] = Right []
extract (i:is) = case lookup i env of
Nothing -> Left $ "getTypeEnvFromProgEnv: Could not find module " ++ i
Just p -> case extract is of
Left err -> Left err
Right ps -> Right (p : ps)
extractKnownTypes :: [Prog] -> TypeEnv
extractKnownTypes ps = listToFM (<) $ concatMap extractProg ps
where
extractProg :: Prog -> [(QName, TypeExpr)]
extractProg (Prog _ _ td fd _)
= concatMap extractTypeDecl td ++ map extractFuncDecl fd
extractFuncDecl :: FuncDecl -> (QName, TypeExpr)
extractFuncDecl (Func n _ _ ty _) = (n, ty)
extractTypeDecl :: TypeDecl -> [(QName, TypeExpr)]
extractTypeDecl (TypeSyn n _ _ ty) = [(n, ty)]
extractTypeDecl (Type n _ vs cs) = map (extractConsDecl ty) cs
where ty = TCons n (map TVar vs)
extractConsDecl :: TypeExpr -> ConsDecl -> (QName, TypeExpr)
extractConsDecl ty (Cons n _ _ tys) = (n, foldr FuncType ty tys)
typeArity :: TypeExpr -> Int
typeArity ty = case ty of
FuncType _ b -> 1 + typeArity b
_ -> 0
type TIM a = ES String (TypeEnv, Int, TypeEnv, FM Int TypeExpr) a
initTIM :: TypeEnv -> (TypeEnv, Int, TypeEnv, FM Int TypeExpr)
initTIM te = (te, 0, emptyFM (<), emptyFM (<))
extendTypeEnv :: [(QName, TypeExpr)] -> TIM ()
extendTypeEnv ftys = gets >+= \ (te, v, fe, ve) ->
puts (addListToFM te ftys, v, fe, ve)
nextTVar :: TIM TypeExpr
nextTVar = gets >+= \ (te, n, fun2Ty, var2Ty) ->
puts (te, n + 1, fun2Ty, var2Ty) >+ returnES (TVar n)
initVarTypes :: TIM ()
initVarTypes = modify $ \ (te, n, fe, _) -> (te, n, fe, emptyFM (<))
initSigEnv :: TIM ()
initSigEnv = modify $ \ (te, n, _, ve) -> (te, n, emptyFM (<), ve)
insertVarType :: Int -> TypeExpr -> TIM ()
insertVarType v ty = modify $ \ (te, n, fe, var2Ty) ->
(te, n, fe, addToFM var2Ty v ty)
insertFunType :: QName -> TypeExpr -> TIM ()
insertFunType f sig = freshVariant sig >+= \ty ->
modify $ \ (te, n, fe, ve) -> (te, n, addToFM fe f ty, ve)
lookupVarType :: Int -> TIM (Maybe TypeExpr)
lookupVarType v = gets >+= \ (_, _, _, var2Ty) -> returnES (lookupFM var2Ty v)
getTypeVariant :: QName -> TIM (QName, TypeExpr)
getTypeVariant f = gets >+= \ (env, _, fe, _) -> case lookupType env f of
Nothing -> case lookupFM fe f of
Nothing -> failES $ "Internal error: getTypeVariant " ++ show f
Just ty -> returnES (f, ty)
Just t -> freshVariant t >+= \ty -> returnES (f, ty)
freshVariant :: TypeExpr -> TIM TypeExpr
freshVariant ty = snd <$> rename [] ty
where
rename ren (TVar i) = case lookup i ren of
Just j -> returnES (ren, j)
Nothing -> nextTVar >+= \j -> returnES ((i, j) : ren, j)
rename ren (FuncType a b) = rename ren a >+= \ (ren1, a') ->
rename ren1 b >+= \ (ren2, b') ->
returnES (ren2, FuncType a' b')
rename ren (TCons t tys) = mapAccumES rename ren tys >+= \(ren', tys') ->
returnES (ren', TCons t tys')
annProg :: Prog -> TIM (AProg TypeExpr)
annProg (Prog mid is td fd od) =
(\afd -> AProg mid is td afd od) <$> mapES annFunc fd
annFuncGroup :: [FuncDecl] -> TIM [AFuncDecl TypeExpr]
annFuncGroup fs = initSigEnv >+ mapES (uncurry insertFunType) ftys >+
mapES annFunc fs
where ftys = [ (f, ty) | Func f _ _ ty _ <- fs]
annFunc ::FuncDecl -> TIM (AFuncDecl TypeExpr)
annFunc (Func qn a v _ r)
= initVarTypes >+ AFunc qn a v <$> (snd <$> getTypeVariant qn) <*> annRule r
annRule :: Rule -> TIM (ARule TypeExpr)
annRule (Rule vs e) = ARule <$> nextTVar <*> mapES annVar vs <*> annExpr e
annRule (External s) = flip AExternal s <$> nextTVar
annExpr :: Expr -> TIM (AExpr TypeExpr)
annExpr (Var i) = lookupVarType i >+=
maybe (failES err) (\ty -> returnES (AVar ty i))
where err = P.pretty 80 $ P.text "Variable" P.<+> ppVarIndex i
P.<+> P.text "was not initialized with a type"
annExpr (Lit l) = nextTVar >+= \ty -> returnES (ALit ty l)
annExpr (Comb t q es) = flip AComb t <$> nextTVar <*> getTypeVariant q
<*> mapES annExpr es
annExpr (Case t e bs) = flip ACase t <$> nextTVar <*> annExpr e
<*> mapES annBranch bs
annExpr (Or a b) = AOr <$> nextTVar <*> annExpr a <*> annExpr b
annExpr (Let ds e) = ALet <$> nextTVar <*> annBindings ds <*> annExpr e
where annBindings bs = let (vs, es) = unzip bs in
mapES annBound vs >+= \vs' ->
mapES annExpr es >+= \es' ->
returnES (zip vs' es')
annBound v = checkShadowing v >+ annVar v
annExpr (Free vs e) = AFree <$> nextTVar <*> mapES annFree vs <*> annExpr e
where annFree v = checkShadowing v >+ annVar v
annExpr (Typed e ty) = ATyped <$> nextTVar <*> annExpr e <*> freshVariant ty
annVar :: VarIndex -> TIM (VarIndex, TypeExpr)
annVar v = nextTVar >+= \ty -> insertVarType v ty >+ returnES (v, ty)
checkShadowing :: VarIndex -> TIM ()
checkShadowing v = lookupVarType v >+= maybe (returnES ()) (\_ -> failES err)
where err = P.pretty 80 $ P.text "shadowing with variable" P.<+> ppVarIndex v
annBranch :: BranchExpr -> TIM (ABranchExpr TypeExpr)
annBranch (Branch p e) = ABranch <$> annPattern p <*> annExpr e
annPattern :: Pattern -> TIM (APattern TypeExpr)
annPattern (Pattern c vs) = APattern <$> nextTVar <*> getTypeVariant c
<*> mapES annPVar vs
where annPVar v = checkShadowing v >+ annVar v
annPattern (LPattern l) = flip ALPattern l <$> nextTVar
type TypeEqs = [(TypeExpr, TypeExpr)]
(=.=) :: TypeExpr -> TypeExpr -> (TypeExpr, TypeExpr)
ty1 =.= ty2 = (ty1, ty2)
ppTypeEqs :: TypeEqs -> P.Doc
ppTypeEqs = P.vsep . map ppEquation
where ppEquation (l, r) = ppTypeExp l P.<+> P.equals P.<+> ppTypeExp r
(++=) :: TIM [a] -> TIM [a] -> TIM [a]
mxs ++= mys = (++) <$> mxs <*> mys
inferAProg :: AProg TypeExpr -> TIM (AProg TypeExpr)
inferAProg (AProg mid is td fd od)
= (\fd' -> AProg mid is td fd' od) <$> mapES inferFunc fd
inferFuncGroup :: [AFuncDecl TypeExpr] -> TIM [AFuncDecl TypeExpr]
inferFuncGroup fs =
concatMapES (uncurry eqsRule) [(ty, r) | AFunc _ _ _ ty r <- fs] >+= \eqs ->
solve (P.text "functions" P.<+> doc) eqs >+= \ sigma ->
mapES (normalize normFunc . substFunc sigma) fs >+= \afs ->
returnES afs
where doc = P.hsep $ P.punctuate P.comma (map (ppQName . AFC.funcName) fs)
inferFunc :: AFuncDecl TypeExpr -> TIM (AFuncDecl TypeExpr)
inferFunc func@(AFunc _ _ _ ty r) =
eqsRule ty r >+= \ eqs ->
solve (P.text "function" P.<+> ppQName (AFC.funcName func)) eqs >+= \ sigma ->
normalize normFunc (substFunc sigma func)
inferAExpr :: AExpr TypeExpr -> TIM (AExpr TypeExpr)
inferAExpr e = eqsExpr e >+= \eqs ->
solve (P.text "expression" P.<+> ppExp e) eqs >+= \sigma ->
normalize normExpr (substExpr sigma e)
eqsRule :: TypeExpr -> ARule TypeExpr -> TIM TypeEqs
eqsRule ty (ARule ty2 vs e)
= returnES [ty =.= ty2, ty2 =.= foldr1 FuncType (map snd vs ++ [exprType e])]
++= eqsExpr e
eqsRule ty (AExternal ty2 _) = returnES [ty =.= ty2]
eqsExpr :: AExpr TypeExpr -> TIM TypeEqs
eqsExpr (AVar _ _) = returnES []
eqsExpr (ALit ty l) = returnES [ty =.= literalType l]
eqsExpr (AComb ty _ (_, fty) es)
= returnES [fty =.= foldr1 FuncType (map exprType es ++ [ty])]
++= concatMapES eqsExpr es
eqsExpr (ACase ty _ e bs) = eqsExpr e ++= concatMapES (eqsBranch ty e) bs
eqsExpr (AOr ty a b) = returnES [exprType a =.= ty, exprType b =.= ty]
++= eqsExpr a ++= eqsExpr b
eqsExpr (ALet ty bs e)
= returnES [ty =.= exprType e]
++= returnES (map (\ ((_, vty), b) -> vty =.= exprType b) bs)
++= concatMapES eqsExpr (e : map snd bs)
eqsExpr (AFree ty _ e) = returnES [ty =.= exprType e] ++= eqsExpr e
eqsExpr (ATyped ty e tz) = returnES [ty =.= exprType e, ty =.= tz] ++= eqsExpr e
eqsBranch :: TypeExpr -> AExpr TypeExpr -> ABranchExpr TypeExpr -> TIM TypeEqs
eqsBranch ty s (ABranch p be) = returnES [ty =.= exprType be]
++= eqsPattern (exprType s) p ++= eqsExpr be
eqsPattern :: TypeExpr -> APattern TypeExpr -> TIM TypeEqs
eqsPattern ty (APattern pty (_, cty) vs)
= returnES [ty =.= pty, cty =.= foldr1 FuncType (map snd vs ++ [pty])]
eqsPattern ty (ALPattern pty l)
= returnES [ty =.= pty, pty =.= literalType l]
literalType :: Literal -> TypeExpr
literalType (Intc _) = TCons ("Prelude", "Int" ) []
literalType (Floatc _) = TCons ("Prelude", "Float") []
literalType (Charc _) = TCons ("Prelude", "Char" ) []
exprType :: AExpr TypeExpr -> TypeExpr
exprType = AFC.annExpr
solve :: P.Doc -> TypeEqs -> TIM AFCSubst
solve what eqs = case unify (fromTypeEqs eqs) of
Left err -> failES $ P.pretty 80 $ ppUnificationError err
P.<+> P.text "during type inference for:" P.<$$> P.nest 2 what
Right sub -> returnES (mapFM (\_ -> toTypeExpr) sub)
fromTypeEqs :: TypeEqs -> TermEqs String
fromTypeEqs = map (\(a,b) -> (fromTypeExpr a, fromTypeExpr b))
toTypeEqs :: TermEqs String -> TypeEqs
toTypeEqs = map (\(a,b) -> (toTypeExpr a =.= toTypeExpr b))
fromTypeExpr :: TypeExpr -> Term String
fromTypeExpr (TVar n) = TermVar n
fromTypeExpr (TCons t vs) = TermCons (fromQName t) (map fromTypeExpr vs)
fromTypeExpr (FuncType a b) = TermCons "->" [fromTypeExpr a, fromTypeExpr b]
toTypeExpr :: Term String -> TypeExpr
toTypeExpr (TermVar n) = TVar n
toTypeExpr (TermCons t vs)
| t == "->" = FuncType (toTypeExpr (vs !! 0)) (toTypeExpr (vs !! 1))
| otherwise = TCons (toQName t) (map toTypeExpr vs)
fromQName :: QName -> String
fromQName (mod, typ) = mod ++ ";" ++ typ
toQName :: String -> QName
toQName str = (fst split, snd split)
where split = splitFirst str ';'
splitFirst :: [a] -> a -> ([a], [a])
splitFirst [] _ = ([], [])
splitFirst (x:xs) c
| x == c = ([], xs)
| otherwise = (x : fst rest, snd rest)
where rest = splitFirst xs c
ppUnificationError :: UnificationError String -> P.Doc
ppUnificationError (Clash a b)
= P.text "Clash:" P.<+> ppTypeExp (toTypeExpr a) P.<+> P.equals
P.<+> ppTypeExp (toTypeExpr b)
ppUnificationError (OccurCheck v t)
= P.text "OccurCheck: Type variable" P.<+> ppTypeExp (toTypeExpr (TermVar v))
P.<+> P.text "occurs in type" P.<+> ppTypeExp (toTypeExpr t)
type NormState = (Int, FM Int Int)
type Normalize a = a -> ES () NormState a
normalize :: Normalize a -> a -> ES String s a
normalize norm x = case evalES (norm x) (0, emptyFM (<)) of
Left _ -> failES $ "Normalization failed for: " ++ show x
Right x' -> returnES x'
normFunc :: Normalize (AFuncDecl TypeExpr)
normFunc (AFunc f a v t r) = AFunc f a v <$> normType t <*> normRule r
normType :: Normalize TypeExpr
normType (TVar i) = gets >+= \(n, fm) -> case lookupFM fm i of
Nothing -> puts (n + 1, addToFM fm i n) >+ returnES (TVar n)
Just n' -> returnES (TVar n')
normType (TCons q tys) = TCons q <$> mapES normType tys
normType (FuncType a b) = FuncType <$> normType a <*> normType b
normRule :: Normalize (ARule TypeExpr)
normRule (ARule ty vs e) = ARule <$> normType ty <*> mapES normSnd vs
<*> normExpr e
normRule (AExternal ty s) = flip AExternal s <$> normType ty
normExpr :: Normalize (AExpr TypeExpr)
normExpr (AVar t v) = flip AVar v <$> normType t
normExpr (ALit t l) = flip ALit l <$> normType t
normExpr (AComb t ct f es) = flip AComb ct <$> normType t
<*> normSnd f <*> mapES normExpr es
normExpr (ALet t ds e) = ALet <$> normType t <*> mapES normBinding ds
<*> normExpr e
where normBinding (v, b) = (\x y -> (x,y)) <$> normSnd v <*> normExpr b
normExpr (AOr t a b) = AOr <$> normType t <*> normExpr a <*> normExpr b
normExpr (ACase t ct e bs) = flip ACase ct <$> normType t <*> normExpr e
<*> mapES normBranch bs
normExpr (AFree t vs e) = AFree <$> normType t <*> mapES normSnd vs
<*> normExpr e
normExpr (ATyped t e y) = ATyped <$> normType t <*> normExpr e <*> normType y
normSnd :: Normalize (a, TypeExpr)
normSnd (a, ty) = normType ty >+= \ty' -> returnES (a, ty')
normBranch :: Normalize (ABranchExpr TypeExpr)
normBranch (ABranch p e) = ABranch <$> normPattern p <*> normExpr e
normPattern :: Normalize (APattern TypeExpr)
normPattern (APattern t c vs) = APattern <$> normType t <*> normSnd c
<*> mapES normSnd vs
normPattern (ALPattern t l) = flip ALPattern l <$> normType t
|