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