@@ -1,1128 +0,0 @@
1−-----------------------------------------------------------------------------
3−-- Module : Language.PureScript.TypeChecker.Types
4−-- Copyright : (c) Phil Freeman 2013
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
12−-- This module implements the type checker
14−-----------------------------------------------------------------------------
16−{-# OPTIONS_GHC -fno-warn-orphans #-}
17−{-# LANGUAGE FlexibleInstances #-}
18−{-# LANGUAGE FlexibleContexts #-}
19−{-# LANGUAGE MultiParamTypeClasses #-}
21−module Language.PureScript.TypeChecker.Types (
26− The following functions represent the corresponding type checking judgements:
29− Synthesize a type for a value
32− Check a value has a given type
35− Check an object with a given type contains specified properties
37− checkFunctionApplication
38− Check a function of a given type returns a value of another type when applied to its arguments
41− Check a type subsumes another type
45−import Data.Maybe (maybeToList, isNothing, isJust, fromMaybe)
46−import Data.Function (on)
47−import Data.Ord (comparing)
50−import Language.PureScript.Declarations
51−import Language.PureScript.Types
52−import Language.PureScript.Kinds
53−import Language.PureScript.Names
54−import Language.PureScript.TypeClassDictionaries
55−import Language.PureScript.TypeChecker.Monad
56−import Language.PureScript.TypeChecker.Kinds
57−import Language.PureScript.TypeChecker.Synonyms
58−import Language.PureScript.Pretty
59−import Language.PureScript.Environment
60−import Language.PureScript.Errors
61−import qualified Language.PureScript.Constants as C
63−import Control.Monad.State
64−import Control.Monad.Error
65−import Control.Monad.Unify
67−import Control.Applicative
68−import Control.Arrow (Arrow(..))
70−import qualified Data.Map as M
71−import qualified Data.HashMap.Strict as H
73−instance Partial Type where
75− isUnknown (TUnknown u) = Just u
76− isUnknown _ = Nothing
77− unknowns = everythingOnTypes (++) go
79− go (TUnknown u) = [u]
81− ($?) sub = everywhereOnTypes go
83− go t@(TUnknown u) = case H.lookup u (runSubstitution sub) of
88−instance Unifiable Check Type where
92−-- Unify two types, updating the current substitution
94−unifyTypes :: Type -> Type -> UnifyT Type Check ()
95−unifyTypes t1 t2 = rethrow (mkErrorStack ("Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2) Nothing <>) $
98− unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
99− unifyTypes' (TUnknown u) t = u =:= t
100− unifyTypes' t (TUnknown u) = u =:= t
101− unifyTypes' (SaturatedTypeSynonym name args) ty = do
102− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ args
104− unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
105− unifyTypes' (ForAll ident1 ty1 sc1) (ForAll ident2 ty2 sc2) =
107− (Just sc1', Just sc2') -> do
108− sko <- newSkolemConstant
109− let sk1 = skolemize ident1 sko sc1' ty1
110− let sk2 = skolemize ident2 sko sc2' ty2
111− sk1 `unifyTypes` sk2
112− _ -> error "Skolemized type variable was not given a scope"
113− unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
114− sko <- newSkolemConstant
115− let sk = skolemize ident sko sc ty1
117− unifyTypes' ForAll{} _ = throwError . strMsg $ "Skolem variable scope is unspecified"
118− unifyTypes' ty f@ForAll{} = f `unifyTypes` ty
119− unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
120− unifyTypes' (TypeConstructor c1) (TypeConstructor c2) =
121− guardWith (strMsg ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".")) (c1 == c2)
122− unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
125− unifyTypes' (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = return ()
126− unifyTypes' r1@RCons{} r2 = unifyRows r1 r2
127− unifyTypes' r1 r2@RCons{} = unifyRows r1 r2
128− unifyTypes' r1@REmpty r2 = unifyRows r1 r2
129− unifyTypes' r1 r2@REmpty = unifyRows r1 r2
130− unifyTypes' t@(ConstrainedType _ _) _ = throwError . strMsg $ "Attempted to unify a constrained type " ++ prettyPrintType t ++ " with another type."
131− unifyTypes' t3 t4@(ConstrainedType _ _) = unifyTypes' t4 t3
132− unifyTypes' t3 t4 = throwError . strMsg $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
135−-- Unify two rows, updating the current substitution
137−-- Common labels are first identified, and unified. Remaining labels and types are unified with a
138−-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
141−unifyRows :: Type -> Type -> UnifyT Type Check ()
144− (s1, r1') = rowToList r1
145− (s2, r2') = rowToList r2
146− int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
147− sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
148− sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
150− forM_ int (uncurry (=?=))
151− unifyRows' sd1 r1' sd2 r2'
153− unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
154− unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
155− unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
156− unifyRows' ((name, ty):row) r others u@(TUnknown un) = do
158− forM_ row $ \(_, t) -> occursCheck un t
160− u =?= RCons name ty u'
161− unifyRows' row r others u'
162− unifyRows' [] REmpty [] REmpty = return ()
163− unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
164− unifyRows' [] (Skolem _ s1 _) [] (Skolem _ s2 _) | s1 == s2 = return ()
165− unifyRows' sd3 r3 sd4 r4 = throwError . strMsg $ "Cannot unify (" ++ prettyPrintRow (rowFromList (sd3, r3)) ++ ") with (" ++ prettyPrintRow (rowFromList (sd4, r4)) ++ ")"
168−-- Infer the types of multiple mutually-recursive values, and return elaborated values including
169−-- type class dictionaries and type annotations.
171−typesOf :: Maybe ModuleName -> ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
172−typesOf mainModuleName moduleName vals = do
173− tys <- fmap tidyUp . liftUnify $ do
174− (es, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName vals
176− triple@(_, (_, ty)) <- typeForBindingGroupElement moduleName e dict untypedDict
177− -- If --main is enabled, need to check that `main` has type Eff eff a for some eff, a
178− when (Just moduleName == mainModuleName && fst e == Ident C.main) $ do
179− [eff, a] <- replicateM 2 fresh
180− ty =?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName [ProperName "Control", ProperName "Monad", ProperName "Eff"])) (ProperName "Eff"))) eff) a
183− forM tys $ \(ident, (val, ty)) -> do
184− -- Replace type class dictionary placeholders with actual dictionaries
185− val' <- replaceTypeClassDictionaries moduleName val
186− -- Check skolem variables did not escape their scope
187− skolemEscapeCheck val'
188− -- Remove type synonyms placeholders, remove duplicate row fields, and replace
189− -- top-level unification variables with named type variables.
190− let val'' = overTypes (desaturateAllTypeSynonyms . setifyAll) val'
191− ty' = varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty
192− return (ident, (val'', ty'))
194− -- Apply the substitution that was returned from runUnify to both types and (type-annotated) values
195− tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
197−typeDictionaryForBindingGroup :: ModuleName -> [(Ident, Value)] -> UnifyT Type Check ([(Ident, (Value, Maybe (Type, Bool)))], M.Map (ModuleName, Ident) (Type, NameKind), [(Ident, Type)])
198−typeDictionaryForBindingGroup moduleName vals = do
200− -- Map each declaration to a name/value pair, with an optional type, if the declaration is typed
201− es = map isTyped vals
202− -- Filter the typed and untyped declarations
203− typed = filter (isJust . snd . snd) es
204− untyped = filter (isNothing . snd . snd) es
205− -- Make a map of names to typed declarations
206− typedDict = map (\(ident, (_, Just (ty, _))) -> (ident, ty)) typed
208− -- Create fresh unification variables for the types of untyped declarations
209− untypedNames <- replicateM (length untyped) fresh
212− -- Make a map of names to the unification variables of untyped declarations
213− untypedDict = zip (map fst untyped) untypedNames
214− -- Create the dictionary of all name/type pairs, which will be added to the environment during type checking
215− dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable))) $ typedDict ++ untypedDict)
216− return (es, dict, untypedDict)
218−typeForBindingGroupElement :: ModuleName -> (Ident, (Value, Maybe (Type, Bool))) -> M.Map (ModuleName, Ident) (Type, NameKind) -> [(Ident, Type)] -> UnifyT Type Check (Ident, (Value, Type))
219−typeForBindingGroupElement moduleName e@(_, (val, _)) dict untypedDict = do
220− -- If the declaration is a function, it has access to other values in the binding group.
221− -- If not, the generated code might fail at runtime since those values might be undefined.
222− let dict' = if isFunction val then dict else M.empty
224− -- Typed declarations
225− (ident, (val', Just (ty, checkType))) -> do
227− kind <- liftCheck $ kindOf moduleName ty
228− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
229− -- Check the type with the new names in scope
230− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
231− val'' <- bindNames dict' $ if checkType
232− then TypedValue True <$> check val' ty' <*> pure ty'
233− else return (TypedValue False val' ty')
234− return (ident, (val'', ty'))
235− -- Untyped declarations
236− (ident, (val', Nothing)) -> do
237− -- Infer the type with the new names in scope
238− TypedValue _ val'' ty <- bindNames dict' $ infer val'
239− ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
240− return (ident, (TypedValue True val'' ty, ty))
243−-- Check if a value introduces a function
245−isFunction :: Value -> Bool
246−isFunction (Abs _ _) = True
247−isFunction (TypedValue _ val _) = isFunction val
248−isFunction (PositionedValue _ val) = isFunction val
252−-- Check if a value contains a type annotation
254−isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
255−isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
256−isTyped (name, value) = (name, (value, Nothing))
259−-- Map a function over type annotations appearing inside a value
261−overTypes :: (Type -> Type) -> Value -> Value
262−overTypes f = let (_, f', _) = everywhereOnValues id g id in f'
265− g (TypedValue checkTy val t) = TypedValue checkTy val (f t)
266− g (TypeClassDictionary b (nm, tys) sco) = TypeClassDictionary b (nm, map f tys) sco
270−-- Replace type class dictionary placeholders with inferred type class dictionaries
272−replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
273−replaceTypeClassDictionaries mn =
274− let (_, f, _) = everywhereOnValuesTopDownM return go return
277− go (TypeClassDictionary trySuperclasses constraint dicts) = do
279− entails env mn dicts constraint trySuperclasses
280− go other = return other
283−-- A simplified representation of expressions which are used to represent type
284−-- class dictionaries at runtime, which can be compared for equality
288− -- A dictionary which is brought into scope by a local constraint
290− = LocalDictionaryValue (Qualified Ident)
292− -- A dictionary which is brought into scope by an instance declaration
294− | GlobalDictionaryValue (Qualified Ident)
296− -- A dictionary which depends on other dictionaries
298− | DependentDictionaryValue (Qualified Ident) [DictionaryValue]
300− -- A subclass dictionary
302− | SubclassDictionaryValue DictionaryValue (Qualified ProperName) Integer
303− deriving (Show, Ord, Eq)
306−-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
307−-- return a type class dictionary reference.
309−entails :: Environment -> ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, [Type]) -> Bool -> Check Value
310−entails env moduleName context = solve (sortedNubBy canonicalizeDictionary (filter filterModule context))
312− sortedNubBy :: (Ord k) => (v -> k) -> [v] -> [v]
313− sortedNubBy f vs = M.elems (M.fromList (map (f &&& id) vs))
315− -- Filter out type dictionaries which are in scope in the current module
316− filterModule :: TypeClassDictionaryInScope -> Bool
317− filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
318− filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
319− filterModule _ = False
321− solve context' (className, tys) trySuperclasses =
323− dicts = go trySuperclasses className tys
324− in case sortedNubBy dictTrace (chooseSimplestDictionaries dicts) of
325− [] -> throwError . strMsg $ "No instance found for " ++ show className ++ " " ++ unwords (map prettyPrintTypeAtom tys)
326− [_] -> return $ dictionaryValueToValue $ head dicts
327− _ -> throwError . strMsg $ "Overlapping instances found for " ++ show className ++ " " ++ unwords (map prettyPrintTypeAtom tys)
329− go trySuperclasses' className' tys' =
330− -- Look for regular type instances
331− [ mkDictionary (canonicalizeDictionary tcd) args
333− -- Make sure the type class name matches the one we are trying to satisfy
334− , className' == tcdClassName tcd
335− -- Make sure the type unifies with the type in the type instance definition
336− , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' (tcdInstanceTypes tcd)
337− -- Solve any necessary subgoals
338− , args <- solveSubgoals subst (tcdDependencies tcd) ] ++
340− -- Look for implementations via superclasses
341− [ SubclassDictionaryValue suDict superclass index
343− , (subclassName, (args, _, implies)) <- M.toList (typeClasses env)
344− -- Try each superclass
345− , (index, (superclass, suTyArgs)) <- zip [0..] implies
346− -- Make sure the type class name matches the superclass name
347− , className' == superclass
348− -- Make sure the types unify with the types in the superclass implication
349− , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' suTyArgs
350− -- Finally, satisfy the subclass constraint
351− , args' <- maybeToList $ mapM (applySubst subst . TypeVar) args
352− , suDict <- go True subclassName args' ]
354− -- Create dictionaries for subgoals which still need to be solved by calling go recursively
355− -- E.g. the goal (Show a, Show b) => Show (Either a b) can be satisfied if the current type
356− -- unifies with Either a b, and we can satisfy the subgoals Show a and Show b recursively.
357− solveSubgoals :: [(String, Type)] -> Maybe [(Qualified ProperName, [Type])] -> [Maybe [DictionaryValue]]
358− solveSubgoals _ Nothing = return Nothing
359− solveSubgoals subst (Just subgoals) = do
360− dict <- mapM (uncurry (go True) . second (map (replaceAllTypeVars subst))) subgoals
362− -- Make a dictionary from subgoal dictionaries by applying the correct function
363− mkDictionary :: Qualified Ident -> Maybe [DictionaryValue] -> DictionaryValue
364− mkDictionary fnName Nothing = LocalDictionaryValue fnName
365− mkDictionary fnName (Just []) = GlobalDictionaryValue fnName
366− mkDictionary fnName (Just dicts) = DependentDictionaryValue fnName dicts
367− -- Turn a DictionaryValue into a Value
368− dictionaryValueToValue :: DictionaryValue -> Value
369− dictionaryValueToValue (LocalDictionaryValue fnName) = Var fnName
370− dictionaryValueToValue (GlobalDictionaryValue fnName) = App (Var fnName) (ObjectLiteral [])
371− dictionaryValueToValue (DependentDictionaryValue fnName dicts) = foldl App (Var fnName) (map dictionaryValueToValue dicts)
372− dictionaryValueToValue (SubclassDictionaryValue dict superclassName index) =
373− App (Accessor (show superclassName ++ "_" ++ show index)
374− (Accessor C.__superclasses (dictionaryValueToValue dict)))
376− -- Ensure that a substitution is valid
377− verifySubstitution :: [(String, Type)] -> Maybe [(String, Type)]
378− verifySubstitution subst = do
379− let grps = groupBy ((==) `on` fst) subst
380− guard (all (pairwise (unifiesWith env) . map snd) grps)
381− return $ map head grps
382− -- Apply a substitution to a type
383− applySubst :: [(String, Type)] -> Type -> Maybe Type
384− applySubst subst = everywhereOnTypesM replace
386− replace (TypeVar v) = lookup v subst
387− replace other = Just other
388− -- Choose the simplest DictionaryValues from a list of candidates
389− -- The reason for this function is as follows:
390− -- When considering overlapping instances, we don't want to consider the same dictionary
391− -- to be an overlap of itself when obtained as a superclass of another class.
392− -- Observing that we probably don't want to select a superclass instance when an instance
393− -- is available directly, and that there is no way for a superclass instance to actually
394− -- introduce an overlap that wouldn't have been there already, we simply remove dictionaries
395− -- obtained as superclass instances if there are simpler instances available.
396− chooseSimplestDictionaries :: [DictionaryValue] -> [DictionaryValue]
397− chooseSimplestDictionaries ds = case filter isSimpleDictionaryValue ds of
400− isSimpleDictionaryValue SubclassDictionaryValue{} = False
401− isSimpleDictionaryValue (DependentDictionaryValue _ ds) = all isSimpleDictionaryValue ds
402− isSimpleDictionaryValue _ = True
404− -- Get the "trace" of a DictionaryValue - that is, remove all SubclassDictionaryValue
405− -- data constructors
407− dictTrace :: DictionaryValue -> DictionaryValue
408− dictTrace (DependentDictionaryValue fnName dicts) = DependentDictionaryValue fnName $ map dictTrace dicts
409− dictTrace (SubclassDictionaryValue dict _ _) = dictTrace dict
410− dictTrace other = other
413−-- Check all values in a list pairwise match a predicate
415−pairwise :: (a -> a -> Bool) -> [a] -> Bool
417−pairwise _ [_] = True
418−pairwise p (x : xs) = all (p x) xs && pairwise p xs
421−-- Check that two types unify
423−unifiesWith :: Environment -> Type -> Type -> Bool
424−unifiesWith _ (TUnknown _) _ = True
425−unifiesWith _ _ (TUnknown _) = True
426−unifiesWith _ (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = True
427−unifiesWith _ (TypeVar v1) (TypeVar v2) | v1 == v2 = True
428−unifiesWith _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = True
429−unifiesWith e (TypeApp h1 t1) (TypeApp h2 t2) = unifiesWith e h1 h2 && unifiesWith e t1 t2
430−unifiesWith e (SaturatedTypeSynonym name args) t2 =
431− case expandTypeSynonym' e name args of
433− Right t1 -> unifiesWith e t1 t2
434−unifiesWith e t1 t2@(SaturatedTypeSynonym _ _) = unifiesWith e t2 t1
435−unifiesWith _ _ _ = False
438−-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
439−-- and return a substitution from type variables to types which makes the type heads unify.
441−typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
442−typeHeadsAreEqual _ _ (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = Just []
443−typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
444−typeHeadsAreEqual _ _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = Just []
445−typeHeadsAreEqual m e (TypeApp h1 t1) (TypeApp h2 t2) = (++) <$> typeHeadsAreEqual m e h1 h2 <*> typeHeadsAreEqual m e t1 t2
446−typeHeadsAreEqual m e (SaturatedTypeSynonym name args) t2 = case expandTypeSynonym' e name args of
448− Right t1 -> typeHeadsAreEqual m e t1 t2
449−typeHeadsAreEqual _ _ _ _ = Nothing
452−-- Ensure skolem variables do not escape their scope
454−skolemEscapeCheck :: Value -> Check ()
455−skolemEscapeCheck (TypedValue False _ _) = return ()
456−skolemEscapeCheck root@TypedValue{} =
457− -- Every skolem variable is created when a ForAll type is skolemized.
458− -- This determines the scope of that skolem variable, which is copied from the SkolemScope
459− -- field of the ForAll constructor.
460− -- We traverse the tree top-down, and collect any SkolemScopes introduced by ForAlls.
461− -- If a Skolem is encountered whose SkolemScope is not in the current list, we have found
462− -- an escaped skolem variable.
463− let (_, f, _, _, _) = everythingWithContextOnValues [] [] (++) def go def def def
466− ((binding, val) : _) -> throwError $ mkErrorStack ("Rigid/skolem type variable " ++ maybe "" (("bound by " ++) . prettyPrintValue) binding ++ " has escaped.") (Just (ValueError val))
470− go :: [(SkolemScope, Value)] -> Value -> ([(SkolemScope, Value)], [(Maybe Value, Value)])
471− go scos val@(TypedValue _ _ (ForAll _ _ (Just sco))) = ((sco, val) : scos, [])
472− go scos val@(TypedValue _ _ ty) = case collectSkolems ty \\ map fst scos of
473− (sco : _) -> (scos, [(findBindingScope sco, val)])
476− collectSkolems :: Type -> [SkolemScope]
477− collectSkolems = nub . everythingOnTypes (++) collect
479− collect (Skolem _ _ scope) = [scope]
481− go scos _ = (scos, [])
482− findBindingScope :: SkolemScope -> Maybe Value
483− findBindingScope sco =
484− let (_, f, _, _, _) = everythingOnValues mappend (const mempty) go' (const mempty) (const mempty) (const mempty)
485− in getFirst $ f root
487− go' val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = First (Just val)
489−skolemEscapeCheck val = throwError $ mkErrorStack "Untyped value passed to skolemEscapeCheck" (Just (ValueError val))
492−-- Ensure a row contains no duplicate labels
494−setify :: Type -> Type
495−setify = rowFromList . first (M.toList . M.fromList) . rowToList
498−-- \"Setify\" all rows occuring inside a value
500−setifyAll :: Type -> Type
501−setifyAll = everywhereOnTypes setify
504−-- Replace outermost unsolved unification variables with named type variables
506−varIfUnknown :: Type -> Type
508− let unks = nub $ unknowns ty
509− toName = (:) 't' . show
510− ty' = everywhereOnTypes typeToVar ty
511− typeToVar :: Type -> Type
512− typeToVar (TUnknown u) = TypeVar (toName u)
514− in mkForAll (sort . map toName $ unks) ty'
517−-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
518−-- or TypeClassDictionary values.
520−-- This is necessary during type checking to avoid unifying a polymorphic type with a
521−-- unification variable.
523−instantiatePolyTypeWithUnknowns :: Value -> Type -> UnifyT Type Check (Value, Type)
524−instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
525− ty' <- replaceVarWithUnknown ident ty
526− instantiatePolyTypeWithUnknowns val ty'
527−instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
528− dicts <- getTypeClassDictionaries
529− (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
530− return (foldl App val (map (flip (TypeClassDictionary True) dicts) constraints), ty')
531−instantiatePolyTypeWithUnknowns val ty = return (val, ty)
534−-- Replace a single type variable with a new unification variable
536−replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
537−replaceVarWithUnknown ident ty = do
539− return $ replaceTypeVars ident tu ty
542−-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
543−-- better error messages during unification.
545−replaceAllTypeSynonyms' :: Environment -> Type -> Either String Type
546−replaceAllTypeSynonyms' env d =
548− syns = map (\(name, (args, _)) -> (name, length args)) . M.toList $ typeSynonyms env
550− saturateAllTypeSynonyms syns d
552−replaceAllTypeSynonyms :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
553−replaceAllTypeSynonyms d = do
555− either (throwError . strMsg) return $ replaceAllTypeSynonyms' env d
558−-- \"Desaturate\" @SaturatedTypeSynonym@s
560−desaturateAllTypeSynonyms :: Type -> Type
561−desaturateAllTypeSynonyms = everywhereOnTypes replaceSaturatedTypeSynonym
563− replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
564− replaceSaturatedTypeSynonym t = t
567−-- Replace a type synonym and its arguments with the aliased type
569−expandTypeSynonym' :: Environment -> Qualified ProperName -> [Type] -> Either String Type
570−expandTypeSynonym' env name args =
571− case M.lookup name (typeSynonyms env) of
572− Just (synArgs, body) -> do
573− let repl = replaceAllTypeVars (zip synArgs args) body
574− replaceAllTypeSynonyms' env repl
575− Nothing -> error "Type synonym was not defined"
577−expandTypeSynonym :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Qualified ProperName -> [Type] -> m Type
578−expandTypeSynonym name args = do
580− either (throwError . strMsg) return $ expandTypeSynonym' env name args
582−expandAllTypeSynonyms :: (Error e, Functor m, Applicative m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
583−expandAllTypeSynonyms = everywhereOnTypesTopDownM go
585− go (SaturatedTypeSynonym name args) = expandTypeSynonym name args
586− go other = return other
589−-- Ensure a set of property names and value does not contain duplicate labels
591−ensureNoDuplicateProperties :: (Error e, MonadError e m) => [(String, Value)] -> m ()
592−ensureNoDuplicateProperties ps = guardWith (strMsg "Duplicate property names") $ length (nub . map fst $ ps) == length ps
595−-- Infer a type for a value, rethrowing any error to provide a more useful error message
597−infer :: Value -> UnifyT Type Check Value
598−infer val = rethrow (mkErrorStack "Error inferring type of value" (Just (ValueError val)) <>) $ infer' val
601−-- Infer a type for a value
603−infer' :: Value -> UnifyT Type Check Value
604−infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
605−infer' v@(StringLiteral _) = return $ TypedValue True v tyString
606−infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
607−infer' (ArrayLiteral vals) = do
608− ts <- mapM infer vals
610− forM_ ts $ \(TypedValue _ _ t) -> els =?= TypeApp tyArray t
611− return $ TypedValue True (ArrayLiteral ts) els
612−infer' (ObjectLiteral ps) = do
613− ensureNoDuplicateProperties ps
614− ts <- mapM (infer . snd) ps
615− let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
616− ty = TypeApp tyObject $ rowFromList (fields, REmpty)
617− return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
618−infer' (ObjectUpdate o ps) = do
619− ensureNoDuplicateProperties ps
621− newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
622− let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
623− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
624− let oldTy = TypeApp tyObject $ rowFromList (oldTys, row)
625− o' <- TypedValue True <$> check o oldTy <*> pure oldTy
626− return $ TypedValue True (ObjectUpdate o' newVals) $ TypeApp tyObject $ rowFromList (newTys, row)
627−infer' (Accessor prop val) = do
628− typed@(TypedValue _ _ objTy) <- infer val
629− propTy <- inferProperty objTy prop
634− _ <- subsumes Nothing objTy (TypeApp tyObject (RCons prop field rest))
635− return $ TypedValue True (Accessor prop typed) field
636− Just ty -> return $ TypedValue True (Accessor prop typed) ty
637−infer' (Abs (Left arg) ret) = do
639− Just moduleName <- checkCurrentModule <$> get
640− bindLocalVariables moduleName [(arg, ty)] $ do
641− body@(TypedValue _ _ bodyTy) <- infer' ret
642− return $ TypedValue True (Abs (Left arg) body) $ function ty bodyTy
643−infer' (Abs (Right _) _) = error "Binder was not desugared"
644−infer' (App f arg) = do
645− f'@(TypedValue _ _ ft) <- infer f
646− (ret, app) <- checkFunctionApplication f' ft arg Nothing
647− return $ TypedValue True app ret
648−infer' (Var var) = do
649− Just moduleName <- checkCurrentModule <$> get
650− ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
652− ConstrainedType constraints ty' -> do
653− dicts <- getTypeClassDictionaries
654− return $ TypedValue True (foldl App (Var var) (map (flip (TypeClassDictionary True) dicts) constraints)) ty'
655− _ -> return $ TypedValue True (Var var) ty
656−infer' v@(Constructor c) = do
658− case M.lookup c (dataConstructors env) of
659− Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
660− Just (_, ty) -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
661− return $ TypedValue True v ty'
662−infer' (Case vals binders) = do
663− ts <- mapM infer vals
665− binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
666− return $ TypedValue True (Case ts binders') ret
667−infer' (IfThenElse cond th el) = do
668− cond' <- check cond tyBoolean
669− v2@(TypedValue _ _ t2) <- infer th
670− v3@(TypedValue _ _ t3) <- infer el
672− return $ TypedValue True (IfThenElse cond' v2 v3) t2
673−infer' (Let ds val) = do
674− (ds', val'@(TypedValue _ _ valTy)) <- inferLetBinding [] ds val infer
675− return $ TypedValue True (Let ds' val') valTy
676−infer' (SuperClassDictionary className tys) = do
677− dicts <- getTypeClassDictionaries
678− return $ TypeClassDictionary False (className, tys) dicts
679−infer' (TypedValue checkType val ty) = do
680− Just moduleName <- checkCurrentModule <$> get
681− kind <- liftCheck $ kindOf moduleName ty
682− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
683− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
684− val' <- if checkType then check val ty' else return val
685− return $ TypedValue True val' ty'
686−infer' (PositionedValue pos val) = rethrowWithPosition pos $ infer' val
687−infer' _ = error "Invalid argument to infer"
689−inferLetBinding :: [Declaration] -> [Declaration] -> Value -> (Value -> UnifyT Type Check Value) -> UnifyT Type Check ([Declaration], Value)
690−inferLetBinding seen [] ret j = (,) seen <$> j ret
691−inferLetBinding seen (ValueDeclaration ident nameKind [] Nothing tv@(TypedValue checkType val ty) : rest) ret j = do
692− Just moduleName <- checkCurrentModule <$> get
693− kind <- liftCheck $ kindOf moduleName ty
694− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
695− let dict = if isFunction val then M.singleton (moduleName, ident) (ty, nameKind) else M.empty
696− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
697− TypedValue _ val' ty'' <- if checkType then bindNames dict (check val ty') else return tv
698− bindNames (M.singleton (moduleName, ident) (ty'', nameKind)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] Nothing (TypedValue checkType val' ty'')]) rest ret j
699−inferLetBinding seen (ValueDeclaration ident nameKind [] Nothing val : rest) ret j = do
701− Just moduleName <- checkCurrentModule <$> get
702− let dict = if isFunction val then M.singleton (moduleName, ident) (valTy, nameKind) else M.empty
703− TypedValue _ val' valTy' <- bindNames dict $ infer val
705− bindNames (M.singleton (moduleName, ident) (valTy', nameKind)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] Nothing val']) rest ret j
706−inferLetBinding seen (BindingGroupDeclaration ds : rest) ret j = do
707− Just moduleName <- checkCurrentModule <$> get
708− (es, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName (map (\(i, _, v) -> (i, v)) ds)
709− ds' <- forM es $ \e -> do
710− (ident, (val', _)) <- typeForBindingGroupElement moduleName e dict untypedDict
711− return $ (ident, LocalVariable, val')
712− bindNames dict $ inferLetBinding (seen ++ [BindingGroupDeclaration ds']) rest ret j
713−inferLetBinding seen (PositionedDeclaration pos d : ds) ret j = rethrowWithPosition pos $ do
714− ((d' : ds'), val') <- inferLetBinding seen (d : ds) ret j
715− return (PositionedDeclaration pos d' : ds', val')
716−inferLetBinding _ _ _ _ = error "Invalid argument to inferLetBinding"
719−-- Infer the type of a property inside a record with a given type
721−inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
722−inferProperty (TypeApp obj row) prop | obj == tyObject = do
723− let (props, _) = rowToList row
724− return $ lookup prop props
725−inferProperty (SaturatedTypeSynonym name args) prop = do
726− replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
727− inferProperty replaced prop
728−inferProperty (ForAll ident ty _) prop = do
729− replaced <- replaceVarWithUnknown ident ty
730− inferProperty replaced prop
731−inferProperty _ _ = return Nothing
734−-- Infer the types of variables brought into scope by a binder
736−inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
737−inferBinder _ NullBinder = return M.empty
738−inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
739−inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
740−inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
741−inferBinder val (VarBinder name) = return $ M.singleton name val
742−inferBinder val (ConstructorBinder ctor binders) = do
744− case M.lookup ctor (dataConstructors env) of
746− (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contain constraints") ty
747− fn' <- replaceAllTypeSynonyms fn
751− _ <- subsumes Nothing val ty'
753− go (binder : binders') (TypeApp (TypeApp t obj) ret) | t == tyFunction =
754− M.union <$> inferBinder obj binder <*> go binders' ret
755− go _ _ = throwError . strMsg $ "Wrong number of arguments to constructor " ++ show ctor
756− _ -> throwError . strMsg $ "Constructor " ++ show ctor ++ " is not defined"
757−inferBinder val (ObjectBinder props) = do
760− m1 <- inferRowProperties row rest props
761− val =?= TypeApp tyObject row
764− inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
765− inferRowProperties nrow row [] = nrow =?= row >> return M.empty
766− inferRowProperties nrow row ((name, binder):binders) = do
768− m1 <- inferBinder propTy binder
769− m2 <- inferRowProperties nrow (RCons name propTy row) binders
770− return $ m1 `M.union` m2
771−inferBinder val (ArrayBinder binders) = do
773− m1 <- M.unions <$> mapM (inferBinder el) binders
774− val =?= TypeApp tyArray el
776−inferBinder val (ConsBinder headBinder tailBinder) = do
778− m1 <- inferBinder el headBinder
779− m2 <- inferBinder val tailBinder
780− val =?= TypeApp tyArray el
781− return $ m1 `M.union` m2
782−inferBinder val (NamedBinder name binder) = do
783− m <- inferBinder val binder
784− return $ M.insert name val m
785−inferBinder val (PositionedBinder pos binder) =
786− rethrowWithPosition pos $ inferBinder val binder
789−-- Check the types of the return values in a set of binders in a case statement
791−checkBinders :: [Type] -> Type -> [CaseAlternative] -> UnifyT Type Check [CaseAlternative]
792−checkBinders _ _ [] = return []
793−checkBinders nvals ret (CaseAlternative binders grd val : bs) = do
794− Just moduleName <- checkCurrentModule <$> get
795− m1 <- M.unions <$> zipWithM inferBinder nvals binders
796− r <- bindLocalVariables moduleName (M.toList m1) $ do
797− val' <- TypedValue True <$> check val ret <*> pure ret
799− Nothing -> return $ CaseAlternative binders Nothing val'
801− g' <- check g tyBoolean
802− return $ CaseAlternative binders (Just g') val'
803− rs <- checkBinders nvals ret bs
807−-- Generate a new skolem constant
809−newSkolemConstant :: UnifyT Type Check Int
810−newSkolemConstant = fresh'
813−-- Generate a new skolem scope
815−newSkolemScope :: UnifyT Type Check SkolemScope
816−newSkolemScope = SkolemScope <$> fresh'
819−-- Skolemize a type variable by replacing its instances with fresh skolem constants
821−skolemize :: String -> Int -> SkolemScope -> Type -> Type
822−skolemize ident sko scope = replaceTypeVars ident (Skolem ident sko scope)
825−-- This function has one purpose - to skolemize type variables appearing in a
826−-- SuperClassDictionary placeholder. These type variables are somewhat unique since they are the
827−-- only example of scoped type variables.
829−skolemizeTypesInValue :: String -> Int -> SkolemScope -> Value -> Value
830−skolemizeTypesInValue ident sko scope = let (_, f, _) = everywhereOnValues id go id in f
832− go (SuperClassDictionary c ts) = SuperClassDictionary c (map (skolemize ident sko scope) ts)
836−-- Introduce skolem scope at every occurence of a ForAll
838−introduceSkolemScope :: Type -> UnifyT Type Check Type
839−introduceSkolemScope = everywhereOnTypesM go
841− go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
842− go other = return other
845−-- Check the type of a value, rethrowing errors to provide a better error message
847−check :: Value -> Type -> UnifyT Type Check Value
848−check val ty = rethrow (mkErrorStack errorMessage (Just (ValueError val)) <>) $ check' val ty
851− "Error checking type of term " ++
852− prettyPrintValue val ++
857−-- Check the type of a value
859−check' :: Value -> Type -> UnifyT Type Check Value
860−check' val (ForAll ident ty _) = do
861− scope <- newSkolemScope
862− sko <- newSkolemConstant
863− let sk = skolemize ident sko scope ty
864− let skVal = skolemizeTypesInValue ident sko scope val
865− val' <- check skVal sk
866− return $ TypedValue True val' (ForAll ident ty (Just scope))
867−check' val t@(ConstrainedType constraints ty) = do
868− dictNames <- forM constraints $ \(Qualified _ (ProperName className), _) -> do
869− n <- liftCheck freshDictionaryName
870− return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
871− val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
872− TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
873− constraints) $ check val ty
874− return $ TypedValue True (foldr (Abs . Left) val' dictNames) t
875−check' val (SaturatedTypeSynonym name args) = do
876− ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
878−check' val u@(TUnknown _) = do
879− val'@(TypedValue _ _ ty) <- infer val
880− -- Don't unify an unknown with an inferred polytype
881− (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
883− return $ TypedValue True val'' ty'
884−check' v@(NumericLiteral _) t | t == tyNumber =
885− return $ TypedValue True v t
886−check' v@(StringLiteral _) t | t == tyString =
887− return $ TypedValue True v t
888−check' v@(BooleanLiteral _) t | t == tyBoolean =
889− return $ TypedValue True v t
890−check' (ArrayLiteral vals) t@(TypeApp a ty) = do
892− array <- ArrayLiteral <$> forM vals (`check` ty)
893− return $ TypedValue True array t
894−check' (Abs (Left arg) ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
895− Just moduleName <- checkCurrentModule <$> get
896− ret' <- bindLocalVariables moduleName [(arg, argTy)] $ check ret retTy
897− return $ TypedValue True (Abs (Left arg) ret') ty
898−check' (Abs (Right _) _) _ = error "Binder was not desugared"
899−check' (App f arg) ret = do
900− f'@(TypedValue _ _ ft) <- infer f
901− (_, app) <- checkFunctionApplication f' ft arg (Just ret)
902− return $ TypedValue True app ret
903−check' v@(Var var) ty = do
904− Just moduleName <- checkCurrentModule <$> get
905− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
906− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
907− v' <- subsumes (Just v) repl ty'
909− Nothing -> throwError . strMsg $ "Unable to check type subsumption"
910− Just v'' -> return $ TypedValue True v'' ty'
911−check' (SuperClassDictionary className tys) _ = do
913− -- Here, we replace a placeholder for a superclass dictionary with a regular
914− -- TypeClassDictionary placeholder. The reason we do this is that it is necessary to have the
915− -- correct super instance dictionaries in scope, and these are not available when the type class
916− -- declaration gets desugared.
918− -- Note also that the first argument to TypeClassDictionary is False, meaning we _do not_ want
919− -- to consider superclass instances when searching for this dictionary - doing so might lead
920− -- to traversing a cycle in the instance graph.
922− dicts <- getTypeClassDictionaries
923− return $ TypeClassDictionary False (className, tys) dicts
924−check' (TypedValue checkType val ty1) ty2 = do
925− Just moduleName <- checkCurrentModule <$> get
926− kind <- liftCheck $ kindOf moduleName ty1
927− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
928− ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
929− val' <- subsumes (Just val) ty1' ty2
931− Nothing -> throwError . strMsg $ "Unable to check type subsumption"
933− val''' <- if checkType then check val'' ty1' else return val''
934− return $ TypedValue checkType (TypedValue True val''' ty1) ty2
935−check' (Case vals binders) ret = do
936− vals' <- mapM infer vals
937− let ts = map (\(TypedValue _ _ t) -> t) vals'
938− binders' <- checkBinders ts ret binders
939− return $ TypedValue True (Case vals' binders') ret
940−check' (IfThenElse cond th el) ty = do
941− cond' <- check cond tyBoolean
944− return $ TypedValue True (IfThenElse cond' th' el') ty
945−check' (ObjectLiteral ps) t@(TypeApp obj row) | obj == tyObject = do
946− ensureNoDuplicateProperties ps
947− ps' <- checkProperties ps row False
948− return $ TypedValue True (ObjectLiteral ps') t
949−check' (ObjectUpdate obj ps) t@(TypeApp o row) | o == tyObject = do
950− ensureNoDuplicateProperties ps
951− us <- zip (map fst ps) <$> replicateM (length ps) fresh
952− let (propsToCheck, rest) = rowToList row
953− propsToRemove = map fst ps
954− remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
955− obj' <- check obj (TypeApp tyObject (rowFromList (us ++ remainingProps, rest)))
956− ps' <- checkProperties ps row True
957− return $ TypedValue True (ObjectUpdate obj' ps') t
958−check' (Accessor prop val) ty = do
960− val' <- check val (TypeApp tyObject (RCons prop ty rest))
961− return $ TypedValue True (Accessor prop val') ty
962−check' (Constructor c) ty = do
964− case M.lookup c (dataConstructors env) of
965− Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
967− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
968− _ <- subsumes Nothing repl ty
969− return $ TypedValue True (Constructor c) ty
970−check' (Let ds val) ty = do
971− (ds', val') <- inferLetBinding [] ds val (flip check ty)
972− return $ TypedValue True (Let ds' val') ty
973−check' val ty | containsTypeSynonyms ty = do
974− ty' <- introduceSkolemScope <=< expandAllTypeSynonyms $ ty
976−check' (PositionedValue pos val) ty =
977− rethrowWithPosition pos $ check val ty
978−check' val ty = throwError $ mkErrorStack ("Value does not have type " ++ prettyPrintType ty) (Just (ValueError val))
980−containsTypeSynonyms :: Type -> Bool
981−containsTypeSynonyms = everythingOnTypes (||) go where
982− go (SaturatedTypeSynonym _ _) = True
986−-- Check the type of a collection of named record fields
988−-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
990−checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Type Check [(String, Value)]
991−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
992− go [] [] REmpty = return []
993− go [] [] u@(TUnknown _) = do u =?= REmpty
995− go [] [] (Skolem _ _ _) | lax = return []
996− go [] ((p, _): _) _ | lax = return []
997− | otherwise = throwError $ mkErrorStack ("Object does not have property " ++ p) (Just (ValueError (ObjectLiteral ps)))
998− go ((p,_):_) [] REmpty = throwError $ mkErrorStack ("Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row) (Just (ValueError (ObjectLiteral ps)))
999− go ((p,v):ps') [] u@(TUnknown _) = do
1000− v'@(TypedValue _ _ ty) <- infer v
1002− u =?= RCons p ty rest
1003− ps'' <- go ps' [] rest
1004− return $ (p, v') : ps''
1005− go ((p,v):ps') ts r =
1006− case lookup p ts of
1008− v'@(TypedValue _ _ ty) <- infer v
1010− r =?= RCons p ty rest
1011− ps'' <- go ps' ts rest
1012− return $ (p, v') : ps''
1015− ps'' <- go ps' (delete (p, ty) ts) r
1016− return $ (p, v') : ps''
1017− go _ _ _ = throwError $ mkErrorStack ("Object does not have type " ++ prettyPrintType (TypeApp tyObject row)) (Just (ValueError (ObjectLiteral ps)))
1020−-- Check the type of a function application, rethrowing errors to provide a better error message
1022−checkFunctionApplication :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
1023−checkFunctionApplication fn fnTy arg ret = rethrow (mkErrorStack errorMessage (Just (ValueError fn)) <>) $ checkFunctionApplication' fn fnTy arg ret
1025− errorMessage = "Error applying function of type "
1026− ++ prettyPrintType fnTy
1027− ++ " to argument " ++ prettyPrintValue arg
1030−-- Check the type of a function application
1032−checkFunctionApplication' :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
1033−checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg ret = do
1034− tyFunction' =?= tyFunction
1035− _ <- maybe (return Nothing) (subsumes Nothing retTy) ret
1036− subst <- unifyCurrentSubstitution <$> UnifyT get
1037− arg' <- check arg (subst $? argTy)
1038− return (retTy, App fn arg')
1039−checkFunctionApplication' fn (ForAll ident ty _) arg ret = do
1040− replaced <- replaceVarWithUnknown ident ty
1041− checkFunctionApplication fn replaced arg ret
1042−checkFunctionApplication' fn u@(TUnknown _) arg ret = do
1044− TypedValue _ arg' t <- infer arg
1045− (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
1046− return $ TypedValue True arg'' t'
1047− let ty = (\(TypedValue _ _ t) -> t) arg'
1048− ret' <- maybe fresh return ret
1049− u =?= function ty ret'
1050− return (ret', App fn arg')
1051−checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
1052− ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1053− checkFunctionApplication fn ty arg ret
1054−checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
1055− dicts <- getTypeClassDictionaries
1056− checkFunctionApplication' (foldl App fn (map (flip (TypeClassDictionary True) dicts) constraints)) fnTy arg ret
1057−checkFunctionApplication' _ fnTy arg _ = throwError . strMsg $ "Cannot apply a function of type "
1058− ++ prettyPrintType fnTy
1059− ++ " to argument " ++ prettyPrintValue arg
1062−-- Check whether one type subsumes another, rethrowing errors to provide a better error message
1064−subsumes :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
1065−subsumes val ty1 ty2 = rethrow (mkErrorStack errorMessage (ValueError <$> val) <>) $ subsumes' val ty1 ty2
1067− errorMessage = "Error checking that type "
1068− ++ prettyPrintType ty1
1069− ++ " subsumes type "
1070− ++ prettyPrintType ty2
1073−-- Check whether one type subsumes another
1075−subsumes' :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
1076−subsumes' val (ForAll ident ty1 _) ty2 = do
1077− replaced <- replaceVarWithUnknown ident ty1
1078− subsumes val replaced ty2
1079−subsumes' val ty1 (ForAll ident ty2 sco) =
1082− sko <- newSkolemConstant
1083− let sk = skolemize ident sko sco' ty2
1084− subsumes val ty1 sk
1085− Nothing -> throwError . strMsg $ "Skolem variable scope is unspecified"
1086−subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
1087− _ <- subsumes Nothing arg2 arg1
1088− _ <- subsumes Nothing ret1 ret2
1090−subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
1091− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1092− subsumes val ty1 ty2
1093−subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
1094− ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1095− subsumes val ty1 ty2
1096−subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
1097− dicts <- getTypeClassDictionaries
1098− _ <- subsumes' Nothing ty1 ty2
1099− return . Just $ foldl App val (map (flip (TypeClassDictionary True) dicts) constraints)
1100−subsumes' val (TypeApp f1 r1) (TypeApp f2 r2) | f1 == tyObject && f2 == tyObject = do
1102− (ts1, r1') = rowToList r1
1103− (ts2, r2') = rowToList r2
1104− ts1' = sortBy (comparing fst) ts1
1105− ts2' = sortBy (comparing fst) ts2
1106− go ts1' ts2' r1' r2'
1109− go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
1110− go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
1111− go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
1112− | p1 == p2 = do _ <- subsumes Nothing ty1 ty2
1114− | p1 < p2 = do rest <- fresh
1115− r2' =?= RCons p1 ty1 rest
1116− go ts1 ((p2, ty2) : ts2) r1' rest
1117− | otherwise = do rest <- fresh
1118− r1' =?= RCons p2 ty2 rest
1119− go ((p1, ty1) : ts1) ts2 rest r2'
1120−subsumes' val ty1 ty2@(TypeApp obj _) | obj == tyObject = subsumes val ty2 ty1
1121−subsumes' val ty1 ty2 = do