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