@@ -0,0 +1,986 @@
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+ let dict = if isFunction val then M.singleton (moduleName, ident) (valTy, nameKind) else M.empty
589+ TypedValue _ val' valTy' <- bindNames dict $ infer val
590+ valTy =?= valTy'
591+ bindNames (M.singleton (moduleName, ident) (valTy', nameKind)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] Nothing val']) rest ret j
592+inferLetBinding seen (BindingGroupDeclaration ds : rest) ret j = do
593+ Just moduleName <- checkCurrentModule <$> get
594+ (es, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName (map (\(i, _, v) -> (i, v)) ds)
595+ ds' <- forM es $ \e -> do
596+ (ident, (val', _)) <- typeForBindingGroupElement moduleName e dict untypedDict
597+ return $ (ident, LocalVariable, val')
598+ bindNames dict $ inferLetBinding (seen ++ [BindingGroupDeclaration ds']) rest ret j
599+inferLetBinding seen (PositionedDeclaration pos d : ds) ret j = do
600+ ((d' : ds'), val') <- inferLetBinding seen (d : ds) ret j
601+ return (PositionedDeclaration pos d' : ds', val')
602+inferLetBinding _ _ _ _ = error "Invalid argument to inferLetBinding"
603+
604+-- |
605+-- Infer the type of a property inside a record with a given type
606+--
607+inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
608+inferProperty (TypeApp obj row) prop | obj == tyObject = do
609+ let (props, _) = rowToList row
610+ return $ lookup prop props
611+inferProperty (SaturatedTypeSynonym name args) prop = do
612+ replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
613+ inferProperty replaced prop
614+inferProperty (ForAll ident ty _) prop = do
615+ replaced <- replaceVarWithUnknown ident ty
616+ inferProperty replaced prop
617+inferProperty _ _ = return Nothing
618+
619+-- |
620+-- Infer the types of variables brought into scope by a binder
621+--
622+inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
623+inferBinder _ NullBinder = return M.empty
624+inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
625+inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
626+inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
627+inferBinder val (VarBinder name) = return $ M.singleton name val
628+inferBinder val (ConstructorBinder ctor binders) = do
629+ env <- getEnv
630+ case M.lookup ctor (dataConstructors env) of
631+ Just (_, ty) -> do
632+ (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contain constraints") ty
633+ fn' <- replaceAllTypeSynonyms fn
634+ go binders fn'
635+ where
636+ go [] ty' = do
637+ _ <- subsumes Nothing val ty'
638+ return M.empty
639+ go (binder : binders') (TypeApp (TypeApp t obj) ret) | t == tyFunction =
640+ M.union <$> inferBinder obj binder <*> go binders' ret
641+ go _ _ = throwError . strMsg $ "Wrong number of arguments to constructor " ++ show ctor
642+ _ -> throwError . strMsg $ "Constructor " ++ show ctor ++ " is not defined"
643+inferBinder val (ObjectBinder props) = do
644+ row <- fresh
645+ rest <- fresh
646+ m1 <- inferRowProperties row rest props
647+ val =?= TypeApp tyObject row
648+ return m1
649+ where
650+ inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
651+ inferRowProperties nrow row [] = nrow =?= row >> return M.empty
652+ inferRowProperties nrow row ((name, binder):binders) = do
653+ propTy <- fresh
654+ m1 <- inferBinder propTy binder
655+ m2 <- inferRowProperties nrow (RCons name propTy row) binders
656+ return $ m1 `M.union` m2
657+inferBinder val (ArrayBinder binders) = do
658+ el <- fresh
659+ m1 <- M.unions <$> mapM (inferBinder el) binders
660+ val =?= TypeApp tyArray el
661+ return m1
662+inferBinder val (ConsBinder headBinder tailBinder) = do
663+ el <- fresh
664+ m1 <- inferBinder el headBinder
665+ m2 <- inferBinder val tailBinder
666+ val =?= TypeApp tyArray el
667+ return $ m1 `M.union` m2
668+inferBinder val (NamedBinder name binder) = do
669+ m <- inferBinder val binder
670+ return $ M.insert name val m
671+inferBinder val (PositionedBinder pos binder) =
672+ rethrowWithPosition pos $ inferBinder val binder
673+
674+-- |
675+-- Check the types of the return values in a set of binders in a case statement
676+--
677+checkBinders :: [Type] -> Type -> [CaseAlternative] -> UnifyT Type Check [CaseAlternative]
678+checkBinders _ _ [] = return []
679+checkBinders nvals ret (CaseAlternative binders grd val : bs) = do
680+ Just moduleName <- checkCurrentModule <$> get
681+ m1 <- M.unions <$> zipWithM inferBinder nvals binders
682+ r <- bindLocalVariables moduleName (M.toList m1) $ do
683+ val' <- TypedValue True <$> check val ret <*> pure ret
684+ case grd of
685+ Nothing -> return $ CaseAlternative binders Nothing val'
686+ Just g -> do
687+ g' <- check g tyBoolean
688+ return $ CaseAlternative binders (Just g') val'
689+ rs <- checkBinders nvals ret bs
690+ return $ r : rs
691+
692+-- |
693+-- Generate a new skolem constant
694+--
695+newSkolemConstant :: UnifyT Type Check Int
696+newSkolemConstant = runUnknown <$> fresh'
697+
698+-- |
699+-- Generate a new skolem scope
700+--
701+newSkolemScope :: UnifyT Type Check SkolemScope
702+newSkolemScope = SkolemScope . runUnknown <$> fresh'
703+
704+-- |
705+-- Skolemize a type variable by replacing its instances with fresh skolem constants
706+--
707+skolemize :: String -> Int -> SkolemScope -> Type -> Type
708+skolemize ident sko scope = replaceTypeVars ident (Skolem sko scope)
709+
710+-- |
711+-- Introduce skolem scope at every occurence of a ForAll
712+--
713+introduceSkolemScope :: Type -> UnifyT Type Check Type
714+introduceSkolemScope = everywhereM (mkM go)
715+ where
716+ go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
717+ go other = return other
718+
719+-- |
720+-- Check the type of a value, rethrowing errors to provide a better error message
721+--
722+check :: Value -> Type -> UnifyT Type Check Value
723+check val ty = rethrow (mkUnifyErrorStack errorMessage (Just (ValueError val)) <>) $ check' val ty
724+ where
725+ errorMessage =
726+ "Error checking type of term " ++
727+ prettyPrintValue val ++
728+ " against type " ++
729+ prettyPrintType ty
730+
731+-- |
732+-- Check the type of a value
733+--
734+check' :: Value -> Type -> UnifyT Type Check Value
735+check' val (ForAll ident ty _) = do
736+ scope <- newSkolemScope
737+ sko <- newSkolemConstant
738+ let sk = skolemize ident sko scope ty
739+ val' <- check val sk
740+ return $ TypedValue True val' (ForAll ident ty (Just scope))
741+check' val t@(ConstrainedType constraints ty) = do
742+ dictNames <- forM constraints $ \(Qualified _ (ProperName className), _) -> do
743+ n <- liftCheck freshDictionaryName
744+ return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
745+ val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
746+ TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
747+ constraints) $ check val ty
748+ return $ TypedValue True (foldr (Abs . Left) val' dictNames) t
749+check' val (SaturatedTypeSynonym name args) = do
750+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
751+ check val ty
752+check' val u@(TUnknown _) = do
753+ val'@(TypedValue _ _ ty) <- infer val
754+ -- Don't unify an unknown with an inferred polytype
755+ (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
756+ ty' =?= u
757+ return $ TypedValue True val'' ty'
758+check' v@(NumericLiteral _) t | t == tyNumber =
759+ return $ TypedValue True v t
760+check' v@(StringLiteral _) t | t == tyString =
761+ return $ TypedValue True v t
762+check' v@(BooleanLiteral _) t | t == tyBoolean =
763+ return $ TypedValue True v t
764+check' (ArrayLiteral vals) t@(TypeApp a ty) = do
765+ a =?= tyArray
766+ array <- ArrayLiteral <$> forM vals (`check` ty)
767+ return $ TypedValue True array t
768+check' (Abs (Left arg) ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
769+ Just moduleName <- checkCurrentModule <$> get
770+ ret' <- bindLocalVariables moduleName [(arg, argTy)] $ check ret retTy
771+ return $ TypedValue True (Abs (Left arg) ret') ty
772+check' (Abs (Right _) _) _ = error "Binder was not desugared"
773+check' (App f arg) ret = do
774+ f'@(TypedValue _ _ ft) <- infer f
775+ (_, app) <- checkFunctionApplication f' ft arg (Just ret)
776+ return $ TypedValue True app ret
777+check' v@(Var var) ty = do
778+ Just moduleName <- checkCurrentModule <$> get
779+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
780+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
781+ v' <- subsumes (Just v) repl ty'
782+ case v' of
783+ Nothing -> throwError . strMsg $ "Unable to check type subsumption"
784+ Just v'' -> return $ TypedValue True v'' ty'
785+check' (TypedValue checkType val ty1) ty2 = do
786+ Just moduleName <- checkCurrentModule <$> get
787+ kind <- liftCheck $ kindOf moduleName ty1
788+ guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
789+ ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
790+ val' <- subsumes (Just val) ty1' ty2
791+ case val' of
792+ Nothing -> throwError . strMsg $ "Unable to check type subsumption"
793+ Just val'' -> do
794+ val''' <- if checkType then check val'' ty1' else return val''
795+ return $ TypedValue checkType (TypedValue True val''' ty1) ty2
796+check' (Case vals binders) ret = do
797+ vals' <- mapM infer vals
798+ let ts = map (\(TypedValue _ _ t) -> t) vals'
799+ binders' <- checkBinders ts ret binders
800+ return $ TypedValue True (Case vals' binders') ret
801+check' (IfThenElse cond th el) ty = do
802+ cond' <- check cond tyBoolean
803+ th' <- check th ty
804+ el' <- check el ty
805+ return $ TypedValue True (IfThenElse cond' th' el') ty
806+check' (ObjectLiteral ps) t@(TypeApp obj row) | obj == tyObject = do
807+ ensureNoDuplicateProperties ps
808+ ps' <- checkProperties ps row False
809+ return $ TypedValue True (ObjectLiteral ps') t
810+check' (ObjectUpdate obj ps) t@(TypeApp o row) | o == tyObject = do
811+ ensureNoDuplicateProperties ps
812+ us <- zip (map fst ps) <$> replicateM (length ps) fresh
813+ let (propsToCheck, rest) = rowToList row
814+ propsToRemove = map fst ps
815+ remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
816+ obj' <- check obj (TypeApp tyObject (rowFromList (us ++ remainingProps, rest)))
817+ ps' <- checkProperties ps row True
818+ return $ TypedValue True (ObjectUpdate obj' ps') t
819+check' (Accessor prop val) ty = do
820+ rest <- fresh
821+ val' <- check val (TypeApp tyObject (RCons prop ty rest))
822+ return $ TypedValue True (Accessor prop val') ty
823+check' (Constructor c) ty = do
824+ env <- getEnv
825+ case M.lookup c (dataConstructors env) of
826+ Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
827+ Just (_, ty1) -> do
828+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
829+ _ <- subsumes Nothing repl ty
830+ return $ TypedValue True (Constructor c) ty
831+check' (Let ds val) ty = do
832+ (ds', val') <- inferLetBinding [] ds val (flip check ty)
833+ return $ TypedValue True (Let ds' val') ty
834+check' val ty | containsTypeSynonyms ty = do
835+ ty' <- introduceSkolemScope <=< expandAllTypeSynonyms $ ty
836+ check val ty'
837+check' (PositionedValue pos val) ty =
838+ rethrowWithPosition pos $ check val ty
839+check' val ty = throwError $ mkUnifyErrorStack ("Value does not have type " ++ prettyPrintType ty) (Just (ValueError val))
840+
841+containsTypeSynonyms :: Type -> Bool
842+containsTypeSynonyms = everything (||) (mkQ False go) where
843+ go (SaturatedTypeSynonym _ _) = True
844+ go _ = False
845+
846+-- |
847+-- Check the type of a collection of named record fields
848+--
849+-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
850+--
851+checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Type Check [(String, Value)]
852+checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
853+ go [] [] REmpty = return []
854+ go [] [] u@(TUnknown _) = do u =?= REmpty
855+ return []
856+ go [] [] (Skolem _ _) | lax = return []
857+ go [] ((p, _): _) _ | lax = return []
858+ | otherwise = throwError $ mkUnifyErrorStack ("Object does not have property " ++ p) (Just (ValueError (ObjectLiteral ps)))
859+ go ((p,_):_) [] REmpty = throwError $ mkUnifyErrorStack ("Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row) (Just (ValueError (ObjectLiteral ps)))
860+ go ((p,v):ps') [] u@(TUnknown _) = do
861+ v'@(TypedValue _ _ ty) <- infer v
862+ rest <- fresh
863+ u =?= RCons p ty rest
864+ ps'' <- go ps' [] rest
865+ return $ (p, v') : ps''
866+ go ((p,v):ps') ts r =
867+ case lookup p ts of
868+ Nothing -> do
869+ v'@(TypedValue _ _ ty) <- infer v
870+ rest <- fresh
871+ r =?= RCons p ty rest
872+ ps'' <- go ps' ts rest
873+ return $ (p, v') : ps''
874+ Just ty -> do
875+ v' <- check v ty
876+ ps'' <- go ps' (delete (p, ty) ts) r
877+ return $ (p, v') : ps''
878+ go _ _ _ = throwError $ mkUnifyErrorStack ("Object does not have type " ++ prettyPrintType (TypeApp tyObject row)) (Just (ValueError (ObjectLiteral ps)))
879+
880+-- |
881+-- Check the type of a function application, rethrowing errors to provide a better error message
882+--
883+checkFunctionApplication :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
884+checkFunctionApplication fn fnTy arg ret = rethrow (mkUnifyErrorStack errorMessage (Just (ValueError fn)) <>) $ checkFunctionApplication' fn fnTy arg ret
885+ where
886+ errorMessage = "Error applying function of type "
887+ ++ prettyPrintType fnTy
888+ ++ " to argument " ++ prettyPrintValue arg
889+
890+-- |
891+-- Check the type of a function application
892+--
893+checkFunctionApplication' :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
894+checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg ret = do
895+ tyFunction' =?= tyFunction
896+ _ <- maybe (return Nothing) (subsumes Nothing retTy) ret
897+ subst <- unifyCurrentSubstitution <$> UnifyT get
898+ arg' <- check arg (subst $? argTy)
899+ return (retTy, App fn arg')
900+checkFunctionApplication' fn (ForAll ident ty _) arg ret = do
901+ replaced <- replaceVarWithUnknown ident ty
902+ checkFunctionApplication fn replaced arg ret
903+checkFunctionApplication' fn u@(TUnknown _) arg ret = do
904+ arg' <- do
905+ TypedValue _ arg' t <- infer arg
906+ (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
907+ return $ TypedValue True arg'' t'
908+ let ty = (\(TypedValue _ _ t) -> t) arg'
909+ ret' <- maybe fresh return ret
910+ u =?= function ty ret'
911+ return (ret', App fn arg')
912+checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
913+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
914+ checkFunctionApplication fn ty arg ret
915+checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
916+ dicts <- getTypeClassDictionaries
917+ checkFunctionApplication' (foldl App fn (map (flip TypeClassDictionary dicts) constraints)) fnTy arg ret
918+checkFunctionApplication' _ fnTy arg _ = throwError . strMsg $ "Cannot apply a function of type "
919+ ++ prettyPrintType fnTy
920+ ++ " to argument " ++ prettyPrintValue arg
921+
922+-- |
923+-- Check whether one type subsumes another, rethrowing errors to provide a better error message
924+--
925+subsumes :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
926+subsumes val ty1 ty2 = rethrow (mkUnifyErrorStack errorMessage (ValueError <$> val) <>) $ subsumes' val ty1 ty2
927+ where
928+ errorMessage = "Error checking that type "
929+ ++ prettyPrintType ty1
930+ ++ " subsumes type "
931+ ++ prettyPrintType ty2
932+
933+-- |
934+-- Check whether one type subsumes another
935+--
936+subsumes' :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
937+subsumes' val (ForAll ident ty1 _) ty2 = do
938+ replaced <- replaceVarWithUnknown ident ty1
939+ subsumes val replaced ty2
940+subsumes' val ty1 (ForAll ident ty2 sco) =
941+ case sco of
942+ Just sco' -> do
943+ sko <- newSkolemConstant
944+ let sk = skolemize ident sko sco' ty2
945+ subsumes val ty1 sk
946+ Nothing -> throwError . strMsg $ "Skolem variable scope is unspecified"
947+subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
948+ _ <- subsumes Nothing arg2 arg1
949+ _ <- subsumes Nothing ret1 ret2
950+ return val
951+subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
952+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
953+ subsumes val ty1 ty2
954+subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
955+ ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
956+ subsumes val ty1 ty2
957+subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
958+ dicts <- getTypeClassDictionaries
959+ _ <- subsumes' Nothing ty1 ty2
960+ return . Just $ foldl App val (map (flip TypeClassDictionary dicts) constraints)
961+subsumes' val (TypeApp f1 r1) (TypeApp f2 r2) | f1 == tyObject && f2 == tyObject = do
962+ let
963+ (ts1, r1') = rowToList r1
964+ (ts2, r2') = rowToList r2
965+ ts1' = sortBy (comparing fst) ts1
966+ ts2' = sortBy (comparing fst) ts2
967+ go ts1' ts2' r1' r2'
968+ return val
969+ where
970+ go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
971+ go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
972+ go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
973+ | p1 == p2 = do _ <- subsumes Nothing ty1 ty2
974+ go ts1 ts2 r1' r2'
975+ | p1 < p2 = do rest <- fresh
976+ r2' =?= RCons p1 ty1 rest
977+ go ts1 ((p2, ty2) : ts2) r1' rest
978+ | otherwise = do rest <- fresh
979+ r1' =?= RCons p2 ty2 rest
980+ go ((p1, ty1) : ts1) ts2 rest r2'
981+subsumes' val ty1 ty2@(TypeApp obj _) | obj == tyObject = subsumes val ty2 ty1
982+subsumes' val ty1 ty2 = do
983+ ty1 =?= ty2
984+ return val
985+
986+