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