@@ -0,0 +1,1228 @@
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' (KindedType ty1 _) ty2 = ty1 `unifyTypes` ty2
128+ unifyTypes' ty1 (KindedType ty2 _) = ty1 `unifyTypes` ty2
129+ unifyTypes' r1@RCons{} r2 = unifyRows r1 r2
130+ unifyTypes' r1 r2@RCons{} = unifyRows r1 r2
131+ unifyTypes' r1@REmpty r2 = unifyRows r1 r2
132+ unifyTypes' r1 r2@REmpty = unifyRows r1 r2
133+ unifyTypes' t@(ConstrainedType _ _) _ = throwError . strMsg $ "Attempted to unify a constrained type " ++ prettyPrintType t ++ " with another type."
134+ unifyTypes' t3 t4@(ConstrainedType _ _) = unifyTypes' t4 t3
135+ unifyTypes' t3 t4 = throwError . strMsg $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
138+-- Unify two rows, updating the current substitution
140+-- Common labels are first identified, and unified. Remaining labels and types are unified with a
141+-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
144+unifyRows :: Type -> Type -> UnifyT Type Check ()
147+ (s1, r1') = rowToList r1
148+ (s2, r2') = rowToList r2
149+ int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
150+ sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
151+ sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
153+ forM_ int (uncurry (=?=))
154+ unifyRows' sd1 r1' sd2 r2'
156+ unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
157+ unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
158+ unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
159+ unifyRows' sd1 (TUnknown u1) sd2 (TUnknown u2) = do
160+ forM_ sd1 $ \(_, t) -> occursCheck u2 t
161+ forM_ sd2 $ \(_, t) -> occursCheck u1 t
163+ u1 =:= rowFromList (sd2, rest)
164+ u2 =:= rowFromList (sd1, rest)
165+ unifyRows' [] REmpty [] REmpty = return ()
166+ unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
167+ unifyRows' [] (Skolem _ s1 _) [] (Skolem _ s2 _) | s1 == s2 = return ()
168+ unifyRows' sd3 r3 sd4 r4 = throwError . strMsg $ "Cannot unify (" ++ prettyPrintRow (rowFromList (sd3, r3)) ++ ") with (" ++ prettyPrintRow (rowFromList (sd4, r4)) ++ ")"
171+-- Infer the types of multiple mutually-recursive values, and return elaborated values including
172+-- type class dictionaries and type annotations.
174+typesOf :: Maybe ModuleName -> ModuleName -> [(Ident, Expr)] -> Check [(Ident, (Expr, Type))]
175+typesOf mainModuleName moduleName vals = do
176+ tys <- fmap tidyUp . liftUnify $ do
177+ (untyped, typed, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName vals
178+ ds1 <- parU typed $ \e -> do
179+ triple@(_, (_, ty)) <- checkTypedBindingGroupElement moduleName e dict
180+ checkMain (fst e) ty
182+ ds2 <- forM untyped $ \e -> do
183+ triple@(_, (_, ty)) <- typeForBindingGroupElement e dict untypedDict
184+ checkMain (fst e) ty
188+ forM tys $ \(ident, (val, ty)) -> do
189+ -- Replace type class dictionary placeholders with actual dictionaries
190+ val' <- replaceTypeClassDictionaries moduleName val
191+ -- Check skolem variables did not escape their scope
192+ skolemEscapeCheck val'
193+ -- Check rows do not contain duplicate labels
194+ checkDuplicateLabels val'
195+ -- Remove type synonyms placeholders, and replace
196+ -- top-level unification variables with named type variables.
197+ let val'' = overTypes desaturateAllTypeSynonyms val'
198+ ty' = varIfUnknown . desaturateAllTypeSynonyms $ ty
199+ return (ident, (val'', ty'))
201+ -- Apply the substitution that was returned from runUnify to both types and (type-annotated) values
202+ tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
203+ -- If --main is enabled, need to check that `main` has type Eff eff a for some eff, a
204+ checkMain nm ty = when (Just moduleName == mainModuleName && nm == Ident C.main) $ do
205+ [eff, a] <- replicateM 2 fresh
206+ ty =?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName [ProperName "Control", ProperName "Monad", ProperName "Eff"])) (ProperName "Eff"))) eff) a
208+type TypeData = M.Map (ModuleName, Ident) (Type, NameKind, NameVisibility)
210+type UntypedData = [(Ident, Type)]
212+typeDictionaryForBindingGroup :: ModuleName -> [(Ident, Expr)] -> UnifyT Type Check ([(Ident, Expr)], [(Ident, (Expr, Type, Bool))], TypeData, UntypedData)
213+typeDictionaryForBindingGroup moduleName vals = do
215+ -- Map each declaration to a name/value pair, with an optional type, if the declaration is typed
216+ es = map isTyped vals
217+ -- Filter the typed and untyped declarations
220+ -- Make a map of names to typed declarations
221+ typedDict = map (\(ident, (_, ty, _)) -> (ident, ty)) typed
223+ -- Create fresh unification variables for the types of untyped declarations
224+ untypedNames <- replicateM (length untyped) fresh
227+ -- Make a map of names to the unification variables of untyped declarations
228+ untypedDict = zip (map fst untyped) untypedNames
229+ -- Create the dictionary of all name/type pairs, which will be added to the environment during type checking
230+ dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable, Undefined))) $ typedDict ++ untypedDict)
231+ return (untyped, typed, dict, untypedDict)
233+checkTypedBindingGroupElement :: ModuleName -> (Ident, (Expr, Type, Bool)) -> TypeData -> UnifyT Type Check (Ident, (Expr, Type))
234+checkTypedBindingGroupElement moduleName (ident, (val', ty, checkType)) dict = do
236+ kind <- liftCheck $ kindOf moduleName ty
237+ guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
238+ -- Check the type with the new names in scope
239+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
240+ val'' <- if checkType
241+ then bindNames dict $ TypedValue True <$> check val' ty' <*> pure ty'
242+ else return (TypedValue False val' ty')
243+ return (ident, (val'', ty'))
245+typeForBindingGroupElement :: (Ident, Expr) -> TypeData -> UntypedData -> UnifyT Type Check (Ident, (Expr, Type))
246+typeForBindingGroupElement (ident, val) dict untypedDict = do
247+ -- Infer the type with the new names in scope
248+ TypedValue _ val' ty <- bindNames dict $ infer val
249+ ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
250+ return (ident, (TypedValue True val' ty, ty))
253+-- Check if a value contains a type annotation
255+isTyped :: (Ident, Expr) -> (Either (Ident, Expr) (Ident, (Expr, Type, Bool)))
256+isTyped (name, TypedValue checkType value ty) = Right (name, (value, ty, checkType))
257+isTyped (name, value) = Left (name, value)
260+-- Map a function over type annotations appearing inside a value
262+overTypes :: (Type -> Type) -> Expr -> Expr
263+overTypes f = let (_, f', _) = everywhereOnValues id g id in f'
266+ g (TypedValue checkTy val t) = TypedValue checkTy val (f t)
267+ g (TypeClassDictionary b (nm, tys) sco) = TypeClassDictionary b (nm, map f tys) sco
271+-- Replace type class dictionary placeholders with inferred type class dictionaries
273+replaceTypeClassDictionaries :: ModuleName -> Expr -> Check Expr
274+replaceTypeClassDictionaries mn =
275+ let (_, f, _) = everywhereOnValuesTopDownM return go return
278+ go (TypeClassDictionary trySuperclasses constraint dicts) = do
280+ entails env mn dicts constraint trySuperclasses
281+ go other = return other
284+-- A simplified representation of expressions which are used to represent type
285+-- class dictionaries at runtime, which can be compared for equality
289+ -- A dictionary which is brought into scope by a local constraint
291+ = LocalDictionaryValue (Qualified Ident)
293+ -- A dictionary which is brought into scope by an instance declaration
295+ | GlobalDictionaryValue (Qualified Ident)
297+ -- A dictionary which depends on other dictionaries
299+ | DependentDictionaryValue (Qualified Ident) [DictionaryValue]
301+ -- A subclass dictionary
303+ | SubclassDictionaryValue DictionaryValue (Qualified ProperName) Integer
304+ deriving (Show, Ord, Eq)
307+-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
308+-- return a type class dictionary reference.
310+entails :: Environment -> ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, [Type]) -> Bool -> Check Expr
311+entails env moduleName context = solve (sortedNubBy canonicalizeDictionary (filter filterModule context))
313+ sortedNubBy :: (Ord k) => (v -> k) -> [v] -> [v]
314+ sortedNubBy f vs = M.elems (M.fromList (map (f &&& id) vs))
316+ -- Filter out type dictionaries which are in scope in the current module
317+ filterModule :: TypeClassDictionaryInScope -> Bool
318+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
319+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
320+ filterModule _ = False
322+ solve context' (className, tys) trySuperclasses =
323+ checkOverlaps $ go trySuperclasses className tys
325+ go trySuperclasses' className' tys' =
326+ -- Look for regular type instances
327+ [ mkDictionary (canonicalizeDictionary tcd) args
329+ -- Make sure the type class name matches the one we are trying to satisfy
330+ , className' == tcdClassName tcd
331+ -- Make sure the type unifies with the type in the type instance definition
332+ , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' (tcdInstanceTypes tcd)
333+ -- Solve any necessary subgoals
334+ , args <- solveSubgoals subst (tcdDependencies tcd) ] ++
336+ -- Look for implementations via superclasses
337+ [ SubclassDictionaryValue suDict superclass index
339+ , (subclassName, (args, _, implies)) <- M.toList (typeClasses env)
340+ -- Try each superclass
341+ , (index, (superclass, suTyArgs)) <- zip [0..] implies
342+ -- Make sure the type class name matches the superclass name
343+ , className' == superclass
344+ -- Make sure the types unify with the types in the superclass implication
345+ , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' suTyArgs
346+ -- Finally, satisfy the subclass constraint
347+ , args' <- maybeToList $ mapM (flip lookup subst) (map fst args)
348+ , suDict <- go True subclassName args' ]
350+ -- Create dictionaries for subgoals which still need to be solved by calling go recursively
351+ -- E.g. the goal (Show a, Show b) => Show (Either a b) can be satisfied if the current type
352+ -- unifies with Either a b, and we can satisfy the subgoals Show a and Show b recursively.
353+ solveSubgoals :: [(String, Type)] -> Maybe [(Qualified ProperName, [Type])] -> [Maybe [DictionaryValue]]
354+ solveSubgoals _ Nothing = return Nothing
355+ solveSubgoals subst (Just subgoals) = do
356+ dict <- mapM (uncurry (go True) . second (map (replaceAllTypeVars subst))) subgoals
358+ -- Make a dictionary from subgoal dictionaries by applying the correct function
359+ mkDictionary :: Qualified Ident -> Maybe [DictionaryValue] -> DictionaryValue
360+ mkDictionary fnName Nothing = LocalDictionaryValue fnName
361+ mkDictionary fnName (Just []) = GlobalDictionaryValue fnName
362+ mkDictionary fnName (Just dicts) = DependentDictionaryValue fnName dicts
363+ -- Turn a DictionaryValue into a Expr
364+ dictionaryValueToValue :: DictionaryValue -> Expr
365+ dictionaryValueToValue (LocalDictionaryValue fnName) = Var fnName
366+ dictionaryValueToValue (GlobalDictionaryValue fnName) = Var fnName
367+ dictionaryValueToValue (DependentDictionaryValue fnName dicts) = foldl App (Var fnName) (map dictionaryValueToValue dicts)
368+ dictionaryValueToValue (SubclassDictionaryValue dict superclassName index) =
369+ App (Accessor (C.__superclass_ ++ show superclassName ++ "_" ++ show index)
370+ (dictionaryValueToValue dict))
372+ -- Ensure that a substitution is valid
373+ verifySubstitution :: [(String, Type)] -> Maybe [(String, Type)]
374+ verifySubstitution subst = do
375+ let grps = groupBy ((==) `on` fst) subst
376+ guard (all (pairwise (unifiesWith env) . map snd) grps)
377+ return $ map head grps
379+ -- Check for overlapping instances
381+ checkOverlaps :: [DictionaryValue] -> Check Expr
382+ checkOverlaps dicts =
383+ case [ (d1, d2) | d1 <- dicts, d2 <- dicts, d1 `overlapping` d2 ] of
384+ (d1, d2) : _ -> throwError . strMsg $ unlines
385+ [ "Overlapping instances found for " ++ show className ++ " " ++ unwords (map prettyPrintType tys) ++ "."
387+ , prettyPrintDictionaryValue d1
389+ , prettyPrintDictionaryValue d2
391+ _ -> case chooseSimplestDictionaries dicts of
392+ [] -> throwError . strMsg $
393+ "No instance found for " ++ show className ++ " " ++ unwords (map prettyPrintTypeAtom tys)
394+ d : _ -> return $ dictionaryValueToValue d
395+ -- Choose the simplest DictionaryValues from a list of candidates
396+ -- The reason for this function is as follows:
397+ -- When considering overlapping instances, we don't want to consider the same dictionary
398+ -- to be an overlap of itself when obtained as a superclass of another class.
399+ -- Observing that we probably don't want to select a superclass instance when an instance
400+ -- is available directly, and that there is no way for a superclass instance to actually
401+ -- introduce an overlap that wouldn't have been there already, we simply remove dictionaries
402+ -- obtained as superclass instances if there are simpler instances available.
403+ chooseSimplestDictionaries :: [DictionaryValue] -> [DictionaryValue]
404+ chooseSimplestDictionaries ds = case filter isSimpleDictionaryValue ds of
407+ isSimpleDictionaryValue SubclassDictionaryValue{} = False
408+ isSimpleDictionaryValue (DependentDictionaryValue _ ds) = all isSimpleDictionaryValue ds
409+ isSimpleDictionaryValue _ = True
411+ -- Check if two dictionaries are overlapping
413+ -- Dictionaries which are subclass dictionaries cannot overlap, since otherwise the overlap would have
414+ -- been caught when constructing superclass dictionaries.
416+ overlapping :: DictionaryValue -> DictionaryValue -> Bool
417+ overlapping (LocalDictionaryValue nm1) (LocalDictionaryValue nm2) | nm1 == nm2 = False
418+ overlapping (GlobalDictionaryValue nm1) (GlobalDictionaryValue nm2) | nm1 == nm2 = False
419+ overlapping (DependentDictionaryValue nm1 ds1) (DependentDictionaryValue nm2 ds2)
420+ | nm1 == nm2 = any id $ zipWith overlapping ds1 ds2
421+ overlapping (SubclassDictionaryValue _ _ _) _ = False
422+ overlapping _ (SubclassDictionaryValue _ _ _) = False
423+ overlapping _ _ = True
425+ -- Render a DictionaryValue fit for human consumption in error messages
427+ prettyPrintDictionaryValue :: DictionaryValue -> String
428+ prettyPrintDictionaryValue = unlines . indented 0
430+ indented n (LocalDictionaryValue _) = [spaces n ++ "Dictionary in scope"]
431+ indented n (GlobalDictionaryValue nm) = [spaces n ++ show nm]
432+ indented n (DependentDictionaryValue nm args) = (spaces n ++ show nm ++ " via") : concatMap (indented (n + 2)) args
433+ indented n (SubclassDictionaryValue sup nm _) = (spaces n ++ show nm ++ " via superclass") : indented (n + 2) sup
435+ spaces n = replicate n ' ' ++ "- "
437+ valUndefined :: Expr
438+ valUndefined = Var (Qualified (Just (ModuleName [ProperName C.prim])) (Ident C.undefined))
441+-- Check all values in a list pairwise match a predicate
443+pairwise :: (a -> a -> Bool) -> [a] -> Bool
445+pairwise _ [_] = True
446+pairwise p (x : xs) = all (p x) xs && pairwise p xs
449+-- Check that two types unify
451+unifiesWith :: Environment -> Type -> Type -> Bool
452+unifiesWith _ (TUnknown u1) (TUnknown u2) | u1 == u2 = True
453+unifiesWith _ (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = True
454+unifiesWith _ (TypeVar v1) (TypeVar v2) | v1 == v2 = True
455+unifiesWith _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = True
456+unifiesWith e (TypeApp h1 t1) (TypeApp h2 t2) = unifiesWith e h1 h2 && unifiesWith e t1 t2
457+unifiesWith e (SaturatedTypeSynonym name args) t2 =
458+ case expandTypeSynonym' e name args of
460+ Right t1 -> unifiesWith e t1 t2
461+unifiesWith e t1 t2@(SaturatedTypeSynonym _ _) = unifiesWith e t2 t1
462+unifiesWith _ _ _ = False
465+-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
466+-- and return a substitution from type variables to types which makes the type heads unify.
468+typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
469+typeHeadsAreEqual _ _ (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = Just []
470+typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
471+typeHeadsAreEqual _ _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = Just []
472+typeHeadsAreEqual m e (TypeApp h1 t1) (TypeApp h2 t2) = (++) <$> typeHeadsAreEqual m e h1 h2 <*> typeHeadsAreEqual m e t1 t2
473+typeHeadsAreEqual m e (SaturatedTypeSynonym name args) t2 = case expandTypeSynonym' e name args of
475+ Right t1 -> typeHeadsAreEqual m e t1 t2
476+typeHeadsAreEqual _ _ _ _ = Nothing
479+-- Ensure skolem variables do not escape their scope
481+skolemEscapeCheck :: Expr -> Check ()
482+skolemEscapeCheck (TypedValue False _ _) = return ()
483+skolemEscapeCheck root@TypedValue{} =
484+ -- Every skolem variable is created when a ForAll type is skolemized.
485+ -- This determines the scope of that skolem variable, which is copied from the SkolemScope
486+ -- field of the ForAll constructor.
487+ -- We traverse the tree top-down, and collect any SkolemScopes introduced by ForAlls.
488+ -- If a Skolem is encountered whose SkolemScope is not in the current list, we have found
489+ -- an escaped skolem variable.
490+ let (_, f, _, _, _) = everythingWithContextOnValues [] [] (++) def go def def def
493+ ((binding, val) : _) -> throwError $ mkErrorStack ("Rigid/skolem type variable " ++ maybe "" (("bound by " ++) . prettyPrintValue) binding ++ " has escaped.") (Just (ExprError val))
497+ go :: [(SkolemScope, Expr)] -> Expr -> ([(SkolemScope, Expr)], [(Maybe Expr, Expr)])
498+ go scos val@(TypedValue _ _ (ForAll _ _ (Just sco))) = ((sco, val) : scos, [])
499+ go scos val@(TypedValue _ _ ty) = case collectSkolems ty \\ map fst scos of
500+ (sco : _) -> (scos, [(findBindingScope sco, val)])
503+ collectSkolems :: Type -> [SkolemScope]
504+ collectSkolems = nub . everythingOnTypes (++) collect
506+ collect (Skolem _ _ scope) = [scope]
508+ go scos _ = (scos, [])
509+ findBindingScope :: SkolemScope -> Maybe Expr
510+ findBindingScope sco =
511+ let (_, f, _, _, _) = everythingOnValues mappend (const mempty) go' (const mempty) (const mempty) (const mempty)
512+ in getFirst $ f root
514+ go' val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = First (Just val)
516+skolemEscapeCheck val = throwError $ mkErrorStack "Untyped value passed to skolemEscapeCheck" (Just (ExprError val))
519+-- Ensure rows do not contain duplicate labels
521+checkDuplicateLabels :: Expr -> Check ()
522+checkDuplicateLabels =
523+ let (_, f, _) = everywhereOnValuesM def go def
529+ go :: Expr -> Check Expr
530+ go e@(TypedValue _ val ty) = do
535+ checkDups :: Type -> Check ()
536+ checkDups (TypeApp t1 t2) = checkDups t1 >> checkDups t2
537+ checkDups (SaturatedTypeSynonym _ ts) = mapM_ checkDups ts
538+ checkDups (ForAll _ t _) = checkDups t
539+ checkDups (ConstrainedType args t) = do
540+ mapM_ (checkDups) $ concatMap snd args
542+ checkDups r@(RCons _ _ _) =
543+ let (ls, _) = rowToList r in
544+ case firstDup . sort . map fst $ ls of
545+ Just l -> throwError $ mkErrorStack ("Duplicate label " ++ show l ++ " in row") $ Just (ExprError val)
546+ Nothing -> return ()
547+ checkDups _ = return ()
549+ firstDup :: (Eq a) => [a] -> Maybe a
550+ firstDup (x : xs@(x' : _))
552+ | otherwise = firstDup xs
553+ firstDup _ = Nothing
555+ go other = return other
558+-- Replace outermost unsolved unification variables with named type variables
560+varIfUnknown :: Type -> Type
562+ let unks = nub $ unknowns ty
563+ toName = (:) 't' . show
564+ ty' = everywhereOnTypes typeToVar ty
565+ typeToVar :: Type -> Type
566+ typeToVar (TUnknown u) = TypeVar (toName u)
568+ in mkForAll (sort . map toName $ unks) ty'
571+-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
572+-- or TypeClassDictionary values.
574+-- This is necessary during type checking to avoid unifying a polymorphic type with a
575+-- unification variable.
577+instantiatePolyTypeWithUnknowns :: Expr -> Type -> UnifyT Type Check (Expr, Type)
578+instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
579+ ty' <- replaceVarWithUnknown ident ty
580+ instantiatePolyTypeWithUnknowns val ty'
581+instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
582+ dicts <- getTypeClassDictionaries
583+ (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
584+ return (foldl App val (map (flip (TypeClassDictionary True) dicts) constraints), ty')
585+instantiatePolyTypeWithUnknowns val ty = return (val, ty)
588+-- Replace a single type variable with a new unification variable
590+replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
591+replaceVarWithUnknown ident ty = do
593+ return $ replaceTypeVars ident tu ty
596+-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
597+-- better error messages during unification.
599+replaceAllTypeSynonyms' :: Environment -> Type -> Either String Type
600+replaceAllTypeSynonyms' env d =
602+ syns = map (\(name, (args, _)) -> (name, length args)) . M.toList $ typeSynonyms env
604+ saturateAllTypeSynonyms syns d
606+replaceAllTypeSynonyms :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
607+replaceAllTypeSynonyms d = do
609+ either (throwError . strMsg) return $ replaceAllTypeSynonyms' env d
612+-- \"Desaturate\" @SaturatedTypeSynonym@s
614+desaturateAllTypeSynonyms :: Type -> Type
615+desaturateAllTypeSynonyms = everywhereOnTypes replaceSaturatedTypeSynonym
617+ replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
618+ replaceSaturatedTypeSynonym t = t
621+-- Replace a type synonym and its arguments with the aliased type
623+expandTypeSynonym' :: Environment -> Qualified ProperName -> [Type] -> Either String Type
624+expandTypeSynonym' env name args =
625+ case M.lookup name (typeSynonyms env) of
626+ Just (synArgs, body) -> do
627+ let repl = replaceAllTypeVars (zip (map fst synArgs) args) body
628+ replaceAllTypeSynonyms' env repl
629+ Nothing -> error "Type synonym was not defined"
631+expandTypeSynonym :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Qualified ProperName -> [Type] -> m Type
632+expandTypeSynonym name args = do
634+ either (throwError . strMsg) return $ expandTypeSynonym' env name args
636+expandAllTypeSynonyms :: (Error e, Functor m, Applicative m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
637+expandAllTypeSynonyms = everywhereOnTypesTopDownM go
639+ go (SaturatedTypeSynonym name args) = expandTypeSynonym name args
640+ go other = return other
643+-- Ensure a set of property names and value does not contain duplicate labels
645+ensureNoDuplicateProperties :: (Error e, MonadError e m) => [(String, Expr)] -> m ()
646+ensureNoDuplicateProperties ps = guardWith (strMsg "Duplicate property names") $ length (nub . map fst $ ps) == length ps
649+-- Infer a type for a value, rethrowing any error to provide a more useful error message
651+infer :: Expr -> UnifyT Type Check Expr
652+infer val = rethrow (mkErrorStack "Error inferring type of value" (Just (ExprError val)) <>) $ infer' val
655+-- Infer a type for a value
657+infer' :: Expr -> UnifyT Type Check Expr
658+infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
659+infer' v@(StringLiteral _) = return $ TypedValue True v tyString
660+infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
661+infer' (ArrayLiteral vals) = do
662+ ts <- mapM infer vals
664+ forM_ ts $ \(TypedValue _ _ t) -> els =?= t
665+ return $ TypedValue True (ArrayLiteral ts) (TypeApp tyArray els)
666+infer' (ObjectLiteral ps) = do
667+ ensureNoDuplicateProperties ps
668+ ts <- mapM (infer . snd) ps
669+ let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
670+ ty = TypeApp tyObject $ rowFromList (fields, REmpty)
671+ return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
672+infer' (ObjectUpdate o ps) = do
673+ ensureNoDuplicateProperties ps
675+ newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
676+ let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
677+ oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
678+ let oldTy = TypeApp tyObject $ rowFromList (oldTys, row)
679+ o' <- TypedValue True <$> check o oldTy <*> pure oldTy
680+ return $ TypedValue True (ObjectUpdate o' newVals) $ TypeApp tyObject $ rowFromList (newTys, row)
681+infer' (Accessor prop val) = do
682+ typed@(TypedValue _ _ objTy) <- infer val
683+ propTy <- inferProperty objTy prop
688+ _ <- subsumes Nothing objTy (TypeApp tyObject (RCons prop field rest))
689+ return $ TypedValue True (Accessor prop typed) field
690+ Just ty -> return $ TypedValue True (Accessor prop typed) ty
691+infer' (Abs (Left arg) ret) = do
693+ Just moduleName <- checkCurrentModule <$> get
694+ makeBindingGroupVisible $ bindLocalVariables moduleName [(arg, ty, Defined)] $ do
695+ body@(TypedValue _ _ bodyTy) <- infer' ret
696+ return $ TypedValue True (Abs (Left arg) body) $ function ty bodyTy
697+infer' (Abs (Right _) _) = error "Binder was not desugared"
698+infer' (App f arg) = do
699+ f'@(TypedValue _ _ ft) <- infer f
700+ (ret, app) <- checkFunctionApplication f' ft arg Nothing
701+ return $ TypedValue True app ret
702+infer' (Var var) = do
703+ Just moduleName <- checkCurrentModule <$> get
704+ checkVisibility moduleName var
705+ ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
707+ ConstrainedType constraints ty' -> do
708+ dicts <- getTypeClassDictionaries
709+ return $ TypedValue True (foldl App (Var var) (map (flip (TypeClassDictionary True) dicts) constraints)) ty'
710+ _ -> return $ TypedValue True (Var var) ty
711+infer' v@(Constructor c) = do
713+ case M.lookup c (dataConstructors env) of
714+ Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
715+ Just (_, _, ty) -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
716+ return $ TypedValue True v ty'
717+infer' (Case vals binders) = do
718+ ts <- mapM infer vals
720+ binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
721+ return $ TypedValue True (Case ts binders') ret
722+infer' (IfThenElse cond th el) = do
723+ cond' <- check cond tyBoolean
724+ v2@(TypedValue _ _ t2) <- infer th
725+ v3@(TypedValue _ _ t3) <- infer el
726+ (v2', v3', t) <- meet v2 v3 t2 t3
727+ return $ TypedValue True (IfThenElse cond' v2' v3') t
728+infer' (Let ds val) = do
729+ (ds', val'@(TypedValue _ _ valTy)) <- inferLetBinding [] ds val infer
730+ return $ TypedValue True (Let ds' val') valTy
731+infer' (SuperClassDictionary className tys) = do
732+ dicts <- getTypeClassDictionaries
733+ return $ TypeClassDictionary False (className, tys) dicts
734+infer' (TypedValue checkType val ty) = do
735+ Just moduleName <- checkCurrentModule <$> get
736+ kind <- liftCheck $ kindOf moduleName ty
737+ guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
738+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
739+ val' <- if checkType then check val ty' else return val
740+ return $ TypedValue True val' ty'
741+infer' (PositionedValue pos val) = rethrowWithPosition pos $ infer' val
742+infer' _ = error "Invalid argument to infer"
744+inferLetBinding :: [Declaration] -> [Declaration] -> Expr -> (Expr -> UnifyT Type Check Expr) -> UnifyT Type Check ([Declaration], Expr)
745+inferLetBinding seen [] ret j = (,) seen <$> makeBindingGroupVisible (j ret)
746+inferLetBinding seen (ValueDeclaration ident nameKind [] (Right (tv@(TypedValue checkType val ty))) : rest) ret j = do
747+ Just moduleName <- checkCurrentModule <$> get
748+ kind <- liftCheck $ kindOf moduleName ty
749+ guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
750+ let dict = M.singleton (moduleName, ident) (ty, nameKind, Undefined)
751+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
752+ TypedValue _ val' ty'' <- if checkType then bindNames dict (check val ty') else return tv
753+ bindNames (M.singleton (moduleName, ident) (ty'', nameKind, Defined)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] (Right (TypedValue checkType val' ty''))]) rest ret j
754+inferLetBinding seen (ValueDeclaration ident nameKind [] (Right val) : rest) ret j = do
756+ Just moduleName <- checkCurrentModule <$> get
757+ let dict = M.singleton (moduleName, ident) (valTy, nameKind, Undefined)
758+ TypedValue _ val' valTy' <- bindNames dict $ infer val
760+ bindNames (M.singleton (moduleName, ident) (valTy', nameKind, Defined)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] (Right val')]) rest ret j
761+inferLetBinding seen (BindingGroupDeclaration ds : rest) ret j = do
762+ Just moduleName <- checkCurrentModule <$> get
763+ (untyped, typed, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName (map (\(i, _, v) -> (i, v)) ds)
764+ ds1' <- parU typed $ \e -> checkTypedBindingGroupElement moduleName e dict
765+ ds2' <- forM untyped $ \e -> typeForBindingGroupElement e dict untypedDict
766+ let ds' = [(ident, LocalVariable, val') | (ident, (val', _)) <- ds1' ++ ds2']
767+ makeBindingGroupVisible $ bindNames dict $ inferLetBinding (seen ++ [BindingGroupDeclaration ds']) rest ret j
768+inferLetBinding seen (PositionedDeclaration pos d : ds) ret j = rethrowWithPosition pos $ do
769+ ((d' : ds'), val') <- inferLetBinding seen (d : ds) ret j
770+ return (PositionedDeclaration pos d' : ds', val')
771+inferLetBinding _ _ _ _ = error "Invalid argument to inferLetBinding"
774+-- Infer the type of a property inside a record with a given type
776+inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
777+inferProperty (TypeApp obj row) prop | obj == tyObject = do
778+ let (props, _) = rowToList row
779+ return $ lookup prop props
780+inferProperty (SaturatedTypeSynonym name args) prop = do
781+ replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
782+ inferProperty replaced prop
783+inferProperty (ForAll ident ty _) prop = do
784+ replaced <- replaceVarWithUnknown ident ty
785+ inferProperty replaced prop
786+inferProperty _ _ = return Nothing
789+-- Infer the types of variables brought into scope by a binder
791+inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
792+inferBinder _ NullBinder = return M.empty
793+inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
794+inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
795+inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
796+inferBinder val (VarBinder name) = return $ M.singleton name val
797+inferBinder val (ConstructorBinder ctor binders) = do
799+ case M.lookup ctor (dataConstructors env) of
800+ Just (_, _, ty) -> do
801+ (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contain constraints") ty
802+ fn' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ fn
806+ _ <- subsumes Nothing val ty'
808+ go (binder : binders') (TypeApp (TypeApp t obj) ret) | t == tyFunction =
809+ M.union <$> inferBinder obj binder <*> go binders' ret
810+ go _ _ = throwError . strMsg $ "Wrong number of arguments to constructor " ++ show ctor
811+ _ -> throwError . strMsg $ "Constructor " ++ show ctor ++ " is not defined"
812+inferBinder val (ObjectBinder props) = do
815+ m1 <- inferRowProperties row rest props
816+ val =?= TypeApp tyObject row
819+ inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
820+ inferRowProperties nrow row [] = nrow =?= row >> return M.empty
821+ inferRowProperties nrow row ((name, binder):binders) = do
823+ m1 <- inferBinder propTy binder
824+ m2 <- inferRowProperties nrow (RCons name propTy row) binders
825+ return $ m1 `M.union` m2
826+inferBinder val (ArrayBinder binders) = do
828+ m1 <- M.unions <$> mapM (inferBinder el) binders
829+ val =?= TypeApp tyArray el
831+inferBinder val (ConsBinder headBinder tailBinder) = do
833+ m1 <- inferBinder el headBinder
834+ m2 <- inferBinder val tailBinder
835+ val =?= TypeApp tyArray el
836+ return $ m1 `M.union` m2
837+inferBinder val (NamedBinder name binder) = do
838+ m <- inferBinder val binder
839+ return $ M.insert name val m
840+inferBinder val (PositionedBinder pos binder) =
841+ rethrowWithPosition pos $ inferBinder val binder
844+-- Check the types of the return values in a set of binders in a case statement
846+checkBinders :: [Type] -> Type -> [CaseAlternative] -> UnifyT Type Check [CaseAlternative]
847+checkBinders _ _ [] = return []
848+checkBinders nvals ret (CaseAlternative binders result : bs) = do
849+ guardWith (strMsg "Overlapping binders in case statement") $
850+ let ns = concatMap binderNames binders in length (nub ns) == length ns
851+ Just moduleName <- checkCurrentModule <$> get
852+ m1 <- M.unions <$> zipWithM inferBinder nvals binders
853+ r <- bindLocalVariables moduleName [ (name, ty, Defined) | (name, ty) <- M.toList m1 ] $
854+ CaseAlternative binders <$>
857+ gs' <- forM gs $ \(grd, val) -> do
858+ grd' <- check grd tyBoolean
859+ val' <- TypedValue True <$> check val ret <*> pure ret
863+ val' <- TypedValue True <$> check val ret <*> pure ret
865+ rs <- checkBinders nvals ret bs
869+-- Generate a new skolem constant
871+newSkolemConstant :: UnifyT Type Check Int
872+newSkolemConstant = fresh'
875+-- Generate a new skolem scope
877+newSkolemScope :: UnifyT Type Check SkolemScope
878+newSkolemScope = SkolemScope <$> fresh'
881+-- Skolemize a type variable by replacing its instances with fresh skolem constants
883+skolemize :: String -> Int -> SkolemScope -> Type -> Type
884+skolemize ident sko scope = replaceTypeVars ident (Skolem ident sko scope)
887+-- This function has one purpose - to skolemize type variables appearing in a
888+-- SuperClassDictionary placeholder. These type variables are somewhat unique since they are the
889+-- only example of scoped type variables.
891+skolemizeTypesInValue :: String -> Int -> SkolemScope -> Expr -> Expr
892+skolemizeTypesInValue ident sko scope = let (_, f, _) = everywhereOnValues id go id in f
894+ go (SuperClassDictionary c ts) = SuperClassDictionary c (map (skolemize ident sko scope) ts)
898+-- Introduce skolem scope at every occurence of a ForAll
900+introduceSkolemScope :: Type -> UnifyT Type Check Type
901+introduceSkolemScope = everywhereOnTypesM go
903+ go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
904+ go other = return other
907+-- Check the type of a value, rethrowing errors to provide a better error message
909+check :: Expr -> Type -> UnifyT Type Check Expr
910+check val ty = rethrow (mkErrorStack errorMessage (Just (ExprError val)) <>) $ check' val ty
913+ "Error checking type of term " ++
914+ prettyPrintValue val ++
919+-- Check the type of a value
921+check' :: Expr -> Type -> UnifyT Type Check Expr
922+check' val (ForAll ident ty _) = do
923+ scope <- newSkolemScope
924+ sko <- newSkolemConstant
925+ let sk = skolemize ident sko scope ty
926+ let skVal = skolemizeTypesInValue ident sko scope val
927+ val' <- check skVal sk
928+ return $ TypedValue True val' (ForAll ident ty (Just scope))
929+check' val t@(ConstrainedType constraints ty) = do
930+ dictNames <- forM constraints $ \(Qualified _ (ProperName className), _) -> do
931+ n <- liftCheck freshDictionaryName
932+ return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
933+ val' <- makeBindingGroupVisible $ withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
934+ TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular False) (map (Qualified Nothing) dictNames)
935+ constraints) $ check val ty
936+ return $ TypedValue True (foldr (Abs . Left) val' dictNames) t
937+check' val (SaturatedTypeSynonym name args) = do
938+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
940+check' val u@(TUnknown _) = do
941+ val'@(TypedValue _ _ ty) <- infer val
942+ -- Don't unify an unknown with an inferred polytype
943+ (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
945+ return $ TypedValue True val'' ty'
946+check' v@(NumericLiteral _) t | t == tyNumber =
947+ return $ TypedValue True v t
948+check' v@(StringLiteral _) t | t == tyString =
949+ return $ TypedValue True v t
950+check' v@(BooleanLiteral _) t | t == tyBoolean =
951+ return $ TypedValue True v t
952+check' (ArrayLiteral vals) t@(TypeApp a ty) = do
954+ array <- ArrayLiteral <$> forM vals (`check` ty)
955+ return $ TypedValue True array t
956+check' (Abs (Left arg) ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
957+ Just moduleName <- checkCurrentModule <$> get
958+ ret' <- makeBindingGroupVisible $ bindLocalVariables moduleName [(arg, argTy, Defined)] $ check ret retTy
959+ return $ TypedValue True (Abs (Left arg) ret') ty
960+check' (Abs (Right _) _) _ = error "Binder was not desugared"
961+check' (App f arg) ret = do
962+ f'@(TypedValue _ _ ft) <- infer f
963+ (_, app) <- checkFunctionApplication f' ft arg (Just ret)
964+ return $ TypedValue True app ret
965+check' v@(Var var) ty = do
966+ Just moduleName <- checkCurrentModule <$> get
967+ checkVisibility moduleName var
968+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
969+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
970+ v' <- subsumes (Just v) repl ty'
972+ Nothing -> throwError . strMsg $ "Unable to check type subsumption"
973+ Just v'' -> return $ TypedValue True v'' ty'
974+check' (SuperClassDictionary className tys) _ = do
976+ -- Here, we replace a placeholder for a superclass dictionary with a regular
977+ -- TypeClassDictionary placeholder. The reason we do this is that it is necessary to have the
978+ -- correct super instance dictionaries in scope, and these are not available when the type class
979+ -- declaration gets desugared.
981+ -- Note also that the first argument to TypeClassDictionary is False, meaning we _do not_ want
982+ -- to consider superclass instances when searching for this dictionary - doing so might lead
983+ -- to traversing a cycle in the instance graph.
985+ dicts <- getTypeClassDictionaries
986+ return $ TypeClassDictionary False (className, tys) dicts
987+check' (TypedValue checkType val ty1) ty2 = do
988+ Just moduleName <- checkCurrentModule <$> get
989+ kind <- liftCheck $ kindOf moduleName ty1
990+ guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
991+ ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
992+ ty2' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty2
993+ val' <- subsumes (Just val) ty1' ty2'
995+ Nothing -> throwError . strMsg $ "Unable to check type subsumption"
997+ val''' <- if checkType then check val'' ty2' else return val''
998+ return $ TypedValue checkType (TypedValue True val''' ty1') ty2'
999+check' (Case vals binders) ret = do
1000+ vals' <- mapM infer vals
1001+ let ts = map (\(TypedValue _ _ t) -> t) vals'
1002+ binders' <- checkBinders ts ret binders
1003+ return $ TypedValue True (Case vals' binders') ret
1004+check' (IfThenElse cond th el) ty = do
1005+ cond' <- check cond tyBoolean
1008+ return $ TypedValue True (IfThenElse cond' th' el') ty
1009+check' (ObjectLiteral ps) t@(TypeApp obj row) | obj == tyObject = do
1010+ ensureNoDuplicateProperties ps
1011+ ps' <- checkProperties ps row False
1012+ return $ TypedValue True (ObjectLiteral ps') t
1013+check' (TypeClassDictionaryConstructorApp name ps) t = do
1015+ return $ TypedValue True (TypeClassDictionaryConstructorApp name ps') t
1016+check' (ObjectUpdate obj ps) t@(TypeApp o row) | o == tyObject = do
1017+ ensureNoDuplicateProperties ps
1018+ -- We need to be careful to avoid duplicate labels here.
1019+ -- We check _obj_ agaist the type _t_ with the types in _ps_ replaced with unknowns.
1020+ let (propsToCheck, rest) = rowToList row
1021+ (removedProps, remainingProps) = partition (\(p, _) -> p `elem` map fst ps) propsToCheck
1022+ us <- zip (map fst removedProps) <$> replicateM (length ps) fresh
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' val kt@(KindedType ty kind) = do
1045+ guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
1046+ val' <- check' val ty
1047+ return $ TypedValue True val' kt
1048+check' (PositionedValue pos val) ty =
1049+ rethrowWithPosition pos $ check val ty
1050+check' val ty = throwError $ mkErrorStack ("Expr does not have type " ++ prettyPrintType ty) (Just (ExprError val))
1052+containsTypeSynonyms :: Type -> Bool
1053+containsTypeSynonyms = everythingOnTypes (||) go where
1054+ go (SaturatedTypeSynonym _ _) = True
1058+-- Check the type of a collection of named record fields
1060+-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
1062+checkProperties :: [(String, Expr)] -> Type -> Bool -> UnifyT Type Check [(String, Expr)]
1063+checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
1064+ go [] [] REmpty = return []
1065+ go [] [] u@(TUnknown _) = do u =?= REmpty
1067+ go [] [] (Skolem _ _ _) | lax = return []
1068+ go [] ((p, _): _) _ | lax = return []
1069+ | otherwise = throwError $ mkErrorStack ("Object does not have property " ++ p) (Just (ExprError (ObjectLiteral ps)))
1070+ go ((p,_):_) [] REmpty = throwError $ mkErrorStack ("Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row) (Just (ExprError (ObjectLiteral ps)))
1071+ go ((p,v):ps') [] u@(TUnknown _) = do
1072+ v'@(TypedValue _ _ ty) <- infer v
1074+ u =?= RCons p ty rest
1075+ ps'' <- go ps' [] rest
1076+ return $ (p, v') : ps''
1077+ go ((p,v):ps') ts r =
1078+ case lookup p ts of
1080+ v'@(TypedValue _ _ ty) <- infer v
1082+ r =?= RCons p ty rest
1083+ ps'' <- go ps' ts rest
1084+ return $ (p, v') : ps''
1087+ ps'' <- go ps' (delete (p, ty) ts) r
1088+ return $ (p, v') : ps''
1089+ go _ _ _ = throwError $ mkErrorStack ("Object does not have type " ++ prettyPrintType (TypeApp tyObject row)) (Just (ExprError (ObjectLiteral ps)))
1092+-- Check the type of a function application, rethrowing errors to provide a better error message
1094+checkFunctionApplication :: Expr -> Type -> Expr -> Maybe Type -> UnifyT Type Check (Type, Expr)
1095+checkFunctionApplication fn fnTy arg ret = rethrow (mkErrorStack errorMessage (Just (ExprError fn)) <>) $ do
1096+ subst <- unifyCurrentSubstitution <$> UnifyT get
1097+ checkFunctionApplication' fn (subst $? fnTy) arg (($?) subst <$> ret)
1099+ errorMessage = "Error applying function of type "
1100+ ++ prettyPrintType fnTy
1101+ ++ " to argument " ++ prettyPrintValue arg
1104+-- Check the type of a function application
1106+checkFunctionApplication' :: Expr -> Type -> Expr -> Maybe Type -> UnifyT Type Check (Type, Expr)
1107+checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg ret = do
1108+ tyFunction' =?= tyFunction
1109+ arg' <- check arg argTy
1111+ Nothing -> return (retTy, App fn arg')
1113+ Just app' <- subsumes (Just (App fn arg')) retTy ret'
1114+ return (retTy, app')
1115+checkFunctionApplication' fn (ForAll ident ty _) arg ret = do
1116+ replaced <- replaceVarWithUnknown ident ty
1117+ checkFunctionApplication fn replaced arg ret
1118+checkFunctionApplication' fn u@(TUnknown _) arg ret = do
1120+ TypedValue _ arg' t <- infer arg
1121+ (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
1122+ return $ TypedValue True arg'' t'
1123+ let ty = (\(TypedValue _ _ t) -> t) arg'
1124+ ret' <- maybe fresh return ret
1125+ u =?= function ty ret'
1126+ return (ret', App fn arg')
1127+checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
1128+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1129+ checkFunctionApplication fn ty arg ret
1130+checkFunctionApplication' fn (KindedType ty _) arg ret = do
1131+ checkFunctionApplication fn ty arg ret
1132+checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
1133+ dicts <- getTypeClassDictionaries
1134+ checkFunctionApplication' (foldl App fn (map (flip (TypeClassDictionary True) dicts) constraints)) fnTy arg ret
1135+checkFunctionApplication' fn fnTy dict@(TypeClassDictionary _ _ _) _ =
1136+ return (fnTy, App fn dict)
1137+checkFunctionApplication' _ fnTy arg _ = throwError . strMsg $ "Cannot apply a function of type "
1138+ ++ prettyPrintType fnTy
1139+ ++ " to argument " ++ prettyPrintValue arg
1142+-- Check whether one type subsumes another, rethrowing errors to provide a better error message
1144+subsumes :: Maybe Expr -> Type -> Type -> UnifyT Type Check (Maybe Expr)
1145+subsumes val ty1 ty2 = rethrow (mkErrorStack errorMessage (ExprError <$> val) <>) $ subsumes' val ty1 ty2
1147+ errorMessage = "Error checking that type "
1148+ ++ prettyPrintType ty1
1149+ ++ " subsumes type "
1150+ ++ prettyPrintType ty2
1153+-- Check whether one type subsumes another
1155+subsumes' :: Maybe Expr -> Type -> Type -> UnifyT Type Check (Maybe Expr)
1156+subsumes' val (ForAll ident ty1 _) ty2 = do
1157+ replaced <- replaceVarWithUnknown ident ty1
1158+ subsumes val replaced ty2
1159+subsumes' val ty1 (ForAll ident ty2 sco) =
1162+ sko <- newSkolemConstant
1163+ let sk = skolemize ident sko sco' ty2
1164+ subsumes val ty1 sk
1165+ Nothing -> throwError . strMsg $ "Skolem variable scope is unspecified"
1166+subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
1167+ _ <- subsumes Nothing arg2 arg1
1168+ _ <- subsumes Nothing ret1 ret2
1170+subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
1171+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1172+ subsumes val ty1 ty2
1173+subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
1174+ ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1175+ subsumes val ty1 ty2
1176+subsumes' val (KindedType ty1 _) ty2 = do
1177+ subsumes val ty1 ty2
1178+subsumes' val ty1 (KindedType ty2 _) = do
1179+ subsumes val ty1 ty2
1180+subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
1181+ dicts <- getTypeClassDictionaries
1182+ subsumes' (Just $ foldl App val (map (flip (TypeClassDictionary True) dicts) constraints)) ty1 ty2
1183+subsumes' val (TypeApp f1 r1) (TypeApp f2 r2) | f1 == tyObject && f2 == tyObject = do
1185+ (ts1, r1') = rowToList r1
1186+ (ts2, r2') = rowToList r2
1187+ ts1' = sortBy (comparing fst) ts1
1188+ ts2' = sortBy (comparing fst) ts2
1189+ go ts1' ts2' r1' r2'
1192+ go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
1193+ go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
1194+ go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
1195+ | p1 == p2 = do _ <- subsumes Nothing ty1 ty2
1197+ | p1 < p2 = do rest <- fresh
1198+ r2' =?= RCons p1 ty1 rest
1199+ go ts1 ((p2, ty2) : ts2) r1' rest
1200+ | otherwise = do rest <- fresh
1201+ r1' =?= RCons p2 ty2 rest
1202+ go ((p1, ty1) : ts1) ts2 rest r2'
1203+subsumes' val ty1 ty2@(TypeApp obj _) | obj == tyObject = subsumes val ty2 ty1
1204+subsumes' val ty1 ty2 = do
1209+-- Compute the meet of two types, i.e. the most general type which both types subsume.
1210+-- TODO: handle constrained types
1212+meet :: Expr -> Expr -> Type -> Type -> UnifyT Type Check (Expr, Expr, Type)
1213+meet e1 e2 (ForAll ident t1 _) t2 = do
1214+ t1' <- replaceVarWithUnknown ident t1
1216+meet e1 e2 t1 (ForAll ident t2 _) = do
1217+ t2' <- replaceVarWithUnknown ident t2
1219+meet e1 e2 t1 t2 = do
1221+ return (e1, e2, t1)