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