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