@@ -0,0 +1,1126 @@
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+ (everythingWithContext, mkQ)
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
65+import Control.Monad.State
66+import Control.Monad.Error
67+import Control.Monad.Unify
69+import Control.Applicative
70+import Control.Arrow (Arrow(..))
72+import qualified Data.Map as M
73+import qualified Data.HashMap.Strict as H
75+instance Partial Type where
77+ isUnknown (TUnknown u) = Just u
78+ isUnknown _ = Nothing
79+ unknowns = everythingOnTypes (++) go
81+ go (TUnknown u) = [u]
83+ ($?) sub = everywhereOnTypes go
85+ go t@(TUnknown u) = case H.lookup u (runSubstitution sub) of
90+instance Unifiable Check Type where
94+-- Unify two types, updating the current substitution
96+unifyTypes :: Type -> Type -> UnifyT Type Check ()
97+unifyTypes t1 t2 = rethrow (mkErrorStack ("Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2) Nothing <>) $
100+ unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
101+ unifyTypes' (TUnknown u) t = u =:= t
102+ unifyTypes' t (TUnknown u) = u =:= t
103+ unifyTypes' (SaturatedTypeSynonym name args) ty = do
104+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ args
106+ unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
107+ unifyTypes' (ForAll ident1 ty1 sc1) (ForAll ident2 ty2 sc2) =
109+ (Just sc1', Just sc2') -> do
110+ sko <- newSkolemConstant
111+ let sk1 = skolemize ident1 sko sc1' ty1
112+ let sk2 = skolemize ident2 sko sc2' ty2
113+ sk1 `unifyTypes` sk2
114+ _ -> error "Skolemized type variable was not given a scope"
115+ unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
116+ sko <- newSkolemConstant
117+ let sk = skolemize ident sko sc ty1
119+ unifyTypes' ForAll{} _ = throwError . strMsg $ "Skolem variable scope is unspecified"
120+ unifyTypes' ty f@ForAll{} = f `unifyTypes` ty
121+ unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
122+ unifyTypes' (TypeConstructor c1) (TypeConstructor c2) =
123+ guardWith (strMsg ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".")) (c1 == c2)
124+ unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
127+ unifyTypes' (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = return ()
128+ unifyTypes' r1@RCons{} r2 = unifyRows r1 r2
129+ unifyTypes' r1 r2@RCons{} = unifyRows r1 r2
130+ unifyTypes' r1@REmpty r2 = unifyRows r1 r2
131+ unifyTypes' r1 r2@REmpty = unifyRows r1 r2
132+ unifyTypes' t@(ConstrainedType _ _) _ = throwError . strMsg $ "Attempted to unify a constrained type " ++ prettyPrintType t ++ " with another type."
133+ unifyTypes' t3 t4@(ConstrainedType _ _) = unifyTypes' t4 t3
134+ unifyTypes' t3 t4 = throwError . strMsg $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
137+-- Unify two rows, updating the current substitution
139+-- Common labels are first identified, and unified. Remaining labels and types are unified with a
140+-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
143+unifyRows :: Type -> Type -> UnifyT Type Check ()
146+ (s1, r1') = rowToList r1
147+ (s2, r2') = rowToList r2
148+ int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
149+ sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
150+ sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
152+ forM_ int (uncurry (=?=))
153+ unifyRows' sd1 r1' sd2 r2'
155+ unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
156+ unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
157+ unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
158+ unifyRows' ((name, ty):row) r others u@(TUnknown un) = do
160+ forM_ row $ \(_, t) -> occursCheck un t
162+ u =?= RCons name ty u'
163+ unifyRows' row r others u'
164+ unifyRows' [] REmpty [] REmpty = return ()
165+ unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
166+ unifyRows' [] (Skolem _ s1 _) [] (Skolem _ s2 _) | s1 == s2 = return ()
167+ unifyRows' sd3 r3 sd4 r4 = throwError . strMsg $ "Cannot unify (" ++ prettyPrintRow (rowFromList (sd3, r3)) ++ ") with (" ++ prettyPrintRow (rowFromList (sd4, r4)) ++ ")"
170+-- Infer the types of multiple mutually-recursive values, and return elaborated values including
171+-- type class dictionaries and type annotations.
173+typesOf :: Maybe ModuleName -> ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
174+typesOf mainModuleName moduleName vals = do
175+ tys <- fmap tidyUp . liftUnify $ do
176+ (es, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName vals
178+ triple@(_, (_, ty)) <- typeForBindingGroupElement moduleName e dict untypedDict
179+ -- If --main is enabled, need to check that `main` has type Eff eff a for some eff, a
180+ when (Just moduleName == mainModuleName && fst e == Ident C.main) $ do
181+ [eff, a] <- replicateM 2 fresh
182+ ty =?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName [ProperName "Control", ProperName "Monad", ProperName "Eff"])) (ProperName "Eff"))) eff) a
185+ forM tys $ \(ident, (val, ty)) -> do
186+ -- Replace type class dictionary placeholders with actual dictionaries
187+ val' <- replaceTypeClassDictionaries moduleName val
188+ -- Check skolem variables did not escape their scope
189+ skolemEscapeCheck val'
190+ -- Remove type synonyms placeholders, remove duplicate row fields, and replace
191+ -- top-level unification variables with named type variables.
192+ let val'' = overTypes (desaturateAllTypeSynonyms . setifyAll) val'
193+ ty' = varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty
194+ return (ident, (val'', ty'))
196+ -- Apply the substitution that was returned from runUnify to both types and (type-annotated) values
197+ tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
199+typeDictionaryForBindingGroup :: ModuleName -> [(Ident, Value)] -> UnifyT Type Check ([(Ident, (Value, Maybe (Type, Bool)))], M.Map (ModuleName, Ident) (Type, NameKind), [(Ident, Type)])
200+typeDictionaryForBindingGroup moduleName vals = do
202+ -- Map each declaration to a name/value pair, with an optional type, if the declaration is typed
203+ es = map isTyped vals
204+ -- Filter the typed and untyped declarations
205+ typed = filter (isJust . snd . snd) es
206+ untyped = filter (isNothing . snd . snd) es
207+ -- Make a map of names to typed declarations
208+ typedDict = map (\(ident, (_, Just (ty, _))) -> (ident, ty)) typed
210+ -- Create fresh unification variables for the types of untyped declarations
211+ untypedNames <- replicateM (length untyped) fresh
214+ -- Make a map of names to the unification variables of untyped declarations
215+ untypedDict = zip (map fst untyped) untypedNames
216+ -- Create the dictionary of all name/type pairs, which will be added to the environment during type checking
217+ dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable))) $ typedDict ++ untypedDict)
218+ return (es, dict, untypedDict)
220+typeForBindingGroupElement :: ModuleName -> (Ident, (Value, Maybe (Type, Bool))) -> M.Map (ModuleName, Ident) (Type, NameKind) -> [(Ident, Type)] -> UnifyT Type Check (Ident, (Value, Type))
221+typeForBindingGroupElement moduleName e@(_, (val, _)) dict untypedDict = do
222+ -- If the declaration is a function, it has access to other values in the binding group.
223+ -- If not, the generated code might fail at runtime since those values might be undefined.
224+ let dict' = if isFunction val then dict else M.empty
226+ -- Typed declarations
227+ (ident, (val', Just (ty, checkType))) -> do
229+ kind <- liftCheck $ kindOf moduleName ty
230+ guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
231+ -- Check the type with the new names in scope
232+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
233+ val'' <- bindNames dict' $ if checkType
234+ then TypedValue True <$> check val' ty' <*> pure ty'
235+ else return (TypedValue False val' ty')
236+ return (ident, (val'', ty'))
237+ -- Untyped declarations
238+ (ident, (val', Nothing)) -> do
239+ -- Infer the type with the new names in scope
240+ TypedValue _ val'' ty <- bindNames dict' $ infer val'
241+ ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
242+ return (ident, (TypedValue True val'' ty, ty))
245+-- Check if a value introduces a function
247+isFunction :: Value -> Bool
248+isFunction (Abs _ _) = True
249+isFunction (TypedValue _ val _) = isFunction val
250+isFunction (PositionedValue _ val) = isFunction val
254+-- Check if a value contains a type annotation
256+isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
257+isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
258+isTyped (name, value) = (name, (value, Nothing))
261+-- Map a function over type annotations appearing inside a value
263+overTypes :: (Type -> Type) -> Value -> Value
264+overTypes f = let (_, f', _) = everywhereOnValues id g id in f'
267+ g (TypedValue checkTy val t) = TypedValue checkTy val (f t)
268+ g (TypeClassDictionary b (nm, tys) sco) = TypeClassDictionary b (nm, map f tys) sco
272+-- Replace type class dictionary placeholders with inferred type class dictionaries
274+replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
275+replaceTypeClassDictionaries mn =
276+ let (_, f, _) = everywhereOnValuesTopDownM return go return
279+ go (TypeClassDictionary trySuperclasses constraint dicts) = do
281+ entails env mn dicts constraint trySuperclasses
282+ go other = return other
285+-- A simplified representation of expressions which are used to represent type
286+-- class dictionaries at runtime, which can be compared for equality
290+ -- A dictionary which is brought into scope by a local constraint
292+ = LocalDictionaryValue (Qualified Ident)
294+ -- A dictionary which is brought into scope by an instance declaration
296+ | GlobalDictionaryValue (Qualified Ident)
298+ -- A dictionary which depends on other dictionaries
300+ | DependentDictionaryValue (Qualified Ident) [DictionaryValue]
302+ -- A subclass dictionary
304+ | SubclassDictionaryValue DictionaryValue (Qualified ProperName) Integer
305+ deriving (Show, Ord, Eq)
308+-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
309+-- return a type class dictionary reference.
311+entails :: Environment -> ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, [Type]) -> Bool -> Check Value
312+entails env moduleName context = solve (sortedNubBy canonicalizeDictionary (filter filterModule context))
314+ sortedNubBy :: (Ord k) => (v -> k) -> [v] -> [v]
315+ sortedNubBy f vs = M.elems (M.fromList (map (f &&& id) vs))
317+ -- Filter out type dictionaries which are in scope in the current module
318+ filterModule :: TypeClassDictionaryInScope -> Bool
319+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
320+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
321+ filterModule _ = False
323+ solve context' (className, tys) trySuperclasses =
325+ dicts = go trySuperclasses className tys
326+ in case sortedNubBy dictTrace (chooseSimplestDictionaries dicts) of
327+ [] -> throwError . strMsg $ "No instance found for " ++ show className ++ " " ++ unwords (map prettyPrintTypeAtom tys)
328+ [_] -> return $ dictionaryValueToValue $ head dicts
329+ _ -> throwError . strMsg $ "Overlapping instances found for " ++ show className ++ " " ++ unwords (map prettyPrintTypeAtom tys)
331+ go trySuperclasses' className' tys' =
332+ -- Look for regular type instances
333+ [ mkDictionary (canonicalizeDictionary tcd) args
335+ -- Make sure the type class name matches the one we are trying to satisfy
336+ , className' == tcdClassName tcd
337+ -- Make sure the type unifies with the type in the type instance definition
338+ , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' (tcdInstanceTypes tcd)
339+ -- Solve any necessary subgoals
340+ , args <- solveSubgoals subst (tcdDependencies tcd) ] ++
342+ -- Look for implementations via superclasses
343+ [ SubclassDictionaryValue suDict superclass index
345+ , (subclassName, (args, _, implies)) <- M.toList (typeClasses env)
346+ -- Try each superclass
347+ , (index, (superclass, suTyArgs)) <- zip [0..] implies
348+ -- Make sure the type class name matches the superclass name
349+ , className' == superclass
350+ -- Make sure the types unify with the types in the superclass implication
351+ , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' suTyArgs
352+ -- Finally, satisfy the subclass constraint
353+ , args' <- maybeToList $ mapM (applySubst subst . TypeVar) args
354+ , suDict <- go True subclassName args' ]
356+ -- Create dictionaries for subgoals which still need to be solved by calling go recursively
357+ -- E.g. the goal (Show a, Show b) => Show (Either a b) can be satisfied if the current type
358+ -- unifies with Either a b, and we can satisfy the subgoals Show a and Show b recursively.
359+ solveSubgoals :: [(String, Type)] -> Maybe [(Qualified ProperName, [Type])] -> [Maybe [DictionaryValue]]
360+ solveSubgoals _ Nothing = return Nothing
361+ solveSubgoals subst (Just subgoals) = do
362+ dict <- mapM (uncurry (go True) . second (map (replaceAllTypeVars subst))) subgoals
364+ -- Make a dictionary from subgoal dictionaries by applying the correct function
365+ mkDictionary :: Qualified Ident -> Maybe [DictionaryValue] -> DictionaryValue
366+ mkDictionary fnName Nothing = LocalDictionaryValue fnName
367+ mkDictionary fnName (Just []) = GlobalDictionaryValue fnName
368+ mkDictionary fnName (Just dicts) = DependentDictionaryValue fnName dicts
369+ -- Turn a DictionaryValue into a Value
370+ dictionaryValueToValue :: DictionaryValue -> Value
371+ dictionaryValueToValue (LocalDictionaryValue fnName) = Var fnName
372+ dictionaryValueToValue (GlobalDictionaryValue fnName) = App (Var fnName) (ObjectLiteral [])
373+ dictionaryValueToValue (DependentDictionaryValue fnName dicts) = foldl App (Var fnName) (map dictionaryValueToValue dicts)
374+ dictionaryValueToValue (SubclassDictionaryValue dict superclassName index) =
375+ App (Accessor (show superclassName ++ "_" ++ show index)
376+ (Accessor C.__superclasses (dictionaryValueToValue dict)))
378+ -- Ensure that a substitution is valid
379+ verifySubstitution :: [(String, Type)] -> Maybe [(String, Type)]
380+ verifySubstitution subst = do
381+ let grps = groupBy ((==) `on` fst) subst
382+ guard (all (pairwise (unifiesWith env) . map snd) grps)
383+ return $ map head grps
384+ -- Apply a substitution to a type
385+ applySubst :: [(String, Type)] -> Type -> Maybe Type
386+ applySubst subst = everywhereOnTypesM replace
388+ replace (TypeVar v) = lookup v subst
389+ replace other = Just other
390+ -- Choose the simplest DictionaryValues from a list of candidates
391+ -- The reason for this function is as follows:
392+ -- When considering overlapping instances, we don't want to consider the same dictionary
393+ -- to be an overlap of itself when obtained as a superclass of another class.
394+ -- Observing that we probably don't want to select a superclass instance when an instance
395+ -- is available directly, and that there is no way for a superclass instance to actually
396+ -- introduce an overlap that wouldn't have been there already, we simply remove dictionaries
397+ -- obtained as superclass instances if there are simpler instances available.
398+ chooseSimplestDictionaries :: [DictionaryValue] -> [DictionaryValue]
399+ chooseSimplestDictionaries ds = case filter isSimpleDictionaryValue ds of
402+ isSimpleDictionaryValue SubclassDictionaryValue{} = False
403+ isSimpleDictionaryValue (DependentDictionaryValue _ ds) = all isSimpleDictionaryValue ds
404+ isSimpleDictionaryValue _ = True
406+ -- Get the "trace" of a DictionaryValue - that is, remove all SubclassDictionaryValue
407+ -- data constructors
409+ dictTrace :: DictionaryValue -> DictionaryValue
410+ dictTrace (DependentDictionaryValue fnName dicts) = DependentDictionaryValue fnName $ map dictTrace dicts
411+ dictTrace (SubclassDictionaryValue dict _ _) = dictTrace dict
412+ dictTrace other = other
415+-- Check all values in a list pairwise match a predicate
417+pairwise :: (a -> a -> Bool) -> [a] -> Bool
419+pairwise _ [_] = True
420+pairwise p (x : xs) = all (p x) xs && pairwise p xs
423+-- Check that two types unify
425+unifiesWith :: Environment -> Type -> Type -> Bool
426+unifiesWith _ (TUnknown _) _ = True
427+unifiesWith _ _ (TUnknown _) = True
428+unifiesWith _ (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = True
429+unifiesWith _ (TypeVar v1) (TypeVar v2) | v1 == v2 = True
430+unifiesWith _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = True
431+unifiesWith e (TypeApp h1 t1) (TypeApp h2 t2) = unifiesWith e h1 h2 && unifiesWith e t1 t2
432+unifiesWith e (SaturatedTypeSynonym name args) t2 =
433+ case expandTypeSynonym' e name args of
435+ Right t1 -> unifiesWith e t1 t2
436+unifiesWith e t1 t2@(SaturatedTypeSynonym _ _) = unifiesWith e t2 t1
437+unifiesWith _ _ _ = False
440+-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
441+-- and return a substitution from type variables to types which makes the type heads unify.
443+typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
444+typeHeadsAreEqual _ _ (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = Just []
445+typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
446+typeHeadsAreEqual _ _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = Just []
447+typeHeadsAreEqual m e (TypeApp h1 t1) (TypeApp h2 t2) = (++) <$> typeHeadsAreEqual m e h1 h2 <*> typeHeadsAreEqual m e t1 t2
448+typeHeadsAreEqual m e (SaturatedTypeSynonym name args) t2 = case expandTypeSynonym' e name args of
450+ Right t1 -> typeHeadsAreEqual m e t1 t2
451+typeHeadsAreEqual _ _ _ _ = Nothing
454+-- Ensure skolem variables do not escape their scope
456+skolemEscapeCheck :: Value -> Check ()
457+skolemEscapeCheck (TypedValue False _ _) = return ()
458+skolemEscapeCheck root@TypedValue{} =
459+ -- Every skolem variable is created when a ForAll type is skolemized.
460+ -- This determines the scope of that skolem variable, which is copied from the SkolemScope
461+ -- field of the ForAll constructor.
462+ -- We traverse the tree top-down, and collect any SkolemScopes introduced by ForAlls.
463+ -- If a Skolem is encountered whose SkolemScope is not in the current list, we have found
464+ -- an escaped skolem variable.
465+ case everythingWithContext [] (++) (mkQ ((,) []) go) root of
467+ ((binding, val) : _) -> throwError $ mkErrorStack ("Rigid/skolem type variable " ++ maybe "" (("bound by " ++) . prettyPrintValue) binding ++ " has escaped.") (Just (ValueError val))
469+ go :: Value -> [(SkolemScope, Value)] -> ([(Maybe Value, Value)], [(SkolemScope, Value)])
470+ go val@(TypedValue _ _ (ForAll _ _ (Just sco))) scos = ([], (sco, val) : scos)
471+ go val@(TypedValue _ _ ty) scos = case collectSkolems ty \\ map fst scos of
472+ (sco : _) -> ([(findBindingScope sco, val)], scos)
475+ collectSkolems :: Type -> [SkolemScope]
476+ collectSkolems = nub . everythingOnTypes (++) collect
478+ collect (Skolem _ _ scope) = [scope]
480+ go _ scos = ([], scos)
481+ findBindingScope :: SkolemScope -> Maybe Value
482+ findBindingScope sco =
483+ let (_, f, _, _, _) = everythingOnValues mappend (const mempty) go' (const mempty) (const mempty) (const mempty)
484+ in getFirst $ f root
486+ go' val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = First (Just val)
488+skolemEscapeCheck val = throwError $ mkErrorStack "Untyped value passed to skolemEscapeCheck" (Just (ValueError val))
491+-- Ensure a row contains no duplicate labels
493+setify :: Type -> Type
494+setify = rowFromList . first (M.toList . M.fromList) . rowToList
497+-- \"Setify\" all rows occuring inside a value
499+setifyAll :: Type -> Type
500+setifyAll = everywhereOnTypes setify
503+-- Replace outermost unsolved unification variables with named type variables
505+varIfUnknown :: Type -> Type
507+ let unks = nub $ unknowns ty
508+ toName = (:) 't' . show
509+ ty' = everywhereOnTypes typeToVar ty
510+ typeToVar :: Type -> Type
511+ typeToVar (TUnknown u) = TypeVar (toName u)
513+ in mkForAll (sort . map toName $ unks) ty'
516+-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
517+-- or TypeClassDictionary values.
519+-- This is necessary during type checking to avoid unifying a polymorphic type with a
520+-- unification variable.
522+instantiatePolyTypeWithUnknowns :: Value -> Type -> UnifyT Type Check (Value, Type)
523+instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
524+ ty' <- replaceVarWithUnknown ident ty
525+ instantiatePolyTypeWithUnknowns val ty'
526+instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
527+ dicts <- getTypeClassDictionaries
528+ (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
529+ return (foldl App val (map (flip (TypeClassDictionary True) dicts) constraints), ty')
530+instantiatePolyTypeWithUnknowns val ty = return (val, ty)
533+-- Replace a single type variable with a new unification variable
535+replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
536+replaceVarWithUnknown ident ty = do
538+ return $ replaceTypeVars ident tu ty
541+-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
542+-- better error messages during unification.
544+replaceAllTypeSynonyms' :: Environment -> Type -> Either String Type
545+replaceAllTypeSynonyms' env d =
547+ syns = map (\(name, (args, _)) -> (name, length args)) . M.toList $ typeSynonyms env
549+ saturateAllTypeSynonyms syns d
551+replaceAllTypeSynonyms :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
552+replaceAllTypeSynonyms d = do
554+ either (throwError . strMsg) return $ replaceAllTypeSynonyms' env d
557+-- \"Desaturate\" @SaturatedTypeSynonym@s
559+desaturateAllTypeSynonyms :: Type -> Type
560+desaturateAllTypeSynonyms = everywhereOnTypes replaceSaturatedTypeSynonym
562+ replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
563+ replaceSaturatedTypeSynonym t = t
566+-- Replace a type synonym and its arguments with the aliased type
568+expandTypeSynonym' :: Environment -> Qualified ProperName -> [Type] -> Either String Type
569+expandTypeSynonym' env name args =
570+ case M.lookup name (typeSynonyms env) of
571+ Just (synArgs, body) -> do
572+ let repl = replaceAllTypeVars (zip synArgs args) body
573+ replaceAllTypeSynonyms' env repl
574+ Nothing -> error "Type synonym was not defined"
576+expandTypeSynonym :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Qualified ProperName -> [Type] -> m Type
577+expandTypeSynonym name args = do
579+ either (throwError . strMsg) return $ expandTypeSynonym' env name args
581+expandAllTypeSynonyms :: (Error e, Functor m, Applicative m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
582+expandAllTypeSynonyms = everywhereOnTypesTopDownM go
584+ go (SaturatedTypeSynonym name args) = expandTypeSynonym name args
585+ go other = return other
588+-- Ensure a set of property names and value does not contain duplicate labels
590+ensureNoDuplicateProperties :: (Error e, MonadError e m) => [(String, Value)] -> m ()
591+ensureNoDuplicateProperties ps = guardWith (strMsg "Duplicate property names") $ length (nub . map fst $ ps) == length ps
594+-- Infer a type for a value, rethrowing any error to provide a more useful error message
596+infer :: Value -> UnifyT Type Check Value
597+infer val = rethrow (mkErrorStack "Error inferring type of value" (Just (ValueError val)) <>) $ infer' val
600+-- Infer a type for a value
602+infer' :: Value -> UnifyT Type Check Value
603+infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
604+infer' v@(StringLiteral _) = return $ TypedValue True v tyString
605+infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
606+infer' (ArrayLiteral vals) = do
607+ ts <- mapM infer vals
609+ forM_ ts $ \(TypedValue _ _ t) -> els =?= TypeApp tyArray t
610+ return $ TypedValue True (ArrayLiteral ts) els
611+infer' (ObjectLiteral ps) = do
612+ ensureNoDuplicateProperties ps
613+ ts <- mapM (infer . snd) ps
614+ let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
615+ ty = TypeApp tyObject $ rowFromList (fields, REmpty)
616+ return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
617+infer' (ObjectUpdate o ps) = do
618+ ensureNoDuplicateProperties ps
620+ newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
621+ let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
622+ oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
623+ let oldTy = TypeApp tyObject $ rowFromList (oldTys, row)
624+ o' <- TypedValue True <$> check o oldTy <*> pure oldTy
625+ return $ TypedValue True (ObjectUpdate o' newVals) $ TypeApp tyObject $ rowFromList (newTys, row)
626+infer' (Accessor prop val) = do
627+ typed@(TypedValue _ _ objTy) <- infer val
628+ propTy <- inferProperty objTy prop
633+ _ <- subsumes Nothing objTy (TypeApp tyObject (RCons prop field rest))
634+ return $ TypedValue True (Accessor prop typed) field
635+ Just ty -> return $ TypedValue True (Accessor prop typed) ty
636+infer' (Abs (Left arg) ret) = do
638+ Just moduleName <- checkCurrentModule <$> get
639+ bindLocalVariables moduleName [(arg, ty)] $ do
640+ body@(TypedValue _ _ bodyTy) <- infer' ret
641+ return $ TypedValue True (Abs (Left arg) body) $ function ty bodyTy
642+infer' (Abs (Right _) _) = error "Binder was not desugared"
643+infer' (App f arg) = do
644+ f'@(TypedValue _ _ ft) <- infer f
645+ (ret, app) <- checkFunctionApplication f' ft arg Nothing
646+ return $ TypedValue True app ret
647+infer' (Var var) = do
648+ Just moduleName <- checkCurrentModule <$> get
649+ ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
651+ ConstrainedType constraints ty' -> do
652+ dicts <- getTypeClassDictionaries
653+ return $ TypedValue True (foldl App (Var var) (map (flip (TypeClassDictionary True) dicts) constraints)) ty'
654+ _ -> return $ TypedValue True (Var var) ty
655+infer' v@(Constructor c) = do
657+ case M.lookup c (dataConstructors env) of
658+ Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
659+ Just (_, ty) -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
660+ return $ TypedValue True v ty'
661+infer' (Case vals binders) = do
662+ ts <- mapM infer vals
664+ binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
665+ return $ TypedValue True (Case ts binders') ret
666+infer' (IfThenElse cond th el) = do
667+ cond' <- check cond tyBoolean
668+ v2@(TypedValue _ _ t2) <- infer th
669+ v3@(TypedValue _ _ t3) <- infer el
671+ return $ TypedValue True (IfThenElse cond' v2 v3) t2
672+infer' (Let ds val) = do
673+ (ds', val'@(TypedValue _ _ valTy)) <- inferLetBinding [] ds val infer
674+ return $ TypedValue True (Let ds' val') valTy
675+infer' (SuperClassDictionary className tys) = do
676+ dicts <- getTypeClassDictionaries
677+ return $ TypeClassDictionary False (className, tys) dicts
678+infer' (TypedValue checkType val ty) = do
679+ Just moduleName <- checkCurrentModule <$> get
680+ kind <- liftCheck $ kindOf moduleName ty
681+ guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
682+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
683+ val' <- if checkType then check val ty' else return val
684+ return $ TypedValue True val' ty'
685+infer' (PositionedValue pos val) = rethrowWithPosition pos $ infer' val
686+infer' _ = error "Invalid argument to infer"
688+inferLetBinding :: [Declaration] -> [Declaration] -> Value -> (Value -> UnifyT Type Check Value) -> UnifyT Type Check ([Declaration], Value)
689+inferLetBinding seen [] ret j = (,) seen <$> j ret
690+inferLetBinding seen (ValueDeclaration ident nameKind [] Nothing tv@(TypedValue checkType val ty) : rest) ret j = do
691+ Just moduleName <- checkCurrentModule <$> get
692+ kind <- liftCheck $ kindOf moduleName ty
693+ guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
694+ let dict = if isFunction val then M.singleton (moduleName, ident) (ty, nameKind) else M.empty
695+ TypedValue _ val' ty' <- if checkType then bindNames dict (check val ty) else return tv
696+ bindNames (M.singleton (moduleName, ident) (ty', nameKind)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] Nothing (TypedValue checkType val' ty')]) rest ret j
697+inferLetBinding seen (ValueDeclaration ident nameKind [] Nothing val : rest) ret j = do
699+ Just moduleName <- checkCurrentModule <$> get
700+ let dict = if isFunction val then M.singleton (moduleName, ident) (valTy, nameKind) else M.empty
701+ TypedValue _ val' valTy' <- bindNames dict $ infer val
703+ bindNames (M.singleton (moduleName, ident) (valTy', nameKind)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] Nothing val']) rest ret j
704+inferLetBinding seen (BindingGroupDeclaration ds : rest) ret j = do
705+ Just moduleName <- checkCurrentModule <$> get
706+ (es, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName (map (\(i, _, v) -> (i, v)) ds)
707+ ds' <- forM es $ \e -> do
708+ (ident, (val', _)) <- typeForBindingGroupElement moduleName e dict untypedDict
709+ return $ (ident, LocalVariable, val')
710+ bindNames dict $ inferLetBinding (seen ++ [BindingGroupDeclaration ds']) rest ret j
711+inferLetBinding seen (PositionedDeclaration pos d : ds) ret j = rethrowWithPosition pos $ do
712+ ((d' : ds'), val') <- inferLetBinding seen (d : ds) ret j
713+ return (PositionedDeclaration pos d' : ds', val')
714+inferLetBinding _ _ _ _ = error "Invalid argument to inferLetBinding"
717+-- Infer the type of a property inside a record with a given type
719+inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
720+inferProperty (TypeApp obj row) prop | obj == tyObject = do
721+ let (props, _) = rowToList row
722+ return $ lookup prop props
723+inferProperty (SaturatedTypeSynonym name args) prop = do
724+ replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
725+ inferProperty replaced prop
726+inferProperty (ForAll ident ty _) prop = do
727+ replaced <- replaceVarWithUnknown ident ty
728+ inferProperty replaced prop
729+inferProperty _ _ = return Nothing
732+-- Infer the types of variables brought into scope by a binder
734+inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
735+inferBinder _ NullBinder = return M.empty
736+inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
737+inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
738+inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
739+inferBinder val (VarBinder name) = return $ M.singleton name val
740+inferBinder val (ConstructorBinder ctor binders) = do
742+ case M.lookup ctor (dataConstructors env) of
744+ (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contain constraints") ty
745+ fn' <- replaceAllTypeSynonyms fn
749+ _ <- subsumes Nothing val ty'
751+ go (binder : binders') (TypeApp (TypeApp t obj) ret) | t == tyFunction =
752+ M.union <$> inferBinder obj binder <*> go binders' ret
753+ go _ _ = throwError . strMsg $ "Wrong number of arguments to constructor " ++ show ctor
754+ _ -> throwError . strMsg $ "Constructor " ++ show ctor ++ " is not defined"
755+inferBinder val (ObjectBinder props) = do
758+ m1 <- inferRowProperties row rest props
759+ val =?= TypeApp tyObject row
762+ inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
763+ inferRowProperties nrow row [] = nrow =?= row >> return M.empty
764+ inferRowProperties nrow row ((name, binder):binders) = do
766+ m1 <- inferBinder propTy binder
767+ m2 <- inferRowProperties nrow (RCons name propTy row) binders
768+ return $ m1 `M.union` m2
769+inferBinder val (ArrayBinder binders) = do
771+ m1 <- M.unions <$> mapM (inferBinder el) binders
772+ val =?= TypeApp tyArray el
774+inferBinder val (ConsBinder headBinder tailBinder) = do
776+ m1 <- inferBinder el headBinder
777+ m2 <- inferBinder val tailBinder
778+ val =?= TypeApp tyArray el
779+ return $ m1 `M.union` m2
780+inferBinder val (NamedBinder name binder) = do
781+ m <- inferBinder val binder
782+ return $ M.insert name val m
783+inferBinder val (PositionedBinder pos binder) =
784+ rethrowWithPosition pos $ inferBinder val binder
787+-- Check the types of the return values in a set of binders in a case statement
789+checkBinders :: [Type] -> Type -> [CaseAlternative] -> UnifyT Type Check [CaseAlternative]
790+checkBinders _ _ [] = return []
791+checkBinders nvals ret (CaseAlternative binders grd val : bs) = do
792+ Just moduleName <- checkCurrentModule <$> get
793+ m1 <- M.unions <$> zipWithM inferBinder nvals binders
794+ r <- bindLocalVariables moduleName (M.toList m1) $ do
795+ val' <- TypedValue True <$> check val ret <*> pure ret
797+ Nothing -> return $ CaseAlternative binders Nothing val'
799+ g' <- check g tyBoolean
800+ return $ CaseAlternative binders (Just g') val'
801+ rs <- checkBinders nvals ret bs
805+-- Generate a new skolem constant
807+newSkolemConstant :: UnifyT Type Check Int
808+newSkolemConstant = fresh'
811+-- Generate a new skolem scope
813+newSkolemScope :: UnifyT Type Check SkolemScope
814+newSkolemScope = SkolemScope <$> fresh'
817+-- Skolemize a type variable by replacing its instances with fresh skolem constants
819+skolemize :: String -> Int -> SkolemScope -> Type -> Type
820+skolemize ident sko scope = replaceTypeVars ident (Skolem ident sko scope)
823+-- This function has one purpose - to skolemize type variables appearing in a
824+-- SuperClassDictionary placeholder. These type variables are somewhat unique since they are the
825+-- only example of scoped type variables.
827+skolemizeTypesInValue :: String -> Int -> SkolemScope -> Value -> Value
828+skolemizeTypesInValue ident sko scope = let (_, f, _) = everywhereOnValues id go id in f
830+ go (SuperClassDictionary c ts) = SuperClassDictionary c (map (skolemize ident sko scope) ts)
834+-- Introduce skolem scope at every occurence of a ForAll
836+introduceSkolemScope :: Type -> UnifyT Type Check Type
837+introduceSkolemScope = everywhereOnTypesM go
839+ go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
840+ go other = return other
843+-- Check the type of a value, rethrowing errors to provide a better error message
845+check :: Value -> Type -> UnifyT Type Check Value
846+check val ty = rethrow (mkErrorStack errorMessage (Just (ValueError val)) <>) $ check' val ty
849+ "Error checking type of term " ++
850+ prettyPrintValue val ++
855+-- Check the type of a value
857+check' :: Value -> Type -> UnifyT Type Check Value
858+check' val (ForAll ident ty _) = do
859+ scope <- newSkolemScope
860+ sko <- newSkolemConstant
861+ let sk = skolemize ident sko scope ty
862+ let skVal = skolemizeTypesInValue ident sko scope val
863+ val' <- check skVal sk
864+ return $ TypedValue True val' (ForAll ident ty (Just scope))
865+check' val t@(ConstrainedType constraints ty) = do
866+ dictNames <- forM constraints $ \(Qualified _ (ProperName className), _) -> do
867+ n <- liftCheck freshDictionaryName
868+ return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
869+ val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
870+ TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
871+ constraints) $ check val ty
872+ return $ TypedValue True (foldr (Abs . Left) val' dictNames) t
873+check' val (SaturatedTypeSynonym name args) = do
874+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
876+check' val u@(TUnknown _) = do
877+ val'@(TypedValue _ _ ty) <- infer val
878+ -- Don't unify an unknown with an inferred polytype
879+ (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
881+ return $ TypedValue True val'' ty'
882+check' v@(NumericLiteral _) t | t == tyNumber =
883+ return $ TypedValue True v t
884+check' v@(StringLiteral _) t | t == tyString =
885+ return $ TypedValue True v t
886+check' v@(BooleanLiteral _) t | t == tyBoolean =
887+ return $ TypedValue True v t
888+check' (ArrayLiteral vals) t@(TypeApp a ty) = do
890+ array <- ArrayLiteral <$> forM vals (`check` ty)
891+ return $ TypedValue True array t
892+check' (Abs (Left arg) ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
893+ Just moduleName <- checkCurrentModule <$> get
894+ ret' <- bindLocalVariables moduleName [(arg, argTy)] $ check ret retTy
895+ return $ TypedValue True (Abs (Left arg) ret') ty
896+check' (Abs (Right _) _) _ = error "Binder was not desugared"
897+check' (App f arg) ret = do
898+ f'@(TypedValue _ _ ft) <- infer f
899+ (_, app) <- checkFunctionApplication f' ft arg (Just ret)
900+ return $ TypedValue True app ret
901+check' v@(Var var) ty = do
902+ Just moduleName <- checkCurrentModule <$> get
903+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
904+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
905+ v' <- subsumes (Just v) repl ty'
907+ Nothing -> throwError . strMsg $ "Unable to check type subsumption"
908+ Just v'' -> return $ TypedValue True v'' ty'
909+check' (SuperClassDictionary className tys) _ = do
911+ -- Here, we replace a placeholder for a superclass dictionary with a regular
912+ -- TypeClassDictionary placeholder. The reason we do this is that it is necessary to have the
913+ -- correct super instance dictionaries in scope, and these are not available when the type class
914+ -- declaration gets desugared.
916+ -- Note also that the first argument to TypeClassDictionary is False, meaning we _do not_ want
917+ -- to consider superclass instances when searching for this dictionary - doing so might lead
918+ -- to traversing a cycle in the instance graph.
920+ dicts <- getTypeClassDictionaries
921+ return $ TypeClassDictionary False (className, tys) dicts
922+check' (TypedValue checkType val ty1) ty2 = do
923+ Just moduleName <- checkCurrentModule <$> get
924+ kind <- liftCheck $ kindOf moduleName ty1
925+ guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
926+ ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
927+ val' <- subsumes (Just val) ty1' ty2
929+ Nothing -> throwError . strMsg $ "Unable to check type subsumption"
931+ val''' <- if checkType then check val'' ty1' else return val''
932+ return $ TypedValue checkType (TypedValue True val''' ty1) ty2
933+check' (Case vals binders) ret = do
934+ vals' <- mapM infer vals
935+ let ts = map (\(TypedValue _ _ t) -> t) vals'
936+ binders' <- checkBinders ts ret binders
937+ return $ TypedValue True (Case vals' binders') ret
938+check' (IfThenElse cond th el) ty = do
939+ cond' <- check cond tyBoolean
942+ return $ TypedValue True (IfThenElse cond' th' el') ty
943+check' (ObjectLiteral ps) t@(TypeApp obj row) | obj == tyObject = do
944+ ensureNoDuplicateProperties ps
945+ ps' <- checkProperties ps row False
946+ return $ TypedValue True (ObjectLiteral ps') t
947+check' (ObjectUpdate obj ps) t@(TypeApp o row) | o == tyObject = do
948+ ensureNoDuplicateProperties ps
949+ us <- zip (map fst ps) <$> replicateM (length ps) fresh
950+ let (propsToCheck, rest) = rowToList row
951+ propsToRemove = map fst ps
952+ remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
953+ obj' <- check obj (TypeApp tyObject (rowFromList (us ++ remainingProps, rest)))
954+ ps' <- checkProperties ps row True
955+ return $ TypedValue True (ObjectUpdate obj' ps') t
956+check' (Accessor prop val) ty = do
958+ val' <- check val (TypeApp tyObject (RCons prop ty rest))
959+ return $ TypedValue True (Accessor prop val') ty
960+check' (Constructor c) ty = do
962+ case M.lookup c (dataConstructors env) of
963+ Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
965+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
966+ _ <- subsumes Nothing repl ty
967+ return $ TypedValue True (Constructor c) ty
968+check' (Let ds val) ty = do
969+ (ds', val') <- inferLetBinding [] ds val (flip check ty)
970+ return $ TypedValue True (Let ds' val') ty
971+check' val ty | containsTypeSynonyms ty = do
972+ ty' <- introduceSkolemScope <=< expandAllTypeSynonyms $ ty
974+check' (PositionedValue pos val) ty =
975+ rethrowWithPosition pos $ check val ty
976+check' val ty = throwError $ mkErrorStack ("Value does not have type " ++ prettyPrintType ty) (Just (ValueError val))
978+containsTypeSynonyms :: Type -> Bool
979+containsTypeSynonyms = everythingOnTypes (||) go where
980+ go (SaturatedTypeSynonym _ _) = True
984+-- Check the type of a collection of named record fields
986+-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
988+checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Type Check [(String, Value)]
989+checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
990+ go [] [] REmpty = return []
991+ go [] [] u@(TUnknown _) = do u =?= REmpty
993+ go [] [] (Skolem _ _ _) | lax = return []
994+ go [] ((p, _): _) _ | lax = return []
995+ | otherwise = throwError $ mkErrorStack ("Object does not have property " ++ p) (Just (ValueError (ObjectLiteral ps)))
996+ go ((p,_):_) [] REmpty = throwError $ mkErrorStack ("Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row) (Just (ValueError (ObjectLiteral ps)))
997+ go ((p,v):ps') [] u@(TUnknown _) = do
998+ v'@(TypedValue _ _ ty) <- infer v
1000+ u =?= RCons p ty rest
1001+ ps'' <- go ps' [] rest
1002+ return $ (p, v') : ps''
1003+ go ((p,v):ps') ts r =
1004+ case lookup p ts of
1006+ v'@(TypedValue _ _ ty) <- infer v
1008+ r =?= RCons p ty rest
1009+ ps'' <- go ps' ts rest
1010+ return $ (p, v') : ps''
1013+ ps'' <- go ps' (delete (p, ty) ts) r
1014+ return $ (p, v') : ps''
1015+ go _ _ _ = throwError $ mkErrorStack ("Object does not have type " ++ prettyPrintType (TypeApp tyObject row)) (Just (ValueError (ObjectLiteral ps)))
1018+-- Check the type of a function application, rethrowing errors to provide a better error message
1020+checkFunctionApplication :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
1021+checkFunctionApplication fn fnTy arg ret = rethrow (mkErrorStack errorMessage (Just (ValueError fn)) <>) $ checkFunctionApplication' fn fnTy arg ret
1023+ errorMessage = "Error applying function of type "
1024+ ++ prettyPrintType fnTy
1025+ ++ " to argument " ++ prettyPrintValue arg
1028+-- Check the type of a function application
1030+checkFunctionApplication' :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
1031+checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg ret = do
1032+ tyFunction' =?= tyFunction
1033+ _ <- maybe (return Nothing) (subsumes Nothing retTy) ret
1034+ subst <- unifyCurrentSubstitution <$> UnifyT get
1035+ arg' <- check arg (subst $? argTy)
1036+ return (retTy, App fn arg')
1037+checkFunctionApplication' fn (ForAll ident ty _) arg ret = do
1038+ replaced <- replaceVarWithUnknown ident ty
1039+ checkFunctionApplication fn replaced arg ret
1040+checkFunctionApplication' fn u@(TUnknown _) arg ret = do
1042+ TypedValue _ arg' t <- infer arg
1043+ (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
1044+ return $ TypedValue True arg'' t'
1045+ let ty = (\(TypedValue _ _ t) -> t) arg'
1046+ ret' <- maybe fresh return ret
1047+ u =?= function ty ret'
1048+ return (ret', App fn arg')
1049+checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
1050+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1051+ checkFunctionApplication fn ty arg ret
1052+checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
1053+ dicts <- getTypeClassDictionaries
1054+ checkFunctionApplication' (foldl App fn (map (flip (TypeClassDictionary True) dicts) constraints)) fnTy arg ret
1055+checkFunctionApplication' _ fnTy arg _ = throwError . strMsg $ "Cannot apply a function of type "
1056+ ++ prettyPrintType fnTy
1057+ ++ " to argument " ++ prettyPrintValue arg
1060+-- Check whether one type subsumes another, rethrowing errors to provide a better error message
1062+subsumes :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
1063+subsumes val ty1 ty2 = rethrow (mkErrorStack errorMessage (ValueError <$> val) <>) $ subsumes' val ty1 ty2
1065+ errorMessage = "Error checking that type "
1066+ ++ prettyPrintType ty1
1067+ ++ " subsumes type "
1068+ ++ prettyPrintType ty2
1071+-- Check whether one type subsumes another
1073+subsumes' :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
1074+subsumes' val (ForAll ident ty1 _) ty2 = do
1075+ replaced <- replaceVarWithUnknown ident ty1
1076+ subsumes val replaced ty2
1077+subsumes' val ty1 (ForAll ident ty2 sco) =
1080+ sko <- newSkolemConstant
1081+ let sk = skolemize ident sko sco' ty2
1082+ subsumes val ty1 sk
1083+ Nothing -> throwError . strMsg $ "Skolem variable scope is unspecified"
1084+subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
1085+ _ <- subsumes Nothing arg2 arg1
1086+ _ <- subsumes Nothing ret1 ret2
1088+subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
1089+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1090+ subsumes val ty1 ty2
1091+subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
1092+ ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1093+ subsumes val ty1 ty2
1094+subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
1095+ dicts <- getTypeClassDictionaries
1096+ _ <- subsumes' Nothing ty1 ty2
1097+ return . Just $ foldl App val (map (flip (TypeClassDictionary True) dicts) constraints)
1098+subsumes' val (TypeApp f1 r1) (TypeApp f2 r2) | f1 == tyObject && f2 == tyObject = do
1100+ (ts1, r1') = rowToList r1
1101+ (ts2, r2') = rowToList r2
1102+ ts1' = sortBy (comparing fst) ts1
1103+ ts2' = sortBy (comparing fst) ts2
1104+ go ts1' ts2' r1' r2'
1107+ go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
1108+ go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
1109+ go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
1110+ | p1 == p2 = do _ <- subsumes Nothing ty1 ty2
1112+ | p1 < p2 = do rest <- fresh
1113+ r2' =?= RCons p1 ty1 rest
1114+ go ts1 ((p2, ty2) : ts2) r1' rest
1115+ | otherwise = do rest <- fresh
1116+ r1' =?= RCons p2 ty2 rest
1117+ go ((p1, ty1) : ts1) ts2 rest r2'
1118+subsumes' val ty1 ty2@(TypeApp obj _) | obj == tyObject = subsumes val ty2 ty1
1119+subsumes' val ty1 ty2 = do