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