@@ -0,0 +1,1218 @@
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, fromMaybe)
46+import Data.Function (on)
47+import Data.Ord (comparing)
49+import Data.Either (lefts, rights)
51+import Language.PureScript.Declarations
52+import Language.PureScript.Types
53+import Language.PureScript.Kinds
54+import Language.PureScript.Names
55+import Language.PureScript.TypeClassDictionaries
56+import Language.PureScript.TypeChecker.Monad
57+import Language.PureScript.TypeChecker.Kinds
58+import Language.PureScript.TypeChecker.Synonyms
59+import Language.PureScript.Pretty
60+import Language.PureScript.Environment
61+import Language.PureScript.Errors
62+import qualified Language.PureScript.Constants as C
64+import Control.Monad.State
65+import Control.Monad.Error
66+import Control.Monad.Unify
68+import Control.Applicative
69+import Control.Arrow (Arrow(..))
71+import qualified Data.Map as M
72+import qualified Data.HashMap.Strict as H
74+instance Partial Type where
76+ isUnknown (TUnknown u) = Just u
77+ isUnknown _ = Nothing
78+ unknowns = everythingOnTypes (++) go
80+ go (TUnknown u) = [u]
82+ ($?) sub = everywhereOnTypes go
84+ go t@(TUnknown u) = case H.lookup u (runSubstitution sub) of
89+instance Unifiable Check Type where
93+-- Unify two types, updating the current substitution
95+unifyTypes :: Type -> Type -> UnifyT Type Check ()
96+unifyTypes t1 t2 = rethrow (mkErrorStack ("Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2) Nothing <>) $
99+ unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
100+ unifyTypes' (TUnknown u) t = u =:= t
101+ unifyTypes' t (TUnknown u) = u =:= t
102+ unifyTypes' (SaturatedTypeSynonym name args) ty = do
103+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ args
105+ unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
106+ unifyTypes' (ForAll ident1 ty1 sc1) (ForAll ident2 ty2 sc2) =
108+ (Just sc1', Just sc2') -> do
109+ sko <- newSkolemConstant
110+ let sk1 = skolemize ident1 sko sc1' ty1
111+ let sk2 = skolemize ident2 sko sc2' ty2
112+ sk1 `unifyTypes` sk2
113+ _ -> error "Skolemized type variable was not given a scope"
114+ unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
115+ sko <- newSkolemConstant
116+ let sk = skolemize ident sko sc ty1
118+ unifyTypes' ForAll{} _ = throwError . strMsg $ "Skolem variable scope is unspecified"
119+ unifyTypes' ty f@ForAll{} = f `unifyTypes` ty
120+ unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
121+ unifyTypes' (TypeConstructor c1) (TypeConstructor c2) =
122+ guardWith (strMsg ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".")) (c1 == c2)
123+ unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
126+ unifyTypes' (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = return ()
127+ unifyTypes' r1@RCons{} r2 = unifyRows r1 r2
128+ unifyTypes' r1 r2@RCons{} = unifyRows r1 r2
129+ unifyTypes' r1@REmpty r2 = unifyRows r1 r2
130+ unifyTypes' r1 r2@REmpty = unifyRows r1 r2
131+ unifyTypes' t@(ConstrainedType _ _) _ = throwError . strMsg $ "Attempted to unify a constrained type " ++ prettyPrintType t ++ " with another type."
132+ unifyTypes' t3 t4@(ConstrainedType _ _) = unifyTypes' t4 t3
133+ unifyTypes' t3 t4 = throwError . strMsg $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
136+-- Unify two rows, updating the current substitution
138+-- Common labels are first identified, and unified. Remaining labels and types are unified with a
139+-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
142+unifyRows :: Type -> Type -> UnifyT Type Check ()
145+ (s1, r1') = rowToList r1
146+ (s2, r2') = rowToList r2
147+ int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
148+ sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
149+ sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
151+ forM_ int (uncurry (=?=))
152+ unifyRows' sd1 r1' sd2 r2'
154+ unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
155+ unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
156+ unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
157+ unifyRows' sd1 (TUnknown u1) sd2 (TUnknown u2) = do
158+ forM_ sd1 $ \(_, t) -> occursCheck u2 t
159+ forM_ sd2 $ \(_, t) -> occursCheck u1 t
161+ u1 =:= rowFromList (sd2, rest)
162+ u2 =:= rowFromList (sd1, rest)
163+ unifyRows' [] REmpty [] REmpty = return ()
164+ unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
165+ unifyRows' [] (Skolem _ s1 _) [] (Skolem _ s2 _) | s1 == s2 = return ()
166+ unifyRows' sd3 r3 sd4 r4 = throwError . strMsg $ "Cannot unify (" ++ prettyPrintRow (rowFromList (sd3, r3)) ++ ") with (" ++ prettyPrintRow (rowFromList (sd4, r4)) ++ ")"
169+-- Infer the types of multiple mutually-recursive values, and return elaborated values including
170+-- type class dictionaries and type annotations.
172+typesOf :: Maybe ModuleName -> ModuleName -> [(Ident, Expr)] -> Check [(Ident, (Expr, Type))]
173+typesOf mainModuleName moduleName vals = do
174+ tys <- fmap tidyUp . liftUnify $ do
175+ (untyped, typed, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName vals
176+ ds1 <- parU typed $ \e -> do
177+ triple@(_, (_, ty)) <- checkTypedBindingGroupElement moduleName e dict
178+ checkMain (fst e) ty
180+ ds2 <- forM untyped $ \e -> do
181+ triple@(_, (_, ty)) <- typeForBindingGroupElement e dict untypedDict
182+ checkMain (fst e) ty
186+ forM tys $ \(ident, (val, ty)) -> do
187+ -- Replace type class dictionary placeholders with actual dictionaries
188+ val' <- replaceTypeClassDictionaries moduleName val
189+ -- Check skolem variables did not escape their scope
190+ skolemEscapeCheck val'
191+ -- Check rows do not contain duplicate labels
192+ checkDuplicateLabels val'
193+ -- Remove type synonyms placeholders, remove duplicate row fields, and replace
194+ -- top-level unification variables with named type variables.
195+ let val'' = overTypes (desaturateAllTypeSynonyms . setifyAll) val'
196+ ty' = varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty
197+ return (ident, (val'', ty'))
199+ -- Apply the substitution that was returned from runUnify to both types and (type-annotated) values
200+ tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
201+ -- If --main is enabled, need to check that `main` has type Eff eff a for some eff, a
202+ checkMain nm ty = when (Just moduleName == mainModuleName && nm == Ident C.main) $ do
203+ [eff, a] <- replicateM 2 fresh
204+ ty =?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName [ProperName "Control", ProperName "Monad", ProperName "Eff"])) (ProperName "Eff"))) eff) a
206+type TypeData = M.Map (ModuleName, Ident) (Type, NameKind, NameVisibility)
208+type UntypedData = [(Ident, Type)]
210+typeDictionaryForBindingGroup :: ModuleName -> [(Ident, Expr)] -> UnifyT Type Check ([(Ident, Expr)], [(Ident, (Expr, Type, Bool))], TypeData, UntypedData)
211+typeDictionaryForBindingGroup moduleName vals = do
213+ -- Map each declaration to a name/value pair, with an optional type, if the declaration is typed
214+ es = map isTyped vals
215+ -- Filter the typed and untyped declarations
218+ -- Make a map of names to typed declarations
219+ typedDict = map (\(ident, (_, ty, _)) -> (ident, ty)) typed
221+ -- Create fresh unification variables for the types of untyped declarations
222+ untypedNames <- replicateM (length untyped) fresh
225+ -- Make a map of names to the unification variables of untyped declarations
226+ untypedDict = zip (map fst untyped) untypedNames
227+ -- Create the dictionary of all name/type pairs, which will be added to the environment during type checking
228+ dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable, Undefined))) $ typedDict ++ untypedDict)
229+ return (untyped, typed, dict, untypedDict)
231+checkTypedBindingGroupElement :: ModuleName -> (Ident, (Expr, Type, Bool)) -> TypeData -> UnifyT Type Check (Ident, (Expr, Type))
232+checkTypedBindingGroupElement moduleName (ident, (val', ty, checkType)) dict = do
234+ kind <- liftCheck $ kindOf moduleName ty
235+ guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
236+ -- Check the type with the new names in scope
237+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
238+ val'' <- if checkType
239+ then bindNames dict $ TypedValue True <$> check val' ty' <*> pure ty'
240+ else return (TypedValue False val' ty')
241+ return (ident, (val'', ty'))
243+typeForBindingGroupElement :: (Ident, Expr) -> TypeData -> UntypedData -> UnifyT Type Check (Ident, (Expr, Type))
244+typeForBindingGroupElement (ident, val) dict untypedDict = do
245+ -- Infer the type with the new names in scope
246+ TypedValue _ val' ty <- bindNames dict $ infer val
247+ ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
248+ return (ident, (TypedValue True val' ty, ty))
251+-- Check if a value contains a type annotation
253+isTyped :: (Ident, Expr) -> (Either (Ident, Expr) (Ident, (Expr, Type, Bool)))
254+isTyped (name, TypedValue checkType value ty) = Right (name, (value, ty, checkType))
255+isTyped (name, value) = Left (name, value)
258+-- Map a function over type annotations appearing inside a value
260+overTypes :: (Type -> Type) -> Expr -> Expr
261+overTypes f = let (_, f', _) = everywhereOnValues id g id in f'
264+ g (TypedValue checkTy val t) = TypedValue checkTy val (f t)
265+ g (TypeClassDictionary b (nm, tys) sco) = TypeClassDictionary b (nm, map f tys) sco
269+-- Replace type class dictionary placeholders with inferred type class dictionaries
271+replaceTypeClassDictionaries :: ModuleName -> Expr -> Check Expr
272+replaceTypeClassDictionaries mn =
273+ let (_, f, _) = everywhereOnValuesTopDownM return go return
276+ go (TypeClassDictionary trySuperclasses constraint dicts) = do
278+ entails env mn dicts constraint trySuperclasses
279+ go other = return other
282+-- A simplified representation of expressions which are used to represent type
283+-- class dictionaries at runtime, which can be compared for equality
287+ -- A dictionary which is brought into scope by a local constraint
289+ = LocalDictionaryValue (Qualified Ident)
291+ -- A dictionary which is brought into scope by an instance declaration
293+ | GlobalDictionaryValue (Qualified Ident)
295+ -- A dictionary which depends on other dictionaries
297+ | DependentDictionaryValue (Qualified Ident) [DictionaryValue]
299+ -- A subclass dictionary
301+ | SubclassDictionaryValue DictionaryValue (Qualified ProperName) Integer
302+ deriving (Show, Ord, Eq)
305+-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
306+-- return a type class dictionary reference.
308+entails :: Environment -> ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, [Type]) -> Bool -> Check Expr
309+entails env moduleName context = solve (sortedNubBy canonicalizeDictionary (filter filterModule context))
311+ sortedNubBy :: (Ord k) => (v -> k) -> [v] -> [v]
312+ sortedNubBy f vs = M.elems (M.fromList (map (f &&& id) vs))
314+ -- Filter out type dictionaries which are in scope in the current module
315+ filterModule :: TypeClassDictionaryInScope -> Bool
316+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
317+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
318+ filterModule _ = False
320+ solve context' (className, tys) trySuperclasses =
321+ checkOverlaps $ go trySuperclasses className tys
323+ go trySuperclasses' className' tys' =
324+ -- Look for regular type instances
325+ [ mkDictionary (canonicalizeDictionary tcd) args
327+ -- Make sure the type class name matches the one we are trying to satisfy
328+ , className' == tcdClassName tcd
329+ -- Make sure the type unifies with the type in the type instance definition
330+ , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' (tcdInstanceTypes tcd)
331+ -- Solve any necessary subgoals
332+ , args <- solveSubgoals subst (tcdDependencies tcd) ] ++
334+ -- Look for implementations via superclasses
335+ [ SubclassDictionaryValue suDict superclass index
337+ , (subclassName, (args, _, implies)) <- M.toList (typeClasses env)
338+ -- Try each superclass
339+ , (index, (superclass, suTyArgs)) <- zip [0..] implies
340+ -- Make sure the type class name matches the superclass name
341+ , className' == superclass
342+ -- Make sure the types unify with the types in the superclass implication
343+ , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' suTyArgs
344+ -- Finally, satisfy the subclass constraint
345+ , args' <- maybeToList $ mapM (flip lookup subst) args
346+ , suDict <- go True subclassName args' ]
348+ -- Create dictionaries for subgoals which still need to be solved by calling go recursively
349+ -- E.g. the goal (Show a, Show b) => Show (Either a b) can be satisfied if the current type
350+ -- unifies with Either a b, and we can satisfy the subgoals Show a and Show b recursively.
351+ solveSubgoals :: [(String, Type)] -> Maybe [(Qualified ProperName, [Type])] -> [Maybe [DictionaryValue]]
352+ solveSubgoals _ Nothing = return Nothing
353+ solveSubgoals subst (Just subgoals) = do
354+ dict <- mapM (uncurry (go True) . second (map (replaceAllTypeVars subst))) subgoals
356+ -- Make a dictionary from subgoal dictionaries by applying the correct function
357+ mkDictionary :: Qualified Ident -> Maybe [DictionaryValue] -> DictionaryValue
358+ mkDictionary fnName Nothing = LocalDictionaryValue fnName
359+ mkDictionary fnName (Just []) = GlobalDictionaryValue fnName
360+ mkDictionary fnName (Just dicts) = DependentDictionaryValue fnName dicts
361+ -- Turn a DictionaryValue into a Expr
362+ dictionaryValueToValue :: DictionaryValue -> Expr
363+ dictionaryValueToValue (LocalDictionaryValue fnName) = Var fnName
364+ dictionaryValueToValue (GlobalDictionaryValue fnName) = Var fnName
365+ dictionaryValueToValue (DependentDictionaryValue fnName dicts) = foldl App (Var fnName) (map dictionaryValueToValue dicts)
366+ dictionaryValueToValue (SubclassDictionaryValue dict superclassName index) =
367+ App (Accessor (C.__superclass_ ++ show superclassName ++ "_" ++ show index)
368+ (dictionaryValueToValue dict))
370+ -- Ensure that a substitution is valid
371+ verifySubstitution :: [(String, Type)] -> Maybe [(String, Type)]
372+ verifySubstitution subst = do
373+ let grps = groupBy ((==) `on` fst) subst
374+ guard (all (pairwise (unifiesWith env) . map snd) grps)
375+ return $ map head grps
377+ -- Check for overlapping instances
379+ checkOverlaps :: [DictionaryValue] -> Check Expr
380+ checkOverlaps dicts =
381+ case [ (d1, d2) | d1 <- dicts, d2 <- dicts, d1 `overlapping` d2 ] of
382+ (d1, d2) : _ -> throwError . strMsg $ unlines
383+ [ "Overlapping instances found for " ++ show className ++ " " ++ unwords (map prettyPrintType tys) ++ "."
385+ , prettyPrintDictionaryValue d1
387+ , prettyPrintDictionaryValue d2
389+ _ -> case chooseSimplestDictionaries dicts of
390+ [] -> throwError . strMsg $
391+ "No instance found for " ++ show className ++ " " ++ unwords (map prettyPrintTypeAtom tys)
392+ d : _ -> return $ dictionaryValueToValue d
393+ -- Choose the simplest DictionaryValues from a list of candidates
394+ -- The reason for this function is as follows:
395+ -- When considering overlapping instances, we don't want to consider the same dictionary
396+ -- to be an overlap of itself when obtained as a superclass of another class.
397+ -- Observing that we probably don't want to select a superclass instance when an instance
398+ -- is available directly, and that there is no way for a superclass instance to actually
399+ -- introduce an overlap that wouldn't have been there already, we simply remove dictionaries
400+ -- obtained as superclass instances if there are simpler instances available.
401+ chooseSimplestDictionaries :: [DictionaryValue] -> [DictionaryValue]
402+ chooseSimplestDictionaries ds = case filter isSimpleDictionaryValue ds of
405+ isSimpleDictionaryValue SubclassDictionaryValue{} = False
406+ isSimpleDictionaryValue (DependentDictionaryValue _ ds) = all isSimpleDictionaryValue ds
407+ isSimpleDictionaryValue _ = True
409+ -- Check if two dictionaries are overlapping
411+ -- Dictionaries which are subclass dictionaries cannot overlap, since otherwise the overlap would have
412+ -- been caught when constructing superclass dictionaries.
414+ overlapping :: DictionaryValue -> DictionaryValue -> Bool
415+ overlapping (LocalDictionaryValue nm1) (LocalDictionaryValue nm2) | nm1 == nm2 = False
416+ overlapping (GlobalDictionaryValue nm1) (GlobalDictionaryValue nm2) | nm1 == nm2 = False
417+ overlapping (DependentDictionaryValue nm1 ds1) (DependentDictionaryValue nm2 ds2)
418+ | nm1 == nm2 = any id $ zipWith overlapping ds1 ds2
419+ overlapping (SubclassDictionaryValue _ _ _) _ = False
420+ overlapping _ (SubclassDictionaryValue _ _ _) = False
421+ overlapping _ _ = True
423+ -- Render a DictionaryValue fit for human consumption in error messages
425+ prettyPrintDictionaryValue :: DictionaryValue -> String
426+ prettyPrintDictionaryValue = unlines . indented 0
428+ indented n (LocalDictionaryValue _) = [spaces n ++ "Dictionary in scope"]
429+ indented n (GlobalDictionaryValue nm) = [spaces n ++ show nm]
430+ indented n (DependentDictionaryValue nm args) = (spaces n ++ show nm ++ " via") : concatMap (indented (n + 2)) args
431+ indented n (SubclassDictionaryValue sup nm _) = (spaces n ++ show nm ++ " via superclass") : indented (n + 2) sup
433+ spaces n = replicate n ' ' ++ "- "
435+ valUndefined :: Expr
436+ valUndefined = Var (Qualified (Just (ModuleName [ProperName C.prim])) (Ident C.undefined))
439+-- Check all values in a list pairwise match a predicate
441+pairwise :: (a -> a -> Bool) -> [a] -> Bool
443+pairwise _ [_] = True
444+pairwise p (x : xs) = all (p x) xs && pairwise p xs
447+-- Check that two types unify
449+unifiesWith :: Environment -> Type -> Type -> Bool
450+unifiesWith _ (TUnknown u1) (TUnknown u2) | u1 == u2 = True
451+unifiesWith _ (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = True
452+unifiesWith _ (TypeVar v1) (TypeVar v2) | v1 == v2 = True
453+unifiesWith _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = True
454+unifiesWith e (TypeApp h1 t1) (TypeApp h2 t2) = unifiesWith e h1 h2 && unifiesWith e t1 t2
455+unifiesWith e (SaturatedTypeSynonym name args) t2 =
456+ case expandTypeSynonym' e name args of
458+ Right t1 -> unifiesWith e t1 t2
459+unifiesWith e t1 t2@(SaturatedTypeSynonym _ _) = unifiesWith e t2 t1
460+unifiesWith _ _ _ = False
463+-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
464+-- and return a substitution from type variables to types which makes the type heads unify.
466+typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
467+typeHeadsAreEqual _ _ (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = Just []
468+typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
469+typeHeadsAreEqual _ _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = Just []
470+typeHeadsAreEqual m e (TypeApp h1 t1) (TypeApp h2 t2) = (++) <$> typeHeadsAreEqual m e h1 h2 <*> typeHeadsAreEqual m e t1 t2
471+typeHeadsAreEqual m e (SaturatedTypeSynonym name args) t2 = case expandTypeSynonym' e name args of
473+ Right t1 -> typeHeadsAreEqual m e t1 t2
474+typeHeadsAreEqual _ _ _ _ = Nothing
477+-- Ensure skolem variables do not escape their scope
479+skolemEscapeCheck :: Expr -> Check ()
480+skolemEscapeCheck (TypedValue False _ _) = return ()
481+skolemEscapeCheck root@TypedValue{} =
482+ -- Every skolem variable is created when a ForAll type is skolemized.
483+ -- This determines the scope of that skolem variable, which is copied from the SkolemScope
484+ -- field of the ForAll constructor.
485+ -- We traverse the tree top-down, and collect any SkolemScopes introduced by ForAlls.
486+ -- If a Skolem is encountered whose SkolemScope is not in the current list, we have found
487+ -- an escaped skolem variable.
488+ let (_, f, _, _, _) = everythingWithContextOnValues [] [] (++) def go def def def
491+ ((binding, val) : _) -> throwError $ mkErrorStack ("Rigid/skolem type variable " ++ maybe "" (("bound by " ++) . prettyPrintValue) binding ++ " has escaped.") (Just (ExprError val))
495+ go :: [(SkolemScope, Expr)] -> Expr -> ([(SkolemScope, Expr)], [(Maybe Expr, Expr)])
496+ go scos val@(TypedValue _ _ (ForAll _ _ (Just sco))) = ((sco, val) : scos, [])
497+ go scos val@(TypedValue _ _ ty) = case collectSkolems ty \\ map fst scos of
498+ (sco : _) -> (scos, [(findBindingScope sco, val)])
501+ collectSkolems :: Type -> [SkolemScope]
502+ collectSkolems = nub . everythingOnTypes (++) collect
504+ collect (Skolem _ _ scope) = [scope]
506+ go scos _ = (scos, [])
507+ findBindingScope :: SkolemScope -> Maybe Expr
508+ findBindingScope sco =
509+ let (_, f, _, _, _) = everythingOnValues mappend (const mempty) go' (const mempty) (const mempty) (const mempty)
510+ in getFirst $ f root
512+ go' val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = First (Just val)
514+skolemEscapeCheck val = throwError $ mkErrorStack "Untyped value passed to skolemEscapeCheck" (Just (ExprError val))
517+-- Ensure rows do not contain duplicate labels
519+checkDuplicateLabels :: Expr -> Check ()
520+checkDuplicateLabels =
521+ let (_, f, _) = everywhereOnValuesM def go def
527+ go :: Expr -> Check Expr
528+ go e@(TypedValue _ _ ty) = checkDups ty >> return e
529+ go other = return other
531+ checkDups :: Type -> Check ()
532+ checkDups (TypeApp t1 t2) = checkDups t1 >> checkDups t2
533+ checkDups (SaturatedTypeSynonym _ ts) = mapM_ checkDups ts
534+ checkDups (ForAll _ t _) = checkDups t
535+ checkDups (ConstrainedType args t) = do
536+ mapM_ (checkDups) $ concatMap snd args
538+ checkDups r@(RCons _ _ _) =
539+ let (ls, _) = rowToList r in
540+ case firstDup . sort . map fst $ ls of
541+ Just l -> throwError . strMsg $ "Duplicate label " ++ show l ++ " in row"
542+ Nothing -> return ()
543+ checkDups _ = return ()
545+ firstDup :: (Eq a) => [a] -> Maybe a
546+ firstDup (x : xs@(x' : _))
548+ | otherwise = firstDup xs
549+ firstDup _ = Nothing
552+-- Ensure a row contains no duplicate labels
554+setify :: Type -> Type
555+setify = rowFromList . first (M.toList . M.fromList) . rowToList
558+-- \"Setify\" all rows occuring inside a value
560+setifyAll :: Type -> Type
561+setifyAll = everywhereOnTypes setify
564+-- Replace outermost unsolved unification variables with named type variables
566+varIfUnknown :: Type -> Type
568+ let unks = nub $ unknowns ty
569+ toName = (:) 't' . show
570+ ty' = everywhereOnTypes typeToVar ty
571+ typeToVar :: Type -> Type
572+ typeToVar (TUnknown u) = TypeVar (toName u)
574+ in mkForAll (sort . map toName $ unks) ty'
577+-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
578+-- or TypeClassDictionary values.
580+-- This is necessary during type checking to avoid unifying a polymorphic type with a
581+-- unification variable.
583+instantiatePolyTypeWithUnknowns :: Expr -> Type -> UnifyT Type Check (Expr, Type)
584+instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
585+ ty' <- replaceVarWithUnknown ident ty
586+ instantiatePolyTypeWithUnknowns val ty'
587+instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
588+ dicts <- getTypeClassDictionaries
589+ (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
590+ return (foldl App val (map (flip (TypeClassDictionary True) dicts) constraints), ty')
591+instantiatePolyTypeWithUnknowns val ty = return (val, ty)
594+-- Replace a single type variable with a new unification variable
596+replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
597+replaceVarWithUnknown ident ty = do
599+ return $ replaceTypeVars ident tu ty
602+-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
603+-- better error messages during unification.
605+replaceAllTypeSynonyms' :: Environment -> Type -> Either String Type
606+replaceAllTypeSynonyms' env d =
608+ syns = map (\(name, (args, _)) -> (name, length args)) . M.toList $ typeSynonyms env
610+ saturateAllTypeSynonyms syns d
612+replaceAllTypeSynonyms :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
613+replaceAllTypeSynonyms d = do
615+ either (throwError . strMsg) return $ replaceAllTypeSynonyms' env d
618+-- \"Desaturate\" @SaturatedTypeSynonym@s
620+desaturateAllTypeSynonyms :: Type -> Type
621+desaturateAllTypeSynonyms = everywhereOnTypes replaceSaturatedTypeSynonym
623+ replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
624+ replaceSaturatedTypeSynonym t = t
627+-- Replace a type synonym and its arguments with the aliased type
629+expandTypeSynonym' :: Environment -> Qualified ProperName -> [Type] -> Either String Type
630+expandTypeSynonym' env name args =
631+ case M.lookup name (typeSynonyms env) of
632+ Just (synArgs, body) -> do
633+ let repl = replaceAllTypeVars (zip synArgs args) body
634+ replaceAllTypeSynonyms' env repl
635+ Nothing -> error "Type synonym was not defined"
637+expandTypeSynonym :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Qualified ProperName -> [Type] -> m Type
638+expandTypeSynonym name args = do
640+ either (throwError . strMsg) return $ expandTypeSynonym' env name args
642+expandAllTypeSynonyms :: (Error e, Functor m, Applicative m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
643+expandAllTypeSynonyms = everywhereOnTypesTopDownM go
645+ go (SaturatedTypeSynonym name args) = expandTypeSynonym name args
646+ go other = return other
649+-- Ensure a set of property names and value does not contain duplicate labels
651+ensureNoDuplicateProperties :: (Error e, MonadError e m) => [(String, Expr)] -> m ()
652+ensureNoDuplicateProperties ps = guardWith (strMsg "Duplicate property names") $ length (nub . map fst $ ps) == length ps
655+-- Infer a type for a value, rethrowing any error to provide a more useful error message
657+infer :: Expr -> UnifyT Type Check Expr
658+infer val = rethrow (mkErrorStack "Error inferring type of value" (Just (ExprError val)) <>) $ infer' val
661+-- Infer a type for a value
663+infer' :: Expr -> UnifyT Type Check Expr
664+infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
665+infer' v@(StringLiteral _) = return $ TypedValue True v tyString
666+infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
667+infer' (ArrayLiteral vals) = do
668+ ts <- mapM infer vals
670+ forM_ ts $ \(TypedValue _ _ t) -> els =?= t
671+ return $ TypedValue True (ArrayLiteral ts) (TypeApp tyArray els)
672+infer' (ObjectLiteral ps) = do
673+ ensureNoDuplicateProperties ps
674+ ts <- mapM (infer . snd) ps
675+ let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
676+ ty = TypeApp tyObject $ rowFromList (fields, REmpty)
677+ return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
678+infer' (ObjectUpdate o ps) = do
679+ ensureNoDuplicateProperties ps
681+ newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
682+ let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
683+ oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
684+ let oldTy = TypeApp tyObject $ rowFromList (oldTys, row)
685+ o' <- TypedValue True <$> check o oldTy <*> pure oldTy
686+ return $ TypedValue True (ObjectUpdate o' newVals) $ TypeApp tyObject $ rowFromList (newTys, row)
687+infer' (Accessor prop val) = do
688+ typed@(TypedValue _ _ objTy) <- infer val
689+ propTy <- inferProperty objTy prop
694+ _ <- subsumes Nothing objTy (TypeApp tyObject (RCons prop field rest))
695+ return $ TypedValue True (Accessor prop typed) field
696+ Just ty -> return $ TypedValue True (Accessor prop typed) ty
697+infer' (Abs (Left arg) ret) = do
699+ Just moduleName <- checkCurrentModule <$> get
700+ makeBindingGroupVisible $ bindLocalVariables moduleName [(arg, ty, Defined)] $ do
701+ body@(TypedValue _ _ bodyTy) <- infer' ret
702+ return $ TypedValue True (Abs (Left arg) body) $ function ty bodyTy
703+infer' (Abs (Right _) _) = error "Binder was not desugared"
704+infer' (App f arg) = do
705+ f'@(TypedValue _ _ ft) <- infer f
706+ (ret, app) <- checkFunctionApplication f' ft arg Nothing
707+ return $ TypedValue True app ret
708+infer' (Var var) = do
709+ Just moduleName <- checkCurrentModule <$> get
710+ checkVisibility moduleName var
711+ ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
713+ ConstrainedType constraints ty' -> do
714+ dicts <- getTypeClassDictionaries
715+ return $ TypedValue True (foldl App (Var var) (map (flip (TypeClassDictionary True) dicts) constraints)) ty'
716+ _ -> return $ TypedValue True (Var var) ty
717+infer' v@(Constructor c) = do
719+ case M.lookup c (dataConstructors env) of
720+ Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
721+ Just (_, _, ty) -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
722+ return $ TypedValue True v ty'
723+infer' (Case vals binders) = do
724+ ts <- mapM infer vals
726+ binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
727+ return $ TypedValue True (Case ts binders') ret
728+infer' (IfThenElse cond th el) = do
729+ cond' <- check cond tyBoolean
730+ v2@(TypedValue _ _ t2) <- infer th
731+ v3@(TypedValue _ _ t3) <- infer el
732+ (v2', v3', t) <- meet v2 v3 t2 t3
733+ return $ TypedValue True (IfThenElse cond' v2' v3') t
734+infer' (Let ds val) = do
735+ (ds', val'@(TypedValue _ _ valTy)) <- inferLetBinding [] ds val infer
736+ return $ TypedValue True (Let ds' val') valTy
737+infer' (SuperClassDictionary className tys) = do
738+ dicts <- getTypeClassDictionaries
739+ return $ TypeClassDictionary False (className, tys) dicts
740+infer' (TypedValue checkType val ty) = do
741+ Just moduleName <- checkCurrentModule <$> get
742+ kind <- liftCheck $ kindOf moduleName ty
743+ guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
744+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
745+ val' <- if checkType then check val ty' else return val
746+ return $ TypedValue True val' ty'
747+infer' (PositionedValue pos val) = rethrowWithPosition pos $ infer' val
748+infer' _ = error "Invalid argument to infer"
750+inferLetBinding :: [Declaration] -> [Declaration] -> Expr -> (Expr -> UnifyT Type Check Expr) -> UnifyT Type Check ([Declaration], Expr)
751+inferLetBinding seen [] ret j = (,) seen <$> makeBindingGroupVisible (j ret)
752+inferLetBinding seen (ValueDeclaration ident nameKind [] Nothing tv@(TypedValue checkType val ty) : rest) ret j = do
753+ Just moduleName <- checkCurrentModule <$> get
754+ kind <- liftCheck $ kindOf moduleName ty
755+ guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
756+ let dict = M.singleton (moduleName, ident) (ty, nameKind, Undefined)
757+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
758+ TypedValue _ val' ty'' <- if checkType then bindNames dict (check val ty') else return tv
759+ bindNames (M.singleton (moduleName, ident) (ty'', nameKind, Defined)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] Nothing (TypedValue checkType val' ty'')]) rest ret j
760+inferLetBinding seen (ValueDeclaration ident nameKind [] Nothing val : rest) ret j = do
762+ Just moduleName <- checkCurrentModule <$> get
763+ let dict = M.singleton (moduleName, ident) (valTy, nameKind, Undefined)
764+ TypedValue _ val' valTy' <- bindNames dict $ infer val
766+ bindNames (M.singleton (moduleName, ident) (valTy', nameKind, Defined)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] Nothing val']) rest ret j
767+inferLetBinding seen (BindingGroupDeclaration ds : rest) ret j = do
768+ Just moduleName <- checkCurrentModule <$> get
769+ (untyped, typed, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName (map (\(i, _, v) -> (i, v)) ds)
770+ ds1' <- parU typed $ \e -> checkTypedBindingGroupElement moduleName e dict
771+ ds2' <- forM untyped $ \e -> typeForBindingGroupElement e dict untypedDict
772+ let ds' = [(ident, LocalVariable, val') | (ident, (val', _)) <- ds1' ++ ds2']
773+ makeBindingGroupVisible $ bindNames dict $ inferLetBinding (seen ++ [BindingGroupDeclaration ds']) rest ret j
774+inferLetBinding seen (PositionedDeclaration pos d : ds) ret j = rethrowWithPosition pos $ do
775+ ((d' : ds'), val') <- inferLetBinding seen (d : ds) ret j
776+ return (PositionedDeclaration pos d' : ds', val')
777+inferLetBinding _ _ _ _ = error "Invalid argument to inferLetBinding"
780+-- Infer the type of a property inside a record with a given type
782+inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
783+inferProperty (TypeApp obj row) prop | obj == tyObject = do
784+ let (props, _) = rowToList row
785+ return $ lookup prop props
786+inferProperty (SaturatedTypeSynonym name args) prop = do
787+ replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
788+ inferProperty replaced prop
789+inferProperty (ForAll ident ty _) prop = do
790+ replaced <- replaceVarWithUnknown ident ty
791+ inferProperty replaced prop
792+inferProperty _ _ = return Nothing
795+-- Infer the types of variables brought into scope by a binder
797+inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
798+inferBinder _ NullBinder = return M.empty
799+inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
800+inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
801+inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
802+inferBinder val (VarBinder name) = return $ M.singleton name val
803+inferBinder val (ConstructorBinder ctor binders) = do
805+ case M.lookup ctor (dataConstructors env) of
806+ Just (_, _, ty) -> do
807+ (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contain constraints") ty
808+ fn' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ fn
812+ _ <- subsumes Nothing val ty'
814+ go (binder : binders') (TypeApp (TypeApp t obj) ret) | t == tyFunction =
815+ M.union <$> inferBinder obj binder <*> go binders' ret
816+ go _ _ = throwError . strMsg $ "Wrong number of arguments to constructor " ++ show ctor
817+ _ -> throwError . strMsg $ "Constructor " ++ show ctor ++ " is not defined"
818+inferBinder val (ObjectBinder props) = do
821+ m1 <- inferRowProperties row rest props
822+ val =?= TypeApp tyObject row
825+ inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
826+ inferRowProperties nrow row [] = nrow =?= row >> return M.empty
827+ inferRowProperties nrow row ((name, binder):binders) = do
829+ m1 <- inferBinder propTy binder
830+ m2 <- inferRowProperties nrow (RCons name propTy row) binders
831+ return $ m1 `M.union` m2
832+inferBinder val (ArrayBinder binders) = do
834+ m1 <- M.unions <$> mapM (inferBinder el) binders
835+ val =?= TypeApp tyArray el
837+inferBinder val (ConsBinder headBinder tailBinder) = do
839+ m1 <- inferBinder el headBinder
840+ m2 <- inferBinder val tailBinder
841+ val =?= TypeApp tyArray el
842+ return $ m1 `M.union` m2
843+inferBinder val (NamedBinder name binder) = do
844+ m <- inferBinder val binder
845+ return $ M.insert name val m
846+inferBinder val (PositionedBinder pos binder) =
847+ rethrowWithPosition pos $ inferBinder val binder
850+-- Check the types of the return values in a set of binders in a case statement
852+checkBinders :: [Type] -> Type -> [CaseAlternative] -> UnifyT Type Check [CaseAlternative]
853+checkBinders _ _ [] = return []
854+checkBinders nvals ret (CaseAlternative binders grd val : bs) = do
855+ guardWith (strMsg "Overlapping binders in case statement") $
856+ let ns = concatMap binderNames binders in length (nub ns) == length ns
857+ Just moduleName <- checkCurrentModule <$> get
858+ m1 <- M.unions <$> zipWithM inferBinder nvals binders
859+ r <- bindLocalVariables moduleName [ (name, ty, Defined) | (name, ty) <- M.toList m1 ] $ do
860+ val' <- TypedValue True <$> check val ret <*> pure ret
862+ Nothing -> return $ CaseAlternative binders Nothing val'
864+ g' <- check g tyBoolean
865+ return $ CaseAlternative binders (Just g') val'
866+ rs <- checkBinders nvals ret bs
870+-- Generate a new skolem constant
872+newSkolemConstant :: UnifyT Type Check Int
873+newSkolemConstant = fresh'
876+-- Generate a new skolem scope
878+newSkolemScope :: UnifyT Type Check SkolemScope
879+newSkolemScope = SkolemScope <$> fresh'
882+-- Skolemize a type variable by replacing its instances with fresh skolem constants
884+skolemize :: String -> Int -> SkolemScope -> Type -> Type
885+skolemize ident sko scope = replaceTypeVars ident (Skolem ident sko scope)
888+-- This function has one purpose - to skolemize type variables appearing in a
889+-- SuperClassDictionary placeholder. These type variables are somewhat unique since they are the
890+-- only example of scoped type variables.
892+skolemizeTypesInValue :: String -> Int -> SkolemScope -> Expr -> Expr
893+skolemizeTypesInValue ident sko scope = let (_, f, _) = everywhereOnValues id go id in f
895+ go (SuperClassDictionary c ts) = SuperClassDictionary c (map (skolemize ident sko scope) ts)
899+-- Introduce skolem scope at every occurence of a ForAll
901+introduceSkolemScope :: Type -> UnifyT Type Check Type
902+introduceSkolemScope = everywhereOnTypesM go
904+ go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
905+ go other = return other
908+-- Check the type of a value, rethrowing errors to provide a better error message
910+check :: Expr -> Type -> UnifyT Type Check Expr
911+check val ty = rethrow (mkErrorStack errorMessage (Just (ExprError val)) <>) $ check' val ty
914+ "Error checking type of term " ++
915+ prettyPrintValue val ++
920+-- Check the type of a value
922+check' :: Expr -> Type -> UnifyT Type Check Expr
923+check' val (ForAll ident ty _) = do
924+ scope <- newSkolemScope
925+ sko <- newSkolemConstant
926+ let sk = skolemize ident sko scope ty
927+ let skVal = skolemizeTypesInValue ident sko scope val
928+ val' <- check skVal sk
929+ return $ TypedValue True val' (ForAll ident ty (Just scope))
930+check' val t@(ConstrainedType constraints ty) = do
931+ dictNames <- forM constraints $ \(Qualified _ (ProperName className), _) -> do
932+ n <- liftCheck freshDictionaryName
933+ return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
934+ val' <- makeBindingGroupVisible $ withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
935+ TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular False) (map (Qualified Nothing) dictNames)
936+ constraints) $ check val ty
937+ return $ TypedValue True (foldr (Abs . Left) val' dictNames) t
938+check' val (SaturatedTypeSynonym name args) = do
939+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
941+check' val u@(TUnknown _) = do
942+ val'@(TypedValue _ _ ty) <- infer val
943+ -- Don't unify an unknown with an inferred polytype
944+ (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
946+ return $ TypedValue True val'' ty'
947+check' v@(NumericLiteral _) t | t == tyNumber =
948+ return $ TypedValue True v t
949+check' v@(StringLiteral _) t | t == tyString =
950+ return $ TypedValue True v t
951+check' v@(BooleanLiteral _) t | t == tyBoolean =
952+ return $ TypedValue True v t
953+check' (ArrayLiteral vals) t@(TypeApp a ty) = do
955+ array <- ArrayLiteral <$> forM vals (`check` ty)
956+ return $ TypedValue True array t
957+check' (Abs (Left arg) ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
958+ Just moduleName <- checkCurrentModule <$> get
959+ ret' <- makeBindingGroupVisible $ bindLocalVariables moduleName [(arg, argTy, Defined)] $ check ret retTy
960+ return $ TypedValue True (Abs (Left arg) ret') ty
961+check' (Abs (Right _) _) _ = error "Binder was not desugared"
962+check' (App f arg) ret = do
963+ f'@(TypedValue _ _ ft) <- infer f
964+ (_, app) <- checkFunctionApplication f' ft arg (Just ret)
965+ return $ TypedValue True app ret
966+check' v@(Var var) ty = do
967+ Just moduleName <- checkCurrentModule <$> get
968+ checkVisibility moduleName var
969+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
970+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
971+ v' <- subsumes (Just v) repl ty'
973+ Nothing -> throwError . strMsg $ "Unable to check type subsumption"
974+ Just v'' -> return $ TypedValue True v'' ty'
975+check' (SuperClassDictionary className tys) _ = do
977+ -- Here, we replace a placeholder for a superclass dictionary with a regular
978+ -- TypeClassDictionary placeholder. The reason we do this is that it is necessary to have the
979+ -- correct super instance dictionaries in scope, and these are not available when the type class
980+ -- declaration gets desugared.
982+ -- Note also that the first argument to TypeClassDictionary is False, meaning we _do not_ want
983+ -- to consider superclass instances when searching for this dictionary - doing so might lead
984+ -- to traversing a cycle in the instance graph.
986+ dicts <- getTypeClassDictionaries
987+ return $ TypeClassDictionary False (className, tys) dicts
988+check' (TypedValue checkType val ty1) ty2 = do
989+ Just moduleName <- checkCurrentModule <$> get
990+ kind <- liftCheck $ kindOf moduleName ty1
991+ guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
992+ ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
993+ ty2' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty2
994+ val' <- subsumes (Just val) ty1' ty2'
996+ Nothing -> throwError . strMsg $ "Unable to check type subsumption"
998+ val''' <- if checkType then check val'' ty2' else return val''
999+ return $ TypedValue checkType (TypedValue True val''' ty1') ty2'
1000+check' (Case vals binders) ret = do
1001+ vals' <- mapM infer vals
1002+ let ts = map (\(TypedValue _ _ t) -> t) vals'
1003+ binders' <- checkBinders ts ret binders
1004+ return $ TypedValue True (Case vals' binders') ret
1005+check' (IfThenElse cond th el) ty = do
1006+ cond' <- check cond tyBoolean
1009+ return $ TypedValue True (IfThenElse cond' th' el') ty
1010+check' (ObjectLiteral ps) t@(TypeApp obj row) | obj == tyObject = do
1011+ ensureNoDuplicateProperties ps
1012+ ps' <- checkProperties ps row False
1013+ return $ TypedValue True (ObjectLiteral ps') t
1014+check' (TypeClassDictionaryConstructorApp name ps) t = do
1016+ return $ TypedValue True (TypeClassDictionaryConstructorApp name ps') t
1017+check' (ObjectUpdate obj ps) t@(TypeApp o row) | o == tyObject = do
1018+ ensureNoDuplicateProperties ps
1019+ us <- zip (map fst ps) <$> replicateM (length ps) fresh
1020+ let (propsToCheck, rest) = rowToList row
1021+ propsToRemove = map fst ps
1022+ remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
1023+ obj' <- check obj (TypeApp tyObject (rowFromList (us ++ remainingProps, rest)))
1024+ ps' <- checkProperties ps row True
1025+ return $ TypedValue True (ObjectUpdate obj' ps') t
1026+check' (Accessor prop val) ty = do
1028+ val' <- check val (TypeApp tyObject (RCons prop ty rest))
1029+ return $ TypedValue True (Accessor prop val') ty
1030+check' (Constructor c) ty = do
1032+ case M.lookup c (dataConstructors env) of
1033+ Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
1034+ Just (_, _, ty1) -> do
1035+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
1036+ _ <- subsumes Nothing repl ty
1037+ return $ TypedValue True (Constructor c) ty
1038+check' (Let ds val) ty = do
1039+ (ds', val') <- inferLetBinding [] ds val (flip check ty)
1040+ return $ TypedValue True (Let ds' val') ty
1041+check' val ty | containsTypeSynonyms ty = do
1042+ ty' <- introduceSkolemScope <=< expandAllTypeSynonyms $ ty
1044+check' (PositionedValue pos val) ty =
1045+ rethrowWithPosition pos $ check val ty
1046+check' val ty = throwError $ mkErrorStack ("Expr does not have type " ++ prettyPrintType ty) (Just (ExprError val))
1048+containsTypeSynonyms :: Type -> Bool
1049+containsTypeSynonyms = everythingOnTypes (||) go where
1050+ go (SaturatedTypeSynonym _ _) = True
1054+-- Check the type of a collection of named record fields
1056+-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
1058+checkProperties :: [(String, Expr)] -> Type -> Bool -> UnifyT Type Check [(String, Expr)]
1059+checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
1060+ go [] [] REmpty = return []
1061+ go [] [] u@(TUnknown _) = do u =?= REmpty
1063+ go [] [] (Skolem _ _ _) | lax = return []
1064+ go [] ((p, _): _) _ | lax = return []
1065+ | otherwise = throwError $ mkErrorStack ("Object does not have property " ++ p) (Just (ExprError (ObjectLiteral ps)))
1066+ go ((p,_):_) [] REmpty = throwError $ mkErrorStack ("Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row) (Just (ExprError (ObjectLiteral ps)))
1067+ go ((p,v):ps') [] u@(TUnknown _) = do
1068+ v'@(TypedValue _ _ ty) <- infer v
1070+ u =?= RCons p ty rest
1071+ ps'' <- go ps' [] rest
1072+ return $ (p, v') : ps''
1073+ go ((p,v):ps') ts r =
1074+ case lookup p ts of
1076+ v'@(TypedValue _ _ ty) <- infer v
1078+ r =?= RCons p ty rest
1079+ ps'' <- go ps' ts rest
1080+ return $ (p, v') : ps''
1083+ ps'' <- go ps' (delete (p, ty) ts) r
1084+ return $ (p, v') : ps''
1085+ go _ _ _ = throwError $ mkErrorStack ("Object does not have type " ++ prettyPrintType (TypeApp tyObject row)) (Just (ExprError (ObjectLiteral ps)))
1088+-- Check the type of a function application, rethrowing errors to provide a better error message
1090+checkFunctionApplication :: Expr -> Type -> Expr -> Maybe Type -> UnifyT Type Check (Type, Expr)
1091+checkFunctionApplication fn fnTy arg ret = rethrow (mkErrorStack errorMessage (Just (ExprError fn)) <>) $ do
1092+ subst <- unifyCurrentSubstitution <$> UnifyT get
1093+ checkFunctionApplication' fn (subst $? fnTy) arg (($?) subst <$> ret)
1095+ errorMessage = "Error applying function of type "
1096+ ++ prettyPrintType fnTy
1097+ ++ " to argument " ++ prettyPrintValue arg
1100+-- Check the type of a function application
1102+checkFunctionApplication' :: Expr -> Type -> Expr -> Maybe Type -> UnifyT Type Check (Type, Expr)
1103+checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg ret = do
1104+ tyFunction' =?= tyFunction
1105+ arg' <- check arg argTy
1107+ Nothing -> return (retTy, App fn arg')
1109+ Just app' <- subsumes (Just (App fn arg')) retTy ret'
1110+ return (retTy, app')
1111+checkFunctionApplication' fn (ForAll ident ty _) arg ret = do
1112+ replaced <- replaceVarWithUnknown ident ty
1113+ checkFunctionApplication fn replaced arg ret
1114+checkFunctionApplication' fn u@(TUnknown _) arg ret = do
1116+ TypedValue _ arg' t <- infer arg
1117+ (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
1118+ return $ TypedValue True arg'' t'
1119+ let ty = (\(TypedValue _ _ t) -> t) arg'
1120+ ret' <- maybe fresh return ret
1121+ u =?= function ty ret'
1122+ return (ret', App fn arg')
1123+checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
1124+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1125+ checkFunctionApplication fn ty arg ret
1126+checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
1127+ dicts <- getTypeClassDictionaries
1128+ checkFunctionApplication' (foldl App fn (map (flip (TypeClassDictionary True) dicts) constraints)) fnTy arg ret
1129+checkFunctionApplication' fn fnTy dict@(TypeClassDictionary _ _ _) _ =
1130+ return (fnTy, App fn dict)
1131+checkFunctionApplication' _ fnTy arg _ = throwError . strMsg $ "Cannot apply a function of type "
1132+ ++ prettyPrintType fnTy
1133+ ++ " to argument " ++ prettyPrintValue arg
1136+-- Check whether one type subsumes another, rethrowing errors to provide a better error message
1138+subsumes :: Maybe Expr -> Type -> Type -> UnifyT Type Check (Maybe Expr)
1139+subsumes val ty1 ty2 = rethrow (mkErrorStack errorMessage (ExprError <$> val) <>) $ subsumes' val ty1 ty2
1141+ errorMessage = "Error checking that type "
1142+ ++ prettyPrintType ty1
1143+ ++ " subsumes type "
1144+ ++ prettyPrintType ty2
1147+-- Check whether one type subsumes another
1149+subsumes' :: Maybe Expr -> Type -> Type -> UnifyT Type Check (Maybe Expr)
1150+subsumes' val (ForAll ident ty1 _) ty2 = do
1151+ replaced <- replaceVarWithUnknown ident ty1
1152+ subsumes val replaced ty2
1153+subsumes' val ty1 (ForAll ident ty2 sco) =
1156+ sko <- newSkolemConstant
1157+ let sk = skolemize ident sko sco' ty2
1158+ subsumes val ty1 sk
1159+ Nothing -> throwError . strMsg $ "Skolem variable scope is unspecified"
1160+subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
1161+ _ <- subsumes Nothing arg2 arg1
1162+ _ <- subsumes Nothing ret1 ret2
1164+subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
1165+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1166+ subsumes val ty1 ty2
1167+subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
1168+ ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1169+ subsumes val ty1 ty2
1170+subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
1171+ dicts <- getTypeClassDictionaries
1172+ subsumes' (Just $ foldl App val (map (flip (TypeClassDictionary True) dicts) constraints)) ty1 ty2
1173+subsumes' val (TypeApp f1 r1) (TypeApp f2 r2) | f1 == tyObject && f2 == tyObject = do
1175+ (ts1, r1') = rowToList r1
1176+ (ts2, r2') = rowToList r2
1177+ ts1' = sortBy (comparing fst) ts1
1178+ ts2' = sortBy (comparing fst) ts2
1179+ go ts1' ts2' r1' r2'
1182+ go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
1183+ go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
1184+ go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
1185+ | p1 == p2 = do _ <- subsumes Nothing ty1 ty2
1187+ | p1 < p2 = do rest <- fresh
1188+ r2' =?= RCons p1 ty1 rest
1189+ go ts1 ((p2, ty2) : ts2) r1' rest
1190+ | otherwise = do rest <- fresh
1191+ r1' =?= RCons p2 ty2 rest
1192+ go ((p1, ty1) : ts1) ts2 rest r2'
1193+subsumes' val ty1 ty2@(TypeApp obj _) | obj == tyObject = subsumes val ty2 ty1
1194+subsumes' val ty1 ty2 = do
1199+-- Compute the meet of two types, i.e. the most general type which both types subsume.
1200+-- TODO: handle constrained types
1202+meet :: Expr -> Expr -> Type -> Type -> UnifyT Type Check (Expr, Expr, Type)
1203+meet e1 e2 (ForAll ident t1 _) t2 = do
1204+ t1' <- replaceVarWithUnknown ident t1
1206+meet e1 e2 t1 (ForAll ident t2 _) = do
1207+ t2' <- replaceVarWithUnknown ident t2
1209+meet e1 e2 t1 t2 = do
1211+ return (e1, e2, t1)