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