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