@@ -0,0 +1,983 @@
1+-----------------------------------------------------------------------------
2+--
3+-- Module : Language.PureScript.TypeChecker.Types
4+-- Copyright : (c) Phil Freeman 2013
5+-- License : MIT
6+--
7+-- Maintainer : Phil Freeman <paf31@cantab.net>
8+-- Stability : experimental
9+-- Portability :
10+--
11+-- |
12+-- This module implements the type checker
13+--
14+-----------------------------------------------------------------------------
15+
16+{-# OPTIONS_GHC -fno-warn-orphans #-}
17+{-# LANGUAGE DeriveDataTypeable #-}
18+{-# LANGUAGE FlexibleContexts #-}
19+{-# LANGUAGE MultiParamTypeClasses #-}
20+
21+module Language.PureScript.TypeChecker.Types (
22+ typesOf
23+) where
24+
25+{-
26+ The following functions represent the corresponding type checking judgements:
27+
28+ infer
29+ Synthesize a type for a value
30+
31+ check
32+ Check a value has a given type
33+
34+ checkProperties
35+ Check an object with a given type contains specified properties
36+
37+ checkFunctionApplication
38+ Check a function of a given type returns a value of another type when applied to its arguments
39+
40+ subsumes
41+ Check a type subsumes another type
42+-}
43+
44+import Data.List
45+import Data.Maybe (maybeToList, isNothing, isJust, fromMaybe)
46+import qualified Data.Data as D
47+import Data.Generics
48+ (everythingWithContext, mkM, everywhereM, everything, mkT,
49+ something, everywhere, mkQ)
50+
51+import Language.PureScript.Values
52+import Language.PureScript.Types
53+import Language.PureScript.Kinds
54+import Language.PureScript.Names
55+import Language.PureScript.TypeChecker.Monad
56+import Language.PureScript.TypeChecker.Kinds
57+import Language.PureScript.TypeChecker.Synonyms
58+import Language.PureScript.Pretty
59+
60+import Control.Monad.State
61+import Control.Monad.Error
62+import Control.Monad.Reader
63+import Control.Monad.Unify
64+
65+import Control.Applicative
66+import Control.Arrow (Arrow(..))
67+
68+import qualified Data.Map as M
69+import Data.Function (on)
70+import Debug.Trace (trace)
71+
72+instance Partial Type where
73+ unknown = TUnknown
74+ isUnknown (TUnknown u) = Just u
75+ isUnknown _ = Nothing
76+
77+instance Unifiable Check Type where
78+ (=?=) = unifyTypes
79+
80+-- |
81+-- Unify two types, updating the current substitution
82+--
83+unifyTypes :: Type -> Type -> UnifyT Type Check ()
84+unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $ do
85+ unifyTypes' t1 t2
86+ where
87+ unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
88+ unifyTypes' (TUnknown u) t = u =:= t
89+ unifyTypes' t (TUnknown u) = u =:= t
90+ unifyTypes' (SaturatedTypeSynonym name args) ty = do
91+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ args
92+ ty1 `unifyTypes` ty
93+ unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
94+ unifyTypes' (ForAll ident1 ty1 sc1) (ForAll ident2 ty2 sc2) =
95+ case (sc1, sc2) of
96+ (Just sc1', Just sc2') -> do
97+ sko <- newSkolemConstant
98+ let sk1 = skolemize ident1 sko sc1' ty1
99+ let sk2 = skolemize ident2 sko sc2' ty2
100+ sk1 `unifyTypes` sk2
101+ _ -> throwError (prettyPrintType ty1)
102+ unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
103+ sko <- newSkolemConstant
104+ let sk = skolemize ident sko sc ty1
105+ sk `unifyTypes` ty2
106+ unifyTypes' (ForAll _ _ _) _ = throwError "Skolem variable scope is unspecified"
107+ unifyTypes' ty f@(ForAll _ _ _) = f `unifyTypes` ty
108+ unifyTypes' (Object row1) (Object row2) = row1 =?= row2
109+ unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
110+ unifyTypes' (TypeConstructor c1) (TypeConstructor c2) = do
111+ env <- getEnv
112+ Just moduleName <- checkCurrentModule <$> get
113+ guardWith ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".") (typeConstructorsAreEqual env moduleName c1 c2)
114+ unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
115+ t3 `unifyTypes` t5
116+ t4 `unifyTypes` t6
117+ unifyTypes' (Skolem s1 _) (Skolem s2 _) | s1 == s2 = return ()
118+ unifyTypes' r1@(RCons _ _ _) r2 = unifyRows r1 r2
119+ unifyTypes' r1 r2@(RCons _ _ _) = unifyRows r1 r2
120+ unifyTypes' r1@REmpty r2 = unifyRows r1 r2
121+ unifyTypes' r1 r2@REmpty = unifyRows r1 r2
122+ unifyTypes' t3 t4 = throwError $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
123+
124+-- |
125+-- Unify two rows, updating the current substitution
126+--
127+-- Common labels are first identified, and unified. Remaining labels and types are unified with a
128+-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
129+-- error.
130+--
131+unifyRows :: Type -> Type -> UnifyT Type Check ()
132+unifyRows r1 r2 =
133+ let
134+ (s1, r1') = rowToList r1
135+ (s2, r2') = rowToList r2
136+ int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
137+ sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
138+ sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
139+ in do
140+ forM_ int (uncurry (=?=))
141+ unifyRows' sd1 r1' sd2 r2'
142+ where
143+ unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
144+ unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
145+ unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
146+ unifyRows' ((name, ty):row) r others u@(TUnknown un) = do
147+ occursCheck un ty
148+ forM_ row $ \(_, t) -> occursCheck un t
149+ u' <- fresh
150+ u =?= RCons name ty u'
151+ unifyRows' row r others u'
152+ unifyRows' [] REmpty [] REmpty = return ()
153+ unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
154+ unifyRows' [] (Skolem s1 _) [] (Skolem s2 _) | s1 == s2 = return ()
155+ unifyRows' sd3 r3 sd4 r4 = throwError $ "Cannot unify " ++ prettyPrintRow (rowFromList (sd3, r3)) ++ " with " ++ prettyPrintRow (rowFromList (sd4, r4)) ++ "."
156+
157+-- |
158+-- Ensure type constructors are equal after canonicalization
159+--
160+typeConstructorsAreEqual :: Environment -> ModuleName -> Qualified ProperName -> Qualified ProperName -> Bool
161+typeConstructorsAreEqual env moduleName = (==) `on` canonicalizeType moduleName env
162+
163+-- |
164+-- Infer the types of multiple mutually-recursive values, and return elaborated values including
165+-- type class dictionaries and type annotations.
166+--
167+typesOf :: ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
168+typesOf moduleName vals = do
169+ tys <- fmap tidyUp . liftUnify $ do
170+ let
171+ -- Map each declaration to a name/value pair, with an optional type, if the declaration is typed
172+ es = map isTyped vals
173+ -- Filter the typed and untyped declarations
174+ typed = filter (isJust . snd . snd) es
175+ untyped = filter (isNothing . snd . snd) es
176+ -- Make a map of names to typed declarations
177+ typedDict = map (\(ident, (_, Just (ty, _))) -> (ident, ty)) typed
178+ -- Create fresh unification variables for the types of untyped declarations
179+ untypedNames <- replicateM (length untyped) fresh
180+ let
181+ -- Make a map of names to the unification variables of untyped declarations
182+ untypedDict = zip (map fst untyped) untypedNames
183+ -- Create the dictionary of all name/type pairs, which will be added to the environment during type checking
184+ dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable))) $ typedDict ++ untypedDict)
185+ forM es $ \e@(_, (val, _)) -> do
186+ -- If the declaration is a function, it has access to other values in the binding group.
187+ -- If not, the generated code might fail at runtime since those values might be undefined.
188+ let dict' = if isFunction val then dict else M.empty
189+ triple@(_, (val, ty)) <- case e of
190+ -- Typed declarations
191+ (ident, (val, Just (ty, checkType))) -> do
192+ -- Kind check
193+ kind <- liftCheck $ kindOf moduleName ty
194+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
195+ -- Check the type with the new names in scope
196+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
197+ val' <- bindNames dict' $ if checkType
198+ then TypedValue True <$> check val ty' <*> pure ty'
199+ else return (TypedValue False val ty')
200+ return (ident, (val', ty'))
201+ -- Untyped declarations
202+ (ident, (val, Nothing)) -> do
203+ -- Infer the type with the new names in scope
204+ TypedValue _ val' ty <- bindNames dict' $ infer val
205+ ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
206+ return (ident, (TypedValue True val' ty, ty))
207+ -- If run-main is enabled, need to check that Main.main has type Eff eff a for some eff, a
208+ when (moduleName == ModuleName (ProperName "Main") && fst e == Ident "main") $ do
209+ [eff, a] <- replicateM 2 fresh
210+ ty =?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName (ProperName "Eff"))) (ProperName "Eff"))) eff) a
211+ -- Make sure unification variables do not escape
212+ escapeCheck val ty
213+ return triple
214+ forM tys $ \(ident, (val, ty)) -> rethrow (("Error in " ++ show ident ++ ": \n") ++) $ do
215+ -- Replace type class dictionary placeholders with actual dictionaries
216+ val' <- replaceTypeClassDictionaries moduleName val
217+ -- Check skolem variables did not escape their scope
218+ skolemEscapeCheck val'
219+ --
220+ return $ (ident, (overTypes (desaturateAllTypeSynonyms . setifyAll) $ val'
221+ , varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty))
222+ where
223+ -- Apply the substitution that was returned from runUnify to both types and (type-annotated) values
224+ tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
225+
226+-- |
227+-- Check if a value introduces a function
228+--
229+isFunction :: Value -> Bool
230+isFunction (Abs _ _) = True
231+isFunction (TypedValue _ val _) = isFunction val
232+isFunction _ = False
233+
234+-- |
235+-- Check if a value contains a type annotation
236+--
237+isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
238+isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
239+isTyped (name, value) = (name, (value, Nothing))
240+
241+-- |
242+-- Map a function over type annotations appearing inside a value
243+--
244+overTypes :: (Type -> Type) -> Value -> Value
245+overTypes f = everywhere (mkT f)
246+
247+-- |
248+-- Replace type class dictionary placeholders with inferred type class dictionaries
249+--
250+replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
251+replaceTypeClassDictionaries mn = everywhereM (mkM go)
252+ where
253+ go (TypeClassDictionary constraint dicts) = entails mn dicts constraint
254+ go other = return other
255+
256+-- |
257+-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
258+-- return a type class dictionary reference.
259+--
260+entails :: ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, Type) -> Check Value
261+entails moduleName context goal@(className, ty) = do
262+ env <- getEnv
263+ case go env goal of
264+ [] -> throwError $ "No " ++ show className ++ " instance found for " ++ prettyPrintType ty
265+ (dict : _) -> return dict
266+ where
267+ go env (className', ty') =
268+ [ mkDictionary (canonicalizeDictionary tcd) args
269+ | tcd <- context
270+ , filterModule tcd
271+ , typeConstructorsAreEqual env moduleName className' (tcdClassName tcd)
272+ , subst <- maybeToList $ typeHeadsAreEqual moduleName env ty' (tcdInstanceType tcd)
273+ , args <- solveSubgoals env subst (tcdDependencies tcd) ]
274+ solveSubgoals :: Environment -> [(String, Type)] -> Maybe [(Qualified ProperName, Type)] -> [Maybe [Value]]
275+ solveSubgoals _ _ Nothing = return Nothing
276+ solveSubgoals env subst (Just subgoals) = do
277+ dict <- mapM (go env) (replaceAllTypeVars subst subgoals)
278+ return $ Just dict
279+ mkDictionary :: Qualified Ident -> Maybe [Value] -> Value
280+ mkDictionary fnName Nothing = Var fnName
281+ mkDictionary fnName (Just dicts) = foldl App (Var fnName) dicts
282+ filterModule :: TypeClassDictionaryInScope -> Bool
283+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
284+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
285+ filterModule _ = False
286+ canonicalizeDictionary :: TypeClassDictionaryInScope -> Qualified Ident
287+ canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDRegular, tcdName = nm }) = nm
288+ canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDAlias nm }) = nm
289+
290+-- |
291+-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
292+-- and return a substitution from type variables to types which makes the type heads unify.
293+--
294+typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
295+typeHeadsAreEqual _ _ (Skolem s1 _) (Skolem s2 _) | s1 == s2 = Just []
296+typeHeadsAreEqual _ _ (TypeVar v) t = Just [(v, t)]
297+typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
298+typeHeadsAreEqual m e (TypeConstructor c1) (TypeConstructor c2) | typeConstructorsAreEqual e m c1 c2 = Just []
299+typeHeadsAreEqual m e (TypeApp h1 (TypeVar v)) (TypeApp h2 arg) = (:) (v, arg) <$> typeHeadsAreEqual m e h1 h2
300+typeHeadsAreEqual m e t1@(TypeApp _ _) t2@(TypeApp _ (TypeVar _)) = typeHeadsAreEqual m e t2 t1
301+typeHeadsAreEqual _ _ _ _ = Nothing
302+
303+-- |
304+-- Ensure unsolved unification variables do not escape
305+--
306+escapeCheck :: Value -> Type -> UnifyT Type Check ()
307+escapeCheck value ty = do
308+ subst <- unifyCurrentSubstitution <$> UnifyT get
309+ let visibleUnknowns = nub $ unknowns $ subst $? ty
310+ let allUnknowns = findAllTypes value
311+ forM_ allUnknowns $ \t -> do
312+ let unsolvedUnknowns = nub . unknowns $ subst $? t
313+ guardWith "Escape check fails" $ null $ unsolvedUnknowns \\ visibleUnknowns
314+
315+-- |
316+-- Find all type annotations occuring inside a value
317+--
318+findAllTypes :: Value -> [Type]
319+findAllTypes = everything (++) (mkQ [] go)
320+ where
321+ go (TypedValue _ _ ty) = [ty]
322+ go _ = []
323+
324+-- |
325+-- Ensure skolem variables do not escape their scope
326+--
327+skolemEscapeCheck :: Value -> Check ()
328+skolemEscapeCheck (TypedValue False _ _) = return ()
329+skolemEscapeCheck root@(TypedValue _ _ _) =
330+ case everythingWithContext [] (++) (mkQ ((,) []) go) root of
331+ [] -> return ()
332+ ((binding, val) : _) -> throwError $ "Rigid/skolem type variable bound by " ++ maybe "<unknown>" prettyPrintValue binding ++ " has escaped at " ++ prettyPrintValue val
333+ where
334+ go :: Value -> [(SkolemScope, Value)] -> ([(Maybe Value, Value)], [(SkolemScope, Value)])
335+ go val@(TypedValue _ _ (ForAll _ _ (Just sco))) scos = ([], (sco, val) : scos)
336+ go val@(TypedValue _ _ ty) scos = case collectSkolems ty \\ map fst scos of
337+ (sco : _) -> ([(findBindingScope sco, val)], scos)
338+ _ -> ([], scos)
339+ where
340+ collectSkolems :: Type -> [SkolemScope]
341+ collectSkolems = nub . everything (++) (mkQ [] collect)
342+ where
343+ collect (Skolem _ scope) = [scope]
344+ collect _ = []
345+ go _ scos = ([], scos)
346+ findBindingScope :: SkolemScope -> Maybe Value
347+ findBindingScope sco = something (mkQ Nothing go) root
348+ where
349+ go val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = Just val
350+ go _ = Nothing
351+skolemEscapeCheck val = throwError $ "Untyped value passed to skolemEscapeCheck: " ++ prettyPrintValue val
352+
353+-- |
354+-- Ensure a row contains no duplicate labels
355+--
356+setify :: Type -> Type
357+setify = rowFromList . first (M.toList . M.fromList) . rowToList
358+
359+-- |
360+-- \"Setify\" all rows occuring inside a value
361+--
362+setifyAll :: (D.Data d) => d -> d
363+setifyAll = everywhere (mkT setify)
364+
365+-- |
366+-- Replace outermost unsolved unification variables with named type variables
367+--
368+varIfUnknown :: Type -> Type
369+varIfUnknown ty =
370+ let unks = nub $ unknowns ty
371+ toName = (:) 't' . show
372+ ty' = everywhere (mkT typeToVar) $ ty
373+ typeToVar :: Type -> Type
374+ typeToVar (TUnknown (Unknown u)) = TypeVar (toName u)
375+ typeToVar t = t
376+ in mkForAll (sort . map (toName . runUnknown) $ unks) ty'
377+
378+-- |
379+-- Replace named type variables with types
380+--
381+replaceAllTypeVars :: (D.Data d) => [(String, Type)] -> d -> d
382+replaceAllTypeVars = foldl' (\f (name, ty) -> replaceTypeVars name ty . f) id
383+
384+-- |
385+-- Replace named type variables with new unification variables
386+--
387+instantiatePolyTypeWithUnknowns :: Value -> Type -> UnifyT Type Check (Value, Type)
388+instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
389+ ty' <- replaceVarWithUnknown ident ty
390+ instantiatePolyTypeWithUnknowns val ty'
391+instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
392+ env <- getEnv
393+ Just moduleName <- checkCurrentModule <$> get
394+ dicts <- getTypeClassDictionaries
395+ (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
396+ return (foldl App val (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints)), ty')
397+instantiatePolyTypeWithUnknowns val ty = return (val, ty)
398+
399+-- |
400+-- Replace a single type variable with a new unification variable
401+--
402+replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
403+replaceVarWithUnknown ident ty = do
404+ tu <- fresh
405+ return $ replaceTypeVars ident tu $ ty
406+
407+-- |
408+-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
409+-- better error messages during unification.
410+--
411+replaceAllTypeSynonyms :: (Functor m, MonadState CheckState m, MonadError String m) => (D.Data d) => d -> m d
412+replaceAllTypeSynonyms d = do
413+ env <- getEnv
414+ Just moduleName <- checkCurrentModule <$> get
415+ let syns = map (\((path, name), (args, _)) -> ((path, name), length args)) . M.toList $ typeSynonyms env
416+ either throwError return $ saturateAllTypeSynonyms env moduleName syns d
417+
418+-- |
419+-- \"Desaturate\" @SaturatedTypeSynonym@s
420+--
421+desaturateAllTypeSynonyms :: (D.Data d) => d -> d
422+desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
423+ where
424+ replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
425+ replaceSaturatedTypeSynonym t = t
426+
427+-- |
428+-- Replace a type synonym and its arguments with the aliased type
429+--
430+expandTypeSynonym :: Qualified ProperName -> [Type] -> UnifyT Type Check Type
431+expandTypeSynonym name args = do
432+ env <- getEnv
433+ Just moduleName <- checkCurrentModule <$> get
434+ case M.lookup (canonicalizeType moduleName env name) (typeSynonyms env) of
435+ Just (synArgs, body) -> return $ replaceAllTypeVars (zip synArgs args) body
436+ Nothing -> error "Type synonym was not defined"
437+
438+-- |
439+-- Ensure a set of property names and value does not contain duplicate labels
440+--
441+ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
442+ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
443+
444+-- |
445+-- Infer a type for a value, rethrowing any error to provide a more useful error message
446+--
447+infer :: Value -> UnifyT Type Check Value
448+infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
449+
450+-- |
451+-- Infer a type for a value
452+--
453+infer' :: Value -> UnifyT Type Check Value
454+infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
455+infer' v@(StringLiteral _) = return $ TypedValue True v tyString
456+infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
457+infer' (ArrayLiteral vals) = do
458+ ts <- mapM infer vals
459+ els <- fresh
460+ forM_ ts $ \(TypedValue _ _ t) -> els =?= TypeApp tyArray t
461+ return $ TypedValue True (ArrayLiteral ts) els
462+infer' (ObjectLiteral ps) = do
463+ ensureNoDuplicateProperties ps
464+ ts <- mapM (infer . snd) ps
465+ let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
466+ ty = Object $ rowFromList (fields, REmpty)
467+ return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
468+infer' (ObjectUpdate o ps) = do
469+ ensureNoDuplicateProperties ps
470+ row <- fresh
471+ newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
472+ let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
473+ oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
474+ let oldTy = Object $ rowFromList (oldTys, row)
475+ o' <- TypedValue True <$> check o oldTy <*> pure oldTy
476+ return $ TypedValue True (ObjectUpdate o' newVals) $ Object $ rowFromList (newTys, row)
477+infer' (Accessor prop val) = do
478+ typed@(TypedValue _ _ objTy) <- infer val
479+ propTy <- inferProperty objTy prop
480+ case propTy of
481+ Nothing -> do
482+ field <- fresh
483+ rest <- fresh
484+ _ <- subsumes Nothing objTy (Object (RCons prop field rest))
485+ return $ TypedValue True (Accessor prop typed) field
486+ Just ty -> return $ TypedValue True (Accessor prop typed) ty
487+infer' (Abs arg ret) = do
488+ ty <- fresh
489+ Just moduleName <- checkCurrentModule <$> get
490+ bindLocalVariables moduleName [(arg, ty)] $ do
491+ body@(TypedValue _ _ bodyTy) <- infer' ret
492+ return $ TypedValue True (Abs arg body) $ function ty bodyTy
493+infer' (App f arg) = do
494+ f'@(TypedValue _ _ ft) <- infer f
495+ (ret, app) <- checkFunctionApplication f' ft arg
496+ return $ TypedValue True app ret
497+infer' (Var var) = do
498+ Just moduleName <- checkCurrentModule <$> get
499+ ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
500+ case ty of
501+ ConstrainedType constraints ty' -> do
502+ env <- getEnv
503+ dicts <- getTypeClassDictionaries
504+ return $ TypedValue True (foldl App (Var var) (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))) ty'
505+ _ -> return $ TypedValue True (Var var) ty
506+infer' (Block ss) = do
507+ ret <- fresh
508+ (allCodePathsReturn, _, ss') <- checkBlock M.empty ret ss
509+ guardWith "Block is missing a return statement" allCodePathsReturn
510+ return $ TypedValue True (Block ss') ret
511+infer' v@(Constructor c) = do
512+ env <- getEnv
513+ Just moduleName <- checkCurrentModule <$> get
514+ case M.lookup (qualify moduleName c) (dataConstructors env) of
515+ Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
516+ Just (ty, _) -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
517+ return $ TypedValue True v ty'
518+infer' (Case vals binders) = do
519+ ts <- mapM infer vals
520+ ret <- fresh
521+ binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
522+ return $ TypedValue True (Case ts binders') ret
523+infer' (IfThenElse cond th el) = do
524+ cond' <- check cond tyBoolean
525+ v2@(TypedValue _ _ t2) <- infer th
526+ v3@(TypedValue _ _ t3) <- infer el
527+ t2 =?= t3
528+ return $ TypedValue True (IfThenElse cond' v2 v3) t2
529+infer' (TypedValue checkType val ty) = do
530+ Just moduleName <- checkCurrentModule <$> get
531+ kind <- liftCheck $ kindOf moduleName ty
532+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
533+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
534+ val' <- if checkType then check val ty' else return val
535+ return $ TypedValue True val' ty'
536+infer' _ = error "Invalid argument to infer"
537+
538+-- |
539+-- Infer the type of a property inside a record with a given type
540+--
541+inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
542+inferProperty (Object row) prop = do
543+ let (props, _) = rowToList row
544+ return $ lookup prop props
545+inferProperty (SaturatedTypeSynonym name args) prop = do
546+ replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
547+ inferProperty replaced prop
548+inferProperty (ForAll ident ty _) prop = do
549+ replaced <- replaceVarWithUnknown ident ty
550+ inferProperty replaced prop
551+inferProperty _ _ = return Nothing
552+
553+-- |
554+-- Infer the types of variables brought into scope by a binder
555+--
556+inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
557+inferBinder _ NullBinder = return M.empty
558+inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
559+inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
560+inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
561+inferBinder val (VarBinder name) = return $ M.singleton name val
562+inferBinder val (NullaryBinder ctor) = do
563+ env <- getEnv
564+ Just moduleName <- checkCurrentModule <$> get
565+ case M.lookup (qualify moduleName ctor) (dataConstructors env) of
566+ Just (ty, _) -> do
567+ _ <- subsumes Nothing ty val
568+ return M.empty
569+ _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
570+inferBinder val (UnaryBinder ctor binder) = do
571+ env <- getEnv
572+ Just moduleName <- checkCurrentModule <$> get
573+ case M.lookup (qualify moduleName ctor) (dataConstructors env) of
574+ Just (ty, _) -> do
575+ (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contains constraints") ty
576+ case fn of
577+ TypeApp (TypeApp t obj) ret | t == tyFunction -> do
578+ _ <- subsumes Nothing val ret
579+ inferBinder obj binder
580+ _ -> throwError $ "Constructor " ++ show ctor ++ " is not a unary constructor"
581+ _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
582+inferBinder val (ObjectBinder props) = do
583+ row <- fresh
584+ rest <- fresh
585+ m1 <- inferRowProperties row rest props
586+ val =?= Object row
587+ return m1
588+ where
589+ inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
590+ inferRowProperties nrow row [] = nrow =?= row >> return M.empty
591+ inferRowProperties nrow row ((name, binder):binders) = do
592+ propTy <- fresh
593+ m1 <- inferBinder propTy binder
594+ m2 <- inferRowProperties nrow (RCons name propTy row) binders
595+ return $ m1 `M.union` m2
596+inferBinder val (ArrayBinder binders) = do
597+ el <- fresh
598+ m1 <- M.unions <$> mapM (inferBinder el) binders
599+ val =?= TypeApp tyArray el
600+ return m1
601+inferBinder val (ConsBinder headBinder tailBinder) = do
602+ el <- fresh
603+ m1 <- inferBinder el headBinder
604+ m2 <- inferBinder val tailBinder
605+ val =?= TypeApp tyArray el
606+ return $ m1 `M.union` m2
607+inferBinder val (NamedBinder name binder) = do
608+ m <- inferBinder val binder
609+ return $ M.insert name val m
610+
611+-- |
612+-- Check the types of the return values in a set of binders in a case statement
613+--
614+checkBinders :: [Type] -> Type -> [([Binder], Maybe Guard, Value)] -> UnifyT Type Check [([Binder], Maybe Guard, Value)]
615+checkBinders _ _ [] = return []
616+checkBinders nvals ret ((binders, grd, val):bs) = do
617+ Just moduleName <- checkCurrentModule <$> get
618+ m1 <- M.unions <$> zipWithM inferBinder nvals binders
619+ r <- bindLocalVariables moduleName (M.toList m1) $ do
620+ val' <- TypedValue True <$> check val ret <*> pure ret
621+ case grd of
622+ Nothing -> return (binders, Nothing, val')
623+ Just g -> do
624+ g' <- check g tyBoolean
625+ return (binders, Just g', val')
626+ rs <- checkBinders nvals ret bs
627+ return $ r : rs
628+
629+-- |
630+-- Check that a local variable name is not already used
631+--
632+assignVariable :: Ident -> UnifyT Type Check ()
633+assignVariable name = do
634+ env <- checkEnv <$> get
635+ Just moduleName <- checkCurrentModule <$> get
636+ case M.lookup (moduleName, name) (names env) of
637+ Just _ -> UnifyT . lift . throwError $ "Variable with name " ++ show name ++ " already exists."
638+ _ -> return ()
639+
640+-- |
641+-- Check the type of the return values of a statement, returning whether or not the statement returns on
642+-- all code paths
643+--
644+checkStatement :: M.Map Ident Type -> Type -> Statement -> UnifyT Type Check (Bool, M.Map Ident Type, Statement)
645+checkStatement mass _ (VariableIntroduction name val) = do
646+ assignVariable name
647+ val'@(TypedValue _ _ t) <- infer val
648+ return (False, M.insert name t mass, VariableIntroduction name val')
649+checkStatement mass _ (Assignment ident val) = do
650+ val'@(TypedValue _ _ t) <- infer val
651+ case M.lookup ident mass of
652+ Nothing -> throwError $ "No local variable with name " ++ show ident
653+ Just ty -> do t =?= ty
654+ return (False, mass, Assignment ident val')
655+checkStatement mass ret (While val inner) = do
656+ val' <- check val tyBoolean
657+ (allCodePathsReturn, _, inner') <- checkBlock mass ret inner
658+ return (allCodePathsReturn, mass, While val' inner')
659+checkStatement mass ret (If ifst) = do
660+ (allCodePathsReturn, ifst') <- checkIfStatement mass ret ifst
661+ return (allCodePathsReturn, mass, If ifst')
662+checkStatement mass ret (For ident start end inner) = do
663+ Just moduleName <- checkCurrentModule <$> get
664+ assignVariable ident
665+ start' <- check start tyNumber
666+ end' <- check end tyNumber
667+ (allCodePathsReturn, _, inner') <- bindLocalVariables moduleName [(ident, tyNumber)] $ checkBlock mass ret inner
668+ return (allCodePathsReturn, mass, For ident start' end' inner')
669+checkStatement mass ret (Return val) = do
670+ val' <- check val ret
671+ return (True, mass, Return (TypedValue True val' ret))
672+
673+-- |
674+-- Check the type of an if-then-else statement
675+--
676+checkIfStatement :: M.Map Ident Type -> Type -> IfStatement -> UnifyT Type Check (Bool, IfStatement)
677+checkIfStatement mass ret (IfStatement val thens Nothing) = do
678+ val' <- check val tyBoolean
679+ (_, _, thens') <- checkBlock mass ret thens
680+ return (False, IfStatement val' thens' Nothing)
681+checkIfStatement mass ret (IfStatement val thens (Just elses)) = do
682+ val' <- check val tyBoolean
683+ (allCodePathsReturn1, _, thens') <- checkBlock mass ret thens
684+ (allCodePathsReturn2, elses') <- checkElseStatement mass ret elses
685+ return (allCodePathsReturn1 && allCodePathsReturn2, IfStatement val' thens' (Just elses'))
686+
687+-- |
688+-- Check the type of an else statement
689+--
690+checkElseStatement :: M.Map Ident Type -> Type -> ElseStatement -> UnifyT Type Check (Bool, ElseStatement)
691+checkElseStatement mass ret (Else elses) = do
692+ (allCodePathsReturn, _, elses') <- checkBlock mass ret elses
693+ return (allCodePathsReturn, Else elses')
694+checkElseStatement mass ret (ElseIf ifst) = (id *** ElseIf) <$> checkIfStatement mass ret ifst
695+
696+-- |
697+-- Check the type of the return value of a block of statements
698+--
699+checkBlock :: M.Map Ident Type -> Type -> [Statement] -> UnifyT Type Check (Bool, M.Map Ident Type, [Statement])
700+checkBlock mass _ [] = return (False, mass, [])
701+checkBlock mass ret (s:ss) = do
702+ Just moduleName <- checkCurrentModule <$> get
703+ (b1, mass1, s') <- checkStatement mass ret s
704+ bindLocalVariables moduleName (M.toList mass1) $ case (b1, ss) of
705+ (True, []) -> return (True, mass1, [s'])
706+ (True, _) -> throwError "Unreachable code"
707+ (False, ss') -> do
708+ (b, m, ss'') <- checkBlock mass1 ret ss'
709+ return (b, m, s':ss'')
710+
711+-- |
712+-- Generate a new skolem constant
713+--
714+newSkolemConstant :: UnifyT Type Check Int
715+newSkolemConstant = runUnknown <$> fresh'
716+
717+-- |
718+-- Generate a new skolem scope
719+--
720+newSkolemScope :: UnifyT Type Check SkolemScope
721+newSkolemScope = SkolemScope . runUnknown <$> fresh'
722+
723+-- |
724+-- Skolemize a type variable by replacing its instances with fresh skolem constants
725+--
726+skolemize :: (D.Data d) => String -> Int -> SkolemScope -> d -> d
727+skolemize ident sko scope d = replaceTypeVars ident (Skolem sko scope) d
728+
729+-- |
730+-- Introduce skolem scope at every occurence of a ForAll
731+--
732+introduceSkolemScope :: Type -> UnifyT Type Check Type
733+introduceSkolemScope = everywhereM (mkM go)
734+ where
735+ go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
736+ go other = return other
737+
738+-- |
739+-- Check the type of a value, rethrowing errors to provide a better error message
740+--
741+check :: Value -> Type -> UnifyT Type Check Value
742+check val ty = rethrow errorMessage $ check' val ty
743+ where
744+ errorMessage msg =
745+ "Error checking type of term " ++
746+ prettyPrintValue val ++
747+ " against type " ++
748+ prettyPrintType ty ++
749+ ":\n" ++
750+ msg
751+
752+-- |
753+-- Check the type of a value
754+--
755+check' :: Value -> Type -> UnifyT Type Check Value
756+check' val t@(ForAll ident ty _) = do
757+ scope <- newSkolemScope
758+ sko <- newSkolemConstant
759+ let sk = skolemize ident sko scope ty
760+ val' <- check val sk
761+ return $ TypedValue True val' (ForAll ident ty (Just scope))
762+check' val t@(ConstrainedType constraints ty) = do
763+ env <- getEnv
764+ Just moduleName <- checkCurrentModule <$> get
765+ dictNames <- flip mapM constraints $ \(Qualified _ (ProperName className), _) -> do
766+ n <- liftCheck freshDictionaryName
767+ return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
768+ val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
769+ TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
770+ (qualifyAllUnqualifiedNames moduleName env constraints)) $
771+ check val ty
772+ return $ TypedValue True (foldr Abs val' dictNames) t
773+check' val t@(SaturatedTypeSynonym name args) = do
774+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
775+ val' <- check val ty
776+ return $ TypedValue True val' ty
777+check' val u@(TUnknown _) = do
778+ val'@(TypedValue _ _ ty) <- infer val
779+ -- Don't unify an unknown with an inferred polytype
780+ (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
781+ ty' =?= u
782+ return $ TypedValue True val'' ty'
783+check' v@(NumericLiteral _) t | t == tyNumber =
784+ return $ TypedValue True v t
785+check' v@(StringLiteral _) t | t == tyString =
786+ return $ TypedValue True v t
787+check' v@(BooleanLiteral _) t | t == tyBoolean =
788+ return $ TypedValue True v t
789+check' (ArrayLiteral vals) t@(TypeApp a ty) | a == tyArray = do
790+ arr <- ArrayLiteral <$> forM vals (\val -> check val ty)
791+ return $ TypedValue True arr t
792+check' (Abs arg ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
793+ Just moduleName <- checkCurrentModule <$> get
794+ ret' <- bindLocalVariables moduleName [(arg, argTy)] $ check ret retTy
795+ return $ TypedValue True (Abs arg ret') ty
796+check' (App f arg) ret = do
797+ f'@(TypedValue _ _ ft) <- infer f
798+ (ret', app) <- checkFunctionApplication f' ft arg
799+ subsumes Nothing ret' ret
800+ return $ TypedValue True app ret
801+check' v@(Var var) ty = do
802+ Just moduleName <- checkCurrentModule <$> get
803+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
804+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
805+ v' <- subsumes (Just v) repl ty'
806+ case v' of
807+ Nothing -> throwError "Unable to check type subsumption"
808+ Just v'' -> return $ TypedValue True v'' ty'
809+check' (TypedValue checkType val ty1) ty2 = do
810+ Just moduleName <- checkCurrentModule <$> get
811+ kind <- liftCheck $ kindOf moduleName ty1
812+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
813+ val' <- subsumes (Just val) ty1 ty2
814+ case val' of
815+ Nothing -> throwError "Unable to check type subsumption"
816+ Just val'' -> do
817+ val''' <- if checkType then check val'' ty1 else return val''
818+ return $ TypedValue checkType (TypedValue True val''' ty1) ty2
819+check' (Case vals binders) ret = do
820+ vals' <- mapM infer vals
821+ let ts = map (\(TypedValue _ _ t) -> t) vals'
822+ binders' <- checkBinders ts ret binders
823+ return $ TypedValue True (Case vals' binders') ret
824+check' (IfThenElse cond th el) ty = do
825+ cond' <- check cond tyBoolean
826+ th' <- check th ty
827+ el' <- check el ty
828+ return $ TypedValue True (IfThenElse cond' th' el') ty
829+check' (ObjectLiteral ps) t@(Object row) = do
830+ ensureNoDuplicateProperties ps
831+ ps' <- checkProperties ps row False
832+ return $ TypedValue True (ObjectLiteral ps') t
833+check' (ObjectUpdate obj ps) t@(Object row) = do
834+ ensureNoDuplicateProperties ps
835+ us <- zip (map fst ps) <$> replicateM (length ps) fresh
836+ let (propsToCheck, rest) = rowToList row
837+ propsToRemove = map fst ps
838+ remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
839+ obj' <- check obj (Object (rowFromList (us ++ remainingProps, rest)))
840+ ps' <- checkProperties ps row True
841+ return $ TypedValue True (ObjectUpdate obj' ps') t
842+check' (Accessor prop val) ty = do
843+ rest <- fresh
844+ val' <- check val (Object (RCons prop ty rest))
845+ return $ TypedValue True (Accessor prop val') ty
846+check' (Block ss) ret = do
847+ (allCodePathsReturn, _, ss') <- checkBlock M.empty ret ss
848+ guardWith "Block is missing a return statement" allCodePathsReturn
849+ return $ TypedValue True (Block ss') ret
850+check' (Constructor c) ty = do
851+ env <- getEnv
852+ Just moduleName <- checkCurrentModule <$> get
853+ case M.lookup (qualify moduleName c) (dataConstructors env) of
854+ Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
855+ Just (ty1, _) -> do
856+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
857+ _ <- subsumes Nothing repl ty
858+ return $ TypedValue True (Constructor c) ty
859+check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
860+
861+-- |
862+-- Check the type of a collection of named record fields
863+--
864+-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
865+--
866+checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Type Check [(String, Value)]
867+checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
868+ go [] [] REmpty = return []
869+ go [] [] u@(TUnknown _) = do u =?= REmpty
870+ return []
871+ go [] [] (Skolem _ _) | lax = return []
872+ go [] ((p, _): _) _ | lax = return []
873+ | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
874+ go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
875+ go ((p,v):ps') [] u@(TUnknown _) = do
876+ v'@(TypedValue _ _ ty) <- infer v
877+ rest <- fresh
878+ u =?= RCons p ty rest
879+ ps'' <- go ps' [] rest
880+ return $ (p, v') : ps''
881+ go ((p,v):ps') ts r =
882+ case lookup p ts of
883+ Nothing -> do
884+ v'@(TypedValue _ _ ty) <- infer v
885+ rest <- fresh
886+ r =?= RCons p ty rest
887+ ps'' <- go ps' ts rest
888+ return $ (p, v') : ps''
889+ Just ty -> do
890+ v' <- check v ty
891+ ps'' <- go ps' (delete (p, ty) ts) r
892+ return $ (p, v') : ps''
893+ go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
894+
895+-- |
896+-- Check the type of a function application, rethrowing errors to provide a better error message
897+--
898+checkFunctionApplication :: Value -> Type -> Value -> UnifyT Type Check (Type, Value)
899+checkFunctionApplication fn fnTy arg = rethrow errorMessage $ checkFunctionApplication' fn fnTy arg
900+ where
901+ errorMessage msg = "Error applying function of type "
902+ ++ prettyPrintType fnTy
903+ ++ " to argument " ++ prettyPrintValue arg
904+ ++ ":\n" ++ msg
905+
906+-- |
907+-- Check the type of a function application
908+--
909+checkFunctionApplication' :: Value -> Type -> Value -> UnifyT Type Check (Type, Value)
910+checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg = do
911+ tyFunction' =?= tyFunction
912+ arg' <- check arg argTy
913+ return (retTy, App fn arg')
914+checkFunctionApplication' fn (ForAll ident ty _) arg = do
915+ replaced <- replaceVarWithUnknown ident ty
916+ checkFunctionApplication fn replaced arg
917+checkFunctionApplication' fn u@(TUnknown _) arg = do
918+ arg' <- do
919+ TypedValue _ v t <- infer arg
920+ (v', t') <- instantiatePolyTypeWithUnknowns arg t
921+ return $ TypedValue True v' t'
922+ let ty = (\(TypedValue _ _ t) -> t) arg'
923+ ret <- fresh
924+ u =?= function ty ret
925+ return (ret, App fn arg')
926+checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg = do
927+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
928+ checkFunctionApplication fn ty arg
929+checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg = do
930+ env <- getEnv
931+ dicts <- getTypeClassDictionaries
932+ Just moduleName <- checkCurrentModule <$> get
933+ checkFunctionApplication' (foldl App fn (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))) fnTy arg
934+checkFunctionApplication' _ fnTy arg = throwError $ "Cannot apply a function of type "
935+ ++ prettyPrintType fnTy
936+ ++ " to argument " ++ prettyPrintValue arg
937+
938+-- |
939+-- Check whether one type subsumes another, rethrowing errors to provide a better error message
940+--
941+subsumes :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
942+subsumes val ty1 ty2 = rethrow errorMessage $ subsumes' val ty1 ty2
943+ where
944+ errorMessage msg = "Error checking that type "
945+ ++ prettyPrintType ty1
946+ ++ " subsumes type "
947+ ++ prettyPrintType ty2
948+ ++ ":\n" ++ msg
949+
950+-- |
951+-- Check whether one type subsumes another
952+--
953+subsumes' :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
954+subsumes' val (ForAll ident ty1 _) ty2 = do
955+ replaced <- replaceVarWithUnknown ident ty1
956+ subsumes val replaced ty2
957+subsumes' val ty1 (ForAll ident ty2 sco) =
958+ case sco of
959+ Just sco' -> do
960+ sko <- newSkolemConstant
961+ let sk = skolemize ident sko sco' ty2
962+ subsumes val ty1 sk
963+ Nothing -> throwError "Skolem variable scope is unspecified"
964+subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
965+ subsumes Nothing arg2 arg1
966+ subsumes Nothing ret1 ret2
967+ return val
968+subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
969+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
970+ subsumes val ty1 ty2
971+subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
972+ ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
973+ subsumes val ty1 ty2
974+subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
975+ env <- getEnv
976+ dicts <- getTypeClassDictionaries
977+ Just moduleName <- checkCurrentModule <$> get
978+ _ <- subsumes' Nothing ty1 ty2
979+ return . Just $ foldl App val (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))
980+subsumes' val ty1 ty2 = do
981+ ty1 =?= ty2
982+ return val
983+