@@ -0,0 +1,1089 @@
1+-----------------------------------------------------------------------------
3+-- Module : Language.PureScript.TypeChecker.Types
4+-- Copyright : (c) Phil Freeman 2013
7+-- Maintainer : Phil Freeman <paf31@cantab.net>
8+-- Stability : experimental
12+-- This module implements the type checker
14+-----------------------------------------------------------------------------
16+{-# OPTIONS_GHC -fno-warn-orphans #-}
17+{-# LANGUAGE FlexibleInstances #-}
18+{-# LANGUAGE FlexibleContexts #-}
19+{-# LANGUAGE MultiParamTypeClasses #-}
21+module Language.PureScript.TypeChecker.Types (
26+ The following functions represent the corresponding type checking judgements:
29+ Synthesize a type for a value
32+ Check a value has a given type
35+ Check an object with a given type contains specified properties
37+ checkFunctionApplication
38+ Check a function of a given type returns a value of another type when applied to its arguments
41+ Check a type subsumes another type
45+import Data.Maybe (maybeToList, isNothing, isJust, fromMaybe)
46+import qualified Data.Data as D
48+ (everythingWithContext, mkM, everywhereM, everything, mkT,
49+ something, everywhere, mkQ)
50+import Data.Generics.Extras
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 Language.PureScript.Errors
63+import qualified Language.PureScript.Constants as C
65+import Control.Monad.State
66+import Control.Monad.Error
67+import Control.Monad.Unify
69+import Control.Applicative
70+import Control.Arrow (Arrow(..))
72+import qualified Data.Map as M
73+import Data.Function (on)
74+import Data.Ord (comparing)
75+import Data.Monoid ((<>))
77+instance Partial Type where
79+ isUnknown (TUnknown u) = Just u
80+ isUnknown _ = Nothing
82+instance Unifiable Check Type where
86+-- Unify two types, updating the current substitution
88+unifyTypes :: Type -> Type -> UnifyT Type Check ()
89+unifyTypes t1 t2 = rethrow (mkErrorStack ("Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2) Nothing <>) $
92+ unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
93+ unifyTypes' (TUnknown u) t = u =:= t
94+ unifyTypes' t (TUnknown u) = u =:= t
95+ unifyTypes' (SaturatedTypeSynonym name args) ty = do
96+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ args
98+ unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
99+ unifyTypes' (ForAll ident1 ty1 sc1) (ForAll ident2 ty2 sc2) =
101+ (Just sc1', Just sc2') -> do
102+ sko <- newSkolemConstant
103+ let sk1 = skolemize ident1 sko sc1' ty1
104+ let sk2 = skolemize ident2 sko sc2' ty2
105+ sk1 `unifyTypes` sk2
106+ _ -> error "Skolemized type variable was not given a scope"
107+ unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
108+ sko <- newSkolemConstant
109+ let sk = skolemize ident sko sc ty1
111+ unifyTypes' ForAll{} _ = throwError . strMsg $ "Skolem variable scope is unspecified"
112+ unifyTypes' ty f@ForAll{} = f `unifyTypes` ty
113+ unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
114+ unifyTypes' (TypeConstructor c1) (TypeConstructor c2) =
115+ guardWith (strMsg ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".")) (c1 == c2)
116+ unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
119+ unifyTypes' (Skolem s1 _) (Skolem s2 _) | s1 == s2 = return ()
120+ unifyTypes' r1@RCons{} r2 = unifyRows r1 r2
121+ unifyTypes' r1 r2@RCons{} = unifyRows r1 r2
122+ unifyTypes' r1@REmpty r2 = unifyRows r1 r2
123+ unifyTypes' r1 r2@REmpty = unifyRows r1 r2
124+ unifyTypes' t@(ConstrainedType _ _) _ = throwError . strMsg $ "Attempted to unify a constrained type " ++ prettyPrintType t ++ " with another type."
125+ unifyTypes' t3 t4@(ConstrainedType _ _) = unifyTypes' t4 t3
126+ unifyTypes' t3 t4 = throwError . strMsg $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
129+-- Unify two rows, updating the current substitution
131+-- Common labels are first identified, and unified. Remaining labels and types are unified with a
132+-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
135+unifyRows :: Type -> Type -> UnifyT Type Check ()
138+ (s1, r1') = rowToList r1
139+ (s2, r2') = rowToList r2
140+ int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
141+ sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
142+ sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
144+ forM_ int (uncurry (=?=))
145+ unifyRows' sd1 r1' sd2 r2'
147+ unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
148+ unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
149+ unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
150+ unifyRows' ((name, ty):row) r others u@(TUnknown un) = do
152+ forM_ row $ \(_, t) -> occursCheck un t
154+ u =?= RCons name ty u'
155+ unifyRows' row r others u'
156+ unifyRows' [] REmpty [] REmpty = return ()
157+ unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
158+ unifyRows' [] (Skolem s1 _) [] (Skolem s2 _) | s1 == s2 = return ()
159+ unifyRows' sd3 r3 sd4 r4 = throwError . strMsg $ "Cannot unify (" ++ prettyPrintRow (rowFromList (sd3, r3)) ++ ") with (" ++ prettyPrintRow (rowFromList (sd4, r4)) ++ ")"
162+-- Infer the types of multiple mutually-recursive values, and return elaborated values including
163+-- type class dictionaries and type annotations.
165+typesOf :: Maybe ModuleName -> ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
166+typesOf mainModuleName moduleName vals = do
167+ tys <- fmap tidyUp . liftUnify $ do
168+ (es, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName vals
170+ triple@(_, (_, ty)) <- typeForBindingGroupElement moduleName e dict untypedDict
171+ -- If --main is enabled, need to check that `main` has type Eff eff a for some eff, a
172+ when (Just moduleName == mainModuleName && fst e == Ident C.main) $ do
173+ [eff, a] <- replicateM 2 fresh
174+ ty =?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName [ProperName "Control", ProperName "Monad", ProperName "Eff"])) (ProperName "Eff"))) eff) a
177+ forM tys $ \(ident, (val, ty)) -> do
178+ -- Replace type class dictionary placeholders with actual dictionaries
179+ val' <- replaceTypeClassDictionaries moduleName val
180+ -- Check skolem variables did not escape their scope
181+ skolemEscapeCheck val'
182+ -- Remove type synonyms placeholders, remove duplicate row fields, and replace
183+ -- top-level unification variables with named type variables.
184+ let val'' = overTypes (desaturateAllTypeSynonyms . setifyAll) val'
185+ ty' = varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty
186+ return (ident, (val'', ty'))
188+ -- Apply the substitution that was returned from runUnify to both types and (type-annotated) values
189+ tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
191+typeDictionaryForBindingGroup :: ModuleName -> [(Ident, Value)] -> UnifyT Type Check ([(Ident, (Value, Maybe (Type, Bool)))], M.Map (ModuleName, Ident) (Type, NameKind), [(Ident, Type)])
192+typeDictionaryForBindingGroup moduleName vals = do
194+ -- Map each declaration to a name/value pair, with an optional type, if the declaration is typed
195+ es = map isTyped vals
196+ -- Filter the typed and untyped declarations
197+ typed = filter (isJust . snd . snd) es
198+ untyped = filter (isNothing . snd . snd) es
199+ -- Make a map of names to typed declarations
200+ typedDict = map (\(ident, (_, Just (ty, _))) -> (ident, ty)) typed
202+ -- Create fresh unification variables for the types of untyped declarations
203+ untypedNames <- replicateM (length untyped) fresh
206+ -- Make a map of names to the unification variables of untyped declarations
207+ untypedDict = zip (map fst untyped) untypedNames
208+ -- Create the dictionary of all name/type pairs, which will be added to the environment during type checking
209+ dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable))) $ typedDict ++ untypedDict)
210+ return (es, dict, untypedDict)
212+typeForBindingGroupElement :: ModuleName -> (Ident, (Value, Maybe (Type, Bool))) -> M.Map (ModuleName, Ident) (Type, NameKind) -> [(Ident, Type)] -> UnifyT Type Check (Ident, (Value, Type))
213+typeForBindingGroupElement moduleName e@(_, (val, _)) dict untypedDict = do
214+ -- If the declaration is a function, it has access to other values in the binding group.
215+ -- If not, the generated code might fail at runtime since those values might be undefined.
216+ let dict' = if isFunction val then dict else M.empty
218+ -- Typed declarations
219+ (ident, (val', Just (ty, checkType))) -> do
221+ kind <- liftCheck $ kindOf moduleName ty
222+ guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
223+ -- Check the type with the new names in scope
224+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
225+ val'' <- bindNames dict' $ if checkType
226+ then TypedValue True <$> check val' ty' <*> pure ty'
227+ else return (TypedValue False val' ty')
228+ return (ident, (val'', ty'))
229+ -- Untyped declarations
230+ (ident, (val', Nothing)) -> do
231+ -- Infer the type with the new names in scope
232+ TypedValue _ val'' ty <- bindNames dict' $ infer val'
233+ ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
234+ return (ident, (TypedValue True val'' ty, ty))
237+-- Check if a value introduces a function
239+isFunction :: Value -> Bool
240+isFunction (Abs _ _) = True
241+isFunction (TypedValue _ val _) = isFunction val
242+isFunction (PositionedValue _ val) = isFunction val
246+-- Check if a value contains a type annotation
248+isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
249+isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
250+isTyped (name, value) = (name, (value, Nothing))
253+-- Map a function over type annotations appearing inside a value
255+overTypes :: (Type -> Type) -> Value -> Value
256+overTypes f = everywhere (mkT f)
259+-- Replace type class dictionary placeholders with inferred type class dictionaries
261+replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
262+replaceTypeClassDictionaries mn = everywhereM' (mkM go)
264+ go (TypeClassDictionary trySuperclasses constraint dicts) = do
266+ entails env mn dicts constraint trySuperclasses
267+ go other = return other
270+-- A simplified representation of expressions which are used to represent type
271+-- class dictionaries at runtime, which can be compared for equality
275+ -- A dictionary which is brought into scope by a local constraint
277+ = LocalDictionaryValue (Qualified Ident)
279+ -- A dictionary which is brought into scope by an instance declaration
281+ | GlobalDictionaryValue (Qualified Ident)
283+ -- A dictionary which depends on other dictionaries
285+ | DependentDictionaryValue (Qualified Ident) [DictionaryValue]
287+ -- A subclass dictionary
289+ | SubclassDictionaryValue DictionaryValue (Qualified ProperName) Integer
290+ deriving (Show, Ord, Eq)
293+-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
294+-- return a type class dictionary reference.
296+entails :: Environment -> ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, [Type]) -> Bool -> Check Value
297+entails env moduleName context = solve (sortedNubBy canonicalizeDictionary (filter filterModule context))
299+ sortedNubBy :: (Ord k) => (v -> k) -> [v] -> [v]
300+ sortedNubBy f vs = M.elems (M.fromList (map (f &&& id) vs))
302+ -- Filter out type dictionaries which are in scope in the current module
303+ filterModule :: TypeClassDictionaryInScope -> Bool
304+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
305+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
306+ filterModule _ = False
308+ solve context' (className, tys) trySuperclasses =
309+ case chooseSimplestDictionaries (go trySuperclasses className tys) of
310+ [] -> throwError . strMsg $ "No instance found for " ++ show className ++ " " ++ unwords (map prettyPrintTypeAtom tys)
311+ [dict] -> return (dictionaryValueToValue dict)
312+ _ -> throwError . strMsg $ "Overlapping instances found for " ++ show className ++ " " ++ unwords (map prettyPrintTypeAtom tys)
314+ go trySuperclasses' className' tys' =
315+ -- Look for regular type instances
316+ [ mkDictionary (canonicalizeDictionary tcd) args
318+ -- Make sure the type class name matches the one we are trying to satisfy
319+ , className' == tcdClassName tcd
320+ -- Make sure the type unifies with the type in the type instance definition
321+ , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' (tcdInstanceTypes tcd)
322+ -- Solve any necessary subgoals
323+ , args <- solveSubgoals subst (tcdDependencies tcd) ] ++
325+ -- Look for implementations via superclasses
326+ [ SubclassDictionaryValue suDict superclass index
328+ , (subclassName, (args, _, implies)) <- M.toList (typeClasses env)
329+ -- Try each superclass
330+ , (index, (superclass, suTyArgs)) <- zip [0..] implies
331+ -- Make sure the type class name matches the superclass name
332+ , className' == superclass
333+ -- Make sure the types unify with the types in the superclass implication
334+ , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' suTyArgs
335+ -- Finally, satisfy the subclass constraint
336+ , suDict <- go trySuperclasses' subclassName (map (applySubst subst . TypeVar) args) ]
338+ -- Create dictionaries for subgoals which still need to be solved by calling go recursively
339+ -- E.g. the goal (Show a, Show b) => Show (Either a b) can be satisfied if the current type
340+ -- unifies with Either a b, and we can satisfy the subgoals Show a and Show b recursively.
341+ solveSubgoals :: [(String, Type)] -> Maybe [(Qualified ProperName, [Type])] -> [Maybe [DictionaryValue]]
342+ solveSubgoals _ Nothing = return Nothing
343+ solveSubgoals subst (Just subgoals) = do
344+ dict <- mapM (uncurry (go True) . second (map (replaceAllTypeVars subst))) subgoals
346+ -- Make a dictionary from subgoal dictionaries by applying the correct function
347+ mkDictionary :: Qualified Ident -> Maybe [DictionaryValue] -> DictionaryValue
348+ mkDictionary fnName Nothing = LocalDictionaryValue fnName
349+ mkDictionary fnName (Just []) = GlobalDictionaryValue fnName
350+ mkDictionary fnName (Just dicts) = DependentDictionaryValue fnName dicts
351+ -- Turn a DictionaryValue into a Value
352+ dictionaryValueToValue :: DictionaryValue -> Value
353+ dictionaryValueToValue (LocalDictionaryValue fnName) = Var fnName
354+ dictionaryValueToValue (GlobalDictionaryValue fnName) = App (Var fnName) (ObjectLiteral [])
355+ dictionaryValueToValue (DependentDictionaryValue fnName dicts) = foldl App (Var fnName) (map dictionaryValueToValue dicts)
356+ dictionaryValueToValue (SubclassDictionaryValue dict superclassName index) =
357+ App (Accessor (show superclassName ++ "_" ++ show index)
358+ (Accessor C.__superclasses (dictionaryValueToValue dict)))
360+ -- Ensure that a substitution is valid
361+ verifySubstitution :: [(String, Type)] -> Maybe [(String, Type)]
362+ verifySubstitution subst = do
363+ let grps = groupBy ((==) `on` fst) subst
364+ guard (all (pairwise (unifiesWith env) . map snd) grps)
365+ return $ map head grps
366+ -- Apply a substitution to a type
367+ applySubst :: [(String, Type)] -> Type -> Type
368+ applySubst subst = everywhere (mkT replace)
370+ replace t@(TypeVar v) = fromMaybe t $ lookup v subst
371+ replace other = other
372+ -- Choose the simplest DictionaryValues from a list of candidates
373+ -- The reason for this function is as follows:
374+ -- When considering overlapping instances, we don't want to consider the same dictionary
375+ -- to be an overlap of itself when obtained as a superclass of another class.
376+ -- Observing that we probably don't want to select a superclass instance when an instance
377+ -- is available directly, and that there is no way for a superclass instance to actually
378+ -- introduce an overlap that wouldn't have been there already, we simply remove dictionaries
379+ -- obtained as superclass instances if there are simpler instances available.
380+ chooseSimplestDictionaries :: [DictionaryValue] -> [DictionaryValue]
381+ chooseSimplestDictionaries ds = case filter isSimpleDictionaryValue ds of
384+ isSimpleDictionaryValue SubclassDictionaryValue{} = False
385+ isSimpleDictionaryValue (DependentDictionaryValue _ ds) = all isSimpleDictionaryValue ds
386+ isSimpleDictionaryValue _ = True
389+-- Check all values in a list pairwise match a predicate
391+pairwise :: (a -> a -> Bool) -> [a] -> Bool
393+pairwise _ [_] = True
394+pairwise p (x : xs) = all (p x) xs && pairwise p xs
397+-- Check that two types unify
399+unifiesWith :: Environment -> Type -> Type -> Bool
400+unifiesWith _ (TUnknown _) _ = True
401+unifiesWith _ _ (TUnknown _) = True
402+unifiesWith _ (Skolem s1 _) (Skolem s2 _) | s1 == s2 = True
403+unifiesWith _ (TypeVar v1) (TypeVar v2) | v1 == v2 = True
404+unifiesWith _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = True
405+unifiesWith e (TypeApp h1 t1) (TypeApp h2 t2) = unifiesWith e h1 h2 && unifiesWith e t1 t2
406+unifiesWith e (SaturatedTypeSynonym name args) t2 =
407+ case expandTypeSynonym' e name args of
409+ Right t1 -> unifiesWith e t1 t2
410+unifiesWith e t1 t2@(SaturatedTypeSynonym _ _) = unifiesWith e t2 t1
411+unifiesWith _ _ _ = False
414+-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
415+-- and return a substitution from type variables to types which makes the type heads unify.
417+typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
418+typeHeadsAreEqual _ _ (Skolem s1 _) (Skolem s2 _) | s1 == s2 = Just []
419+typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
420+typeHeadsAreEqual _ _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = Just []
421+typeHeadsAreEqual m e (TypeApp h1 t1) (TypeApp h2 t2) = (++) <$> typeHeadsAreEqual m e h1 h2 <*> typeHeadsAreEqual m e t1 t2
422+typeHeadsAreEqual m e (SaturatedTypeSynonym name args) t2 = case expandTypeSynonym' e name args of
424+ Right t1 -> typeHeadsAreEqual m e t1 t2
425+typeHeadsAreEqual _ _ _ _ = Nothing
428+-- Ensure skolem variables do not escape their scope
430+skolemEscapeCheck :: Value -> Check ()
431+skolemEscapeCheck (TypedValue False _ _) = return ()
432+skolemEscapeCheck root@TypedValue{} =
433+ -- Every skolem variable is created when a ForAll type is skolemized.
434+ -- This determines the scope of that skolem variable, which is copied from the SkolemScope
435+ -- field of the ForAll constructor.
436+ -- We traverse the tree top-down, and collect any SkolemScopes introduced by ForAlls.
437+ -- If a Skolem is encountered whose SkolemScope is not in the current list, we have found
438+ -- an escaped skolem variable.
439+ case everythingWithContext [] (++) (mkQ ((,) []) go) root of
441+ ((binding, val) : _) -> throwError $ mkErrorStack ("Rigid/skolem type variable " ++ maybe "" (("bound by " ++) . prettyPrintValue) binding ++ " has escaped.") (Just (ValueError val))
443+ go :: Value -> [(SkolemScope, Value)] -> ([(Maybe Value, Value)], [(SkolemScope, Value)])
444+ go val@(TypedValue _ _ (ForAll _ _ (Just sco))) scos = ([], (sco, val) : scos)
445+ go val@(TypedValue _ _ ty) scos = case collectSkolems ty \\ map fst scos of
446+ (sco : _) -> ([(findBindingScope sco, val)], scos)
449+ collectSkolems :: Type -> [SkolemScope]
450+ collectSkolems = nub . everything (++) (mkQ [] collect)
452+ collect (Skolem _ scope) = [scope]
454+ go _ scos = ([], scos)
455+ findBindingScope :: SkolemScope -> Maybe Value
456+ findBindingScope sco = something (mkQ Nothing go') root
458+ go' val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = Just val
460+skolemEscapeCheck val = throwError $ mkErrorStack "Untyped value passed to skolemEscapeCheck" (Just (ValueError val))
463+-- Ensure a row contains no duplicate labels
465+setify :: Type -> Type
466+setify = rowFromList . first (M.toList . M.fromList) . rowToList
469+-- \"Setify\" all rows occuring inside a value
471+setifyAll :: (D.Data d) => d -> d
472+setifyAll = everywhere (mkT setify)
475+-- Replace outermost unsolved unification variables with named type variables
477+varIfUnknown :: Type -> Type
479+ let unks = nub $ unknowns ty
480+ toName = (:) 't' . show
481+ ty' = everywhere (mkT typeToVar) ty
482+ typeToVar :: Type -> Type
483+ typeToVar (TUnknown (Unknown u)) = TypeVar (toName u)
485+ in mkForAll (sort . map (toName . runUnknown) $ unks) ty'
488+-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
489+-- or TypeClassDictionary values.
491+-- This is necessary during type checking to avoid unifying a polymorphic type with a
492+-- unification variable.
494+instantiatePolyTypeWithUnknowns :: Value -> Type -> UnifyT Type Check (Value, Type)
495+instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
496+ ty' <- replaceVarWithUnknown ident ty
497+ instantiatePolyTypeWithUnknowns val ty'
498+instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
499+ dicts <- getTypeClassDictionaries
500+ (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
501+ return (foldl App val (map (flip (TypeClassDictionary True) dicts) constraints), ty')
502+instantiatePolyTypeWithUnknowns val ty = return (val, ty)
505+-- Replace a single type variable with a new unification variable
507+replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
508+replaceVarWithUnknown ident ty = do
510+ return $ replaceTypeVars ident tu ty
513+-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
514+-- better error messages during unification.
516+replaceAllTypeSynonyms' :: (D.Data d) => Environment -> d -> Either String d
517+replaceAllTypeSynonyms' env d =
519+ syns = map (\(name, (args, _)) -> (name, length args)) . M.toList $ typeSynonyms env
521+ saturateAllTypeSynonyms syns d
523+replaceAllTypeSynonyms :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => (D.Data d) => d -> m d
524+replaceAllTypeSynonyms d = do
526+ either (throwError . strMsg) return $ replaceAllTypeSynonyms' env d
529+-- \"Desaturate\" @SaturatedTypeSynonym@s
531+desaturateAllTypeSynonyms :: (D.Data d) => d -> d
532+desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
534+ replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
535+ replaceSaturatedTypeSynonym t = t
538+-- Replace a type synonym and its arguments with the aliased type
540+expandTypeSynonym' :: Environment -> Qualified ProperName -> [Type] -> Either String Type
541+expandTypeSynonym' env name args =
542+ case M.lookup name (typeSynonyms env) of
543+ Just (synArgs, body) -> do
544+ let repl = replaceAllTypeVars (zip synArgs args) body
545+ replaceAllTypeSynonyms' env repl
546+ Nothing -> error "Type synonym was not defined"
548+expandTypeSynonym :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Qualified ProperName -> [Type] -> m Type
549+expandTypeSynonym name args = do
551+ either (throwError . strMsg) return $ expandTypeSynonym' env name args
553+expandAllTypeSynonyms :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
554+expandAllTypeSynonyms = everywhereM' (mkM go)
556+ go (SaturatedTypeSynonym name args) = expandTypeSynonym name args
557+ go other = return other
560+-- Ensure a set of property names and value does not contain duplicate labels
562+ensureNoDuplicateProperties :: (Error e, MonadError e m) => [(String, Value)] -> m ()
563+ensureNoDuplicateProperties ps = guardWith (strMsg "Duplicate property names") $ length (nub . map fst $ ps) == length ps
566+-- Infer a type for a value, rethrowing any error to provide a more useful error message
568+infer :: Value -> UnifyT Type Check Value
569+infer val = rethrow (mkErrorStack "Error inferring type of value" (Just (ValueError val)) <>) $ infer' val
572+-- Infer a type for a value
574+infer' :: Value -> UnifyT Type Check Value
575+infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
576+infer' v@(StringLiteral _) = return $ TypedValue True v tyString
577+infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
578+infer' (ArrayLiteral vals) = do
579+ ts <- mapM infer vals
581+ forM_ ts $ \(TypedValue _ _ t) -> els =?= TypeApp tyArray t
582+ return $ TypedValue True (ArrayLiteral ts) els
583+infer' (ObjectLiteral ps) = do
584+ ensureNoDuplicateProperties ps
585+ ts <- mapM (infer . snd) ps
586+ let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
587+ ty = TypeApp tyObject $ rowFromList (fields, REmpty)
588+ return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
589+infer' (ObjectUpdate o ps) = do
590+ ensureNoDuplicateProperties ps
592+ newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
593+ let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
594+ oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
595+ let oldTy = TypeApp tyObject $ rowFromList (oldTys, row)
596+ o' <- TypedValue True <$> check o oldTy <*> pure oldTy
597+ return $ TypedValue True (ObjectUpdate o' newVals) $ TypeApp tyObject $ rowFromList (newTys, row)
598+infer' (Accessor prop val) = do
599+ typed@(TypedValue _ _ objTy) <- infer val
600+ propTy <- inferProperty objTy prop
605+ _ <- subsumes Nothing objTy (TypeApp tyObject (RCons prop field rest))
606+ return $ TypedValue True (Accessor prop typed) field
607+ Just ty -> return $ TypedValue True (Accessor prop typed) ty
608+infer' (Abs (Left arg) ret) = do
610+ Just moduleName <- checkCurrentModule <$> get
611+ bindLocalVariables moduleName [(arg, ty)] $ do
612+ body@(TypedValue _ _ bodyTy) <- infer' ret
613+ return $ TypedValue True (Abs (Left arg) body) $ function ty bodyTy
614+infer' (Abs (Right _) _) = error "Binder was not desugared"
615+infer' (App f arg) = do
616+ f'@(TypedValue _ _ ft) <- infer f
617+ (ret, app) <- checkFunctionApplication f' ft arg Nothing
618+ return $ TypedValue True app ret
619+infer' (Var var) = do
620+ Just moduleName <- checkCurrentModule <$> get
621+ ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
623+ ConstrainedType constraints ty' -> do
624+ dicts <- getTypeClassDictionaries
625+ return $ TypedValue True (foldl App (Var var) (map (flip (TypeClassDictionary True) dicts) constraints)) ty'
626+ _ -> return $ TypedValue True (Var var) ty
627+infer' v@(Constructor c) = do
629+ case M.lookup c (dataConstructors env) of
630+ Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
631+ Just (_, ty) -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
632+ return $ TypedValue True v ty'
633+infer' (Case vals binders) = do
634+ ts <- mapM infer vals
636+ binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
637+ return $ TypedValue True (Case ts binders') ret
638+infer' (IfThenElse cond th el) = do
639+ cond' <- check cond tyBoolean
640+ v2@(TypedValue _ _ t2) <- infer th
641+ v3@(TypedValue _ _ t3) <- infer el
643+ return $ TypedValue True (IfThenElse cond' v2 v3) t2
644+infer' (Let ds val) = do
645+ (ds', val'@(TypedValue _ _ valTy)) <- inferLetBinding [] ds val infer
646+ return $ TypedValue True (Let ds' val') valTy
647+infer' (SuperClassDictionary className tys) = do
648+ dicts <- getTypeClassDictionaries
649+ return $ TypeClassDictionary False (className, tys) dicts
650+infer' (TypedValue checkType val ty) = do
651+ Just moduleName <- checkCurrentModule <$> get
652+ kind <- liftCheck $ kindOf moduleName ty
653+ guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
654+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
655+ val' <- if checkType then check val ty' else return val
656+ return $ TypedValue True val' ty'
657+infer' (PositionedValue pos val) = rethrowWithPosition pos $ infer' val
658+infer' _ = error "Invalid argument to infer"
660+inferLetBinding :: [Declaration] -> [Declaration] -> Value -> (Value -> UnifyT Type Check Value) -> UnifyT Type Check ([Declaration], Value)
661+inferLetBinding seen [] ret j = (,) seen <$> j ret
662+inferLetBinding seen (ValueDeclaration ident nameKind [] Nothing val : rest) ret j = do
664+ Just moduleName <- checkCurrentModule <$> get
665+ let dict = if isFunction val then M.singleton (moduleName, ident) (valTy, nameKind) else M.empty
666+ TypedValue _ val' valTy' <- bindNames dict $ infer val
668+ bindNames (M.singleton (moduleName, ident) (valTy', nameKind)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] Nothing val']) rest ret j
669+inferLetBinding seen (BindingGroupDeclaration ds : rest) ret j = do
670+ Just moduleName <- checkCurrentModule <$> get
671+ (es, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName (map (\(i, _, v) -> (i, v)) ds)
672+ ds' <- forM es $ \e -> do
673+ (ident, (val', _)) <- typeForBindingGroupElement moduleName e dict untypedDict
674+ return $ (ident, LocalVariable, val')
675+ bindNames dict $ inferLetBinding (seen ++ [BindingGroupDeclaration ds']) rest ret j
676+inferLetBinding seen (PositionedDeclaration pos d : ds) ret j = do
677+ ((d' : ds'), val') <- inferLetBinding seen (d : ds) ret j
678+ return (PositionedDeclaration pos d' : ds', val')
679+inferLetBinding _ _ _ _ = error "Invalid argument to inferLetBinding"
682+-- Infer the type of a property inside a record with a given type
684+inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
685+inferProperty (TypeApp obj row) prop | obj == tyObject = do
686+ let (props, _) = rowToList row
687+ return $ lookup prop props
688+inferProperty (SaturatedTypeSynonym name args) prop = do
689+ replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
690+ inferProperty replaced prop
691+inferProperty (ForAll ident ty _) prop = do
692+ replaced <- replaceVarWithUnknown ident ty
693+ inferProperty replaced prop
694+inferProperty _ _ = return Nothing
697+-- Infer the types of variables brought into scope by a binder
699+inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
700+inferBinder _ NullBinder = return M.empty
701+inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
702+inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
703+inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
704+inferBinder val (VarBinder name) = return $ M.singleton name val
705+inferBinder val (ConstructorBinder ctor binders) = do
707+ case M.lookup ctor (dataConstructors env) of
709+ (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contain constraints") ty
710+ fn' <- replaceAllTypeSynonyms fn
714+ _ <- subsumes Nothing val ty'
716+ go (binder : binders') (TypeApp (TypeApp t obj) ret) | t == tyFunction =
717+ M.union <$> inferBinder obj binder <*> go binders' ret
718+ go _ _ = throwError . strMsg $ "Wrong number of arguments to constructor " ++ show ctor
719+ _ -> throwError . strMsg $ "Constructor " ++ show ctor ++ " is not defined"
720+inferBinder val (ObjectBinder props) = do
723+ m1 <- inferRowProperties row rest props
724+ val =?= TypeApp tyObject row
727+ inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
728+ inferRowProperties nrow row [] = nrow =?= row >> return M.empty
729+ inferRowProperties nrow row ((name, binder):binders) = do
731+ m1 <- inferBinder propTy binder
732+ m2 <- inferRowProperties nrow (RCons name propTy row) binders
733+ return $ m1 `M.union` m2
734+inferBinder val (ArrayBinder binders) = do
736+ m1 <- M.unions <$> mapM (inferBinder el) binders
737+ val =?= TypeApp tyArray el
739+inferBinder val (ConsBinder headBinder tailBinder) = do
741+ m1 <- inferBinder el headBinder
742+ m2 <- inferBinder val tailBinder
743+ val =?= TypeApp tyArray el
744+ return $ m1 `M.union` m2
745+inferBinder val (NamedBinder name binder) = do
746+ m <- inferBinder val binder
747+ return $ M.insert name val m
748+inferBinder val (PositionedBinder pos binder) =
749+ rethrowWithPosition pos $ inferBinder val binder
752+-- Check the types of the return values in a set of binders in a case statement
754+checkBinders :: [Type] -> Type -> [CaseAlternative] -> UnifyT Type Check [CaseAlternative]
755+checkBinders _ _ [] = return []
756+checkBinders nvals ret (CaseAlternative binders grd val : bs) = do
757+ Just moduleName <- checkCurrentModule <$> get
758+ m1 <- M.unions <$> zipWithM inferBinder nvals binders
759+ r <- bindLocalVariables moduleName (M.toList m1) $ do
760+ val' <- TypedValue True <$> check val ret <*> pure ret
762+ Nothing -> return $ CaseAlternative binders Nothing val'
764+ g' <- check g tyBoolean
765+ return $ CaseAlternative binders (Just g') val'
766+ rs <- checkBinders nvals ret bs
770+-- Generate a new skolem constant
772+newSkolemConstant :: UnifyT Type Check Int
773+newSkolemConstant = runUnknown <$> fresh'
776+-- Generate a new skolem scope
778+newSkolemScope :: UnifyT Type Check SkolemScope
779+newSkolemScope = SkolemScope . runUnknown <$> fresh'
782+-- Skolemize a type variable by replacing its instances with fresh skolem constants
784+skolemize :: String -> Int -> SkolemScope -> Type -> Type
785+skolemize ident sko scope = replaceTypeVars ident (Skolem sko scope)
788+-- This function has one purpose - to skolemize type variables appearing in a
789+-- SuperClassDictionary placeholder. These type variables are somewhat unique since they are the
790+-- only example of scoped type variables.
792+skolemizeTypesInValue :: String -> Int -> SkolemScope -> Value -> Value
793+skolemizeTypesInValue ident sko scope = everywhere (mkT go)
795+ go (SuperClassDictionary c ts) = SuperClassDictionary c (map (skolemize ident sko scope) ts)
799+-- Introduce skolem scope at every occurence of a ForAll
801+introduceSkolemScope :: Type -> UnifyT Type Check Type
802+introduceSkolemScope = everywhereM (mkM go)
804+ go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
805+ go other = return other
808+-- Check the type of a value, rethrowing errors to provide a better error message
810+check :: Value -> Type -> UnifyT Type Check Value
811+check val ty = rethrow (mkErrorStack errorMessage (Just (ValueError val)) <>) $ check' val ty
814+ "Error checking type of term " ++
815+ prettyPrintValue val ++
820+-- Check the type of a value
822+check' :: Value -> Type -> UnifyT Type Check Value
823+check' val (ForAll ident ty _) = do
824+ scope <- newSkolemScope
825+ sko <- newSkolemConstant
826+ let sk = skolemize ident sko scope ty
827+ let skVal = skolemizeTypesInValue ident sko scope val
828+ val' <- check skVal sk
829+ return $ TypedValue True val' (ForAll ident ty (Just scope))
830+check' val t@(ConstrainedType constraints ty) = do
831+ dictNames <- forM constraints $ \(Qualified _ (ProperName className), _) -> do
832+ n <- liftCheck freshDictionaryName
833+ return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
834+ val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
835+ TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
836+ constraints) $ check val ty
837+ return $ TypedValue True (foldr (Abs . Left) val' dictNames) t
838+check' val (SaturatedTypeSynonym name args) = do
839+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
841+check' val u@(TUnknown _) = do
842+ val'@(TypedValue _ _ ty) <- infer val
843+ -- Don't unify an unknown with an inferred polytype
844+ (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
846+ return $ TypedValue True val'' ty'
847+check' v@(NumericLiteral _) t | t == tyNumber =
848+ return $ TypedValue True v t
849+check' v@(StringLiteral _) t | t == tyString =
850+ return $ TypedValue True v t
851+check' v@(BooleanLiteral _) t | t == tyBoolean =
852+ return $ TypedValue True v t
853+check' (ArrayLiteral vals) t@(TypeApp a ty) = do
855+ array <- ArrayLiteral <$> forM vals (`check` ty)
856+ return $ TypedValue True array t
857+check' (Abs (Left arg) ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
858+ Just moduleName <- checkCurrentModule <$> get
859+ ret' <- bindLocalVariables moduleName [(arg, argTy)] $ check ret retTy
860+ return $ TypedValue True (Abs (Left arg) ret') ty
861+check' (Abs (Right _) _) _ = error "Binder was not desugared"
862+check' (App f arg) ret = do
863+ f'@(TypedValue _ _ ft) <- infer f
864+ (_, app) <- checkFunctionApplication f' ft arg (Just ret)
865+ return $ TypedValue True app ret
866+check' v@(Var var) ty = do
867+ Just moduleName <- checkCurrentModule <$> get
868+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
869+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
870+ v' <- subsumes (Just v) repl ty'
872+ Nothing -> throwError . strMsg $ "Unable to check type subsumption"
873+ Just v'' -> return $ TypedValue True v'' ty'
874+check' (SuperClassDictionary className tys) _ = do
876+ -- Here, we replace a placeholder for a superclass dictionary with a regular
877+ -- TypeClassDictionary placeholder. The reason we do this is that it is necessary to have the
878+ -- correct super instance dictionaries in scope, and these are not available when the type class
879+ -- declaration gets desugared.
881+ -- Note also that the first argument to TypeClassDictionary is False, meaning we _do not_ want
882+ -- to consider superclass instances when searching for this dictionary - doing so might lead
883+ -- to traversing a cycle in the instance graph.
885+ dicts <- getTypeClassDictionaries
886+ return $ TypeClassDictionary False (className, tys) dicts
887+check' (TypedValue checkType val ty1) ty2 = do
888+ Just moduleName <- checkCurrentModule <$> get
889+ kind <- liftCheck $ kindOf moduleName ty1
890+ guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
891+ ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
892+ val' <- subsumes (Just val) ty1' ty2
894+ Nothing -> throwError . strMsg $ "Unable to check type subsumption"
896+ val''' <- if checkType then check val'' ty1' else return val''
897+ return $ TypedValue checkType (TypedValue True val''' ty1) ty2
898+check' (Case vals binders) ret = do
899+ vals' <- mapM infer vals
900+ let ts = map (\(TypedValue _ _ t) -> t) vals'
901+ binders' <- checkBinders ts ret binders
902+ return $ TypedValue True (Case vals' binders') ret
903+check' (IfThenElse cond th el) ty = do
904+ cond' <- check cond tyBoolean
907+ return $ TypedValue True (IfThenElse cond' th' el') ty
908+check' (ObjectLiteral ps) t@(TypeApp obj row) | obj == tyObject = do
909+ ensureNoDuplicateProperties ps
910+ ps' <- checkProperties ps row False
911+ return $ TypedValue True (ObjectLiteral ps') t
912+check' (ObjectUpdate obj ps) t@(TypeApp o row) | o == tyObject = do
913+ ensureNoDuplicateProperties ps
914+ us <- zip (map fst ps) <$> replicateM (length ps) fresh
915+ let (propsToCheck, rest) = rowToList row
916+ propsToRemove = map fst ps
917+ remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
918+ obj' <- check obj (TypeApp tyObject (rowFromList (us ++ remainingProps, rest)))
919+ ps' <- checkProperties ps row True
920+ return $ TypedValue True (ObjectUpdate obj' ps') t
921+check' (Accessor prop val) ty = do
923+ val' <- check val (TypeApp tyObject (RCons prop ty rest))
924+ return $ TypedValue True (Accessor prop val') ty
925+check' (Constructor c) ty = do
927+ case M.lookup c (dataConstructors env) of
928+ Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
930+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
931+ _ <- subsumes Nothing repl ty
932+ return $ TypedValue True (Constructor c) ty
933+check' (Let ds val) ty = do
934+ (ds', val') <- inferLetBinding [] ds val (flip check ty)
935+ return $ TypedValue True (Let ds' val') ty
936+check' val ty | containsTypeSynonyms ty = do
937+ ty' <- introduceSkolemScope <=< expandAllTypeSynonyms $ ty
939+check' (PositionedValue pos val) ty =
940+ rethrowWithPosition pos $ check val ty
941+check' val ty = throwError $ mkErrorStack ("Value does not have type " ++ prettyPrintType ty) (Just (ValueError val))
943+containsTypeSynonyms :: Type -> Bool
944+containsTypeSynonyms = everything (||) (mkQ False go) where
945+ go (SaturatedTypeSynonym _ _) = True
949+-- Check the type of a collection of named record fields
951+-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
953+checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Type Check [(String, Value)]
954+checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
955+ go [] [] REmpty = return []
956+ go [] [] u@(TUnknown _) = do u =?= REmpty
958+ go [] [] (Skolem _ _) | lax = return []
959+ go [] ((p, _): _) _ | lax = return []
960+ | otherwise = throwError $ mkErrorStack ("Object does not have property " ++ p) (Just (ValueError (ObjectLiteral ps)))
961+ go ((p,_):_) [] REmpty = throwError $ mkErrorStack ("Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row) (Just (ValueError (ObjectLiteral ps)))
962+ go ((p,v):ps') [] u@(TUnknown _) = do
963+ v'@(TypedValue _ _ ty) <- infer v
965+ u =?= RCons p ty rest
966+ ps'' <- go ps' [] rest
967+ return $ (p, v') : ps''
968+ go ((p,v):ps') ts r =
971+ v'@(TypedValue _ _ ty) <- infer v
973+ r =?= RCons p ty rest
974+ ps'' <- go ps' ts rest
975+ return $ (p, v') : ps''
978+ ps'' <- go ps' (delete (p, ty) ts) r
979+ return $ (p, v') : ps''
980+ go _ _ _ = throwError $ mkErrorStack ("Object does not have type " ++ prettyPrintType (TypeApp tyObject row)) (Just (ValueError (ObjectLiteral ps)))
983+-- Check the type of a function application, rethrowing errors to provide a better error message
985+checkFunctionApplication :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
986+checkFunctionApplication fn fnTy arg ret = rethrow (mkErrorStack errorMessage (Just (ValueError fn)) <>) $ checkFunctionApplication' fn fnTy arg ret
988+ errorMessage = "Error applying function of type "
989+ ++ prettyPrintType fnTy
990+ ++ " to argument " ++ prettyPrintValue arg
993+-- Check the type of a function application
995+checkFunctionApplication' :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
996+checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg ret = do
997+ tyFunction' =?= tyFunction
998+ _ <- maybe (return Nothing) (subsumes Nothing retTy) ret
999+ subst <- unifyCurrentSubstitution <$> UnifyT get
1000+ arg' <- check arg (subst $? argTy)
1001+ return (retTy, App fn arg')
1002+checkFunctionApplication' fn (ForAll ident ty _) arg ret = do
1003+ replaced <- replaceVarWithUnknown ident ty
1004+ checkFunctionApplication fn replaced arg ret
1005+checkFunctionApplication' fn u@(TUnknown _) arg ret = do
1007+ TypedValue _ arg' t <- infer arg
1008+ (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
1009+ return $ TypedValue True arg'' t'
1010+ let ty = (\(TypedValue _ _ t) -> t) arg'
1011+ ret' <- maybe fresh return ret
1012+ u =?= function ty ret'
1013+ return (ret', App fn arg')
1014+checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
1015+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1016+ checkFunctionApplication fn ty arg ret
1017+checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
1018+ dicts <- getTypeClassDictionaries
1019+ checkFunctionApplication' (foldl App fn (map (flip (TypeClassDictionary True) dicts) constraints)) fnTy arg ret
1020+checkFunctionApplication' _ fnTy arg _ = throwError . strMsg $ "Cannot apply a function of type "
1021+ ++ prettyPrintType fnTy
1022+ ++ " to argument " ++ prettyPrintValue arg
1025+-- Check whether one type subsumes another, rethrowing errors to provide a better error message
1027+subsumes :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
1028+subsumes val ty1 ty2 = rethrow (mkErrorStack errorMessage (ValueError <$> val) <>) $ subsumes' val ty1 ty2
1030+ errorMessage = "Error checking that type "
1031+ ++ prettyPrintType ty1
1032+ ++ " subsumes type "
1033+ ++ prettyPrintType ty2
1036+-- Check whether one type subsumes another
1038+subsumes' :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
1039+subsumes' val (ForAll ident ty1 _) ty2 = do
1040+ replaced <- replaceVarWithUnknown ident ty1
1041+ subsumes val replaced ty2
1042+subsumes' val ty1 (ForAll ident ty2 sco) =
1045+ sko <- newSkolemConstant
1046+ let sk = skolemize ident sko sco' ty2
1047+ subsumes val ty1 sk
1048+ Nothing -> throwError . strMsg $ "Skolem variable scope is unspecified"
1049+subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
1050+ _ <- subsumes Nothing arg2 arg1
1051+ _ <- subsumes Nothing ret1 ret2
1053+subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
1054+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1055+ subsumes val ty1 ty2
1056+subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
1057+ ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1058+ subsumes val ty1 ty2
1059+subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
1060+ dicts <- getTypeClassDictionaries
1061+ _ <- subsumes' Nothing ty1 ty2
1062+ return . Just $ foldl App val (map (flip (TypeClassDictionary True) dicts) constraints)
1063+subsumes' val (TypeApp f1 r1) (TypeApp f2 r2) | f1 == tyObject && f2 == tyObject = do
1065+ (ts1, r1') = rowToList r1
1066+ (ts2, r2') = rowToList r2
1067+ ts1' = sortBy (comparing fst) ts1
1068+ ts2' = sortBy (comparing fst) ts2
1069+ go ts1' ts2' r1' r2'
1072+ go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
1073+ go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
1074+ go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
1075+ | p1 == p2 = do _ <- subsumes Nothing ty1 ty2
1077+ | p1 < p2 = do rest <- fresh
1078+ r2' =?= RCons p1 ty1 rest
1079+ go ts1 ((p2, ty2) : ts2) r1' rest
1080+ | otherwise = do rest <- fresh
1081+ r1' =?= RCons p2 ty2 rest
1082+ go ((p1, ty1) : ts1) ts2 rest r2'
1083+subsumes' val ty1 ty2@(TypeApp obj _) | obj == tyObject = subsumes val ty2 ty1
1084+subsumes' val ty1 ty2 = do