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