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