@@ -0,0 +1,966 @@
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 FlexibleContexts #-}
18+{-# LANGUAGE MultiParamTypeClasses #-}
20+module Language.PureScript.TypeChecker.Types (
25+ The following functions represent the corresponding type checking judgements:
28+ Synthesize a type for a value
31+ Check a value has a given type
34+ Check an object with a given type contains specified properties
36+ checkFunctionApplication
37+ Check a function of a given type returns a value of another type when applied to its arguments
40+ Check a type subsumes another type
44+import Data.Maybe (maybeToList, isNothing, isJust, fromMaybe)
45+import qualified Data.Data as D
47+ (everythingWithContext, mkM, everywhereM, everything, mkT,
48+ something, everywhere, mkQ)
49+import Data.Generics.Extras
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 qualified Language.PureScript.Constants as C
63+import Control.Monad.State
64+import Control.Monad.Error
65+import Control.Monad.Unify
67+import Control.Applicative
68+import Control.Arrow (Arrow(..))
70+import qualified Data.Map as M
71+import Data.Function (on)
72+import Data.Ord (comparing)
74+instance Partial Type where
76+ isUnknown (TUnknown u) = Just u
77+ isUnknown _ = Nothing
79+instance Unifiable Check Type where
83+-- Unify two types, updating the current substitution
85+unifyTypes :: Type -> Type -> UnifyT Type Check ()
86+unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $
89+ unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
90+ unifyTypes' (TUnknown u) t = u =:= t
91+ unifyTypes' t (TUnknown u) = u =:= t
92+ unifyTypes' (SaturatedTypeSynonym name args) ty = do
93+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ args
95+ unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
96+ unifyTypes' (ForAll ident1 ty1 sc1) (ForAll ident2 ty2 sc2) =
98+ (Just sc1', Just sc2') -> do
99+ sko <- newSkolemConstant
100+ let sk1 = skolemize ident1 sko sc1' ty1
101+ let sk2 = skolemize ident2 sko sc2' ty2
102+ sk1 `unifyTypes` sk2
103+ _ -> throwError (prettyPrintType ty1)
104+ unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
105+ sko <- newSkolemConstant
106+ let sk = skolemize ident sko sc ty1
108+ unifyTypes' ForAll{} _ = throwError "Skolem variable scope is unspecified"
109+ unifyTypes' ty f@ForAll{} = f `unifyTypes` ty
110+ unifyTypes' (Object row1) (Object row2) = row1 =?= row2
111+ unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
112+ unifyTypes' (TypeConstructor c1) (TypeConstructor c2) =
113+ guardWith ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".") (c1 == c2)
114+ unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
117+ unifyTypes' (Skolem s1 _) (Skolem s2 _) | s1 == s2 = return ()
118+ unifyTypes' r1@RCons{} r2 = unifyRows r1 r2
119+ unifyTypes' r1 r2@RCons{} = unifyRows r1 r2
120+ unifyTypes' r1@REmpty r2 = unifyRows r1 r2
121+ unifyTypes' r1 r2@REmpty = unifyRows r1 r2
122+ unifyTypes' t@(ConstrainedType _ _) _ = throwError $ "Attempted to unify a constrained type " ++ prettyPrintType t ++
123+ " with another type."
124+ unifyTypes' t3 t4@(ConstrainedType _ _) = unifyTypes' t4 t3
125+ unifyTypes' t3 t4 = throwError $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
128+-- Unify two rows, updating the current substitution
130+-- Common labels are first identified, and unified. Remaining labels and types are unified with a
131+-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
134+unifyRows :: Type -> Type -> UnifyT Type Check ()
137+ (s1, r1') = rowToList r1
138+ (s2, r2') = rowToList r2
139+ int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
140+ sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
141+ sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
143+ forM_ int (uncurry (=?=))
144+ unifyRows' sd1 r1' sd2 r2'
146+ unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
147+ unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
148+ unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
149+ unifyRows' ((name, ty):row) r others u@(TUnknown un) = do
151+ forM_ row $ \(_, t) -> occursCheck un t
153+ u =?= RCons name ty u'
154+ unifyRows' row r others u'
155+ unifyRows' [] REmpty [] REmpty = return ()
156+ unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
157+ unifyRows' [] (Skolem s1 _) [] (Skolem s2 _) | s1 == s2 = return ()
158+ unifyRows' sd3 r3 sd4 r4 = throwError $ "Cannot unify (" ++ prettyPrintRow (rowFromList (sd3, r3)) ++ ") with (" ++ prettyPrintRow (rowFromList (sd4, r4)) ++ ")."
161+-- Infer the types of multiple mutually-recursive values, and return elaborated values including
162+-- type class dictionaries and type annotations.
164+typesOf :: Maybe ModuleName -> ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
165+typesOf mainModuleName moduleName vals = do
166+ tys <- fmap tidyUp . liftUnify $ do
167+ (es, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName vals
169+ triple@(_, (_, ty)) <- typeForBindingGroupElement moduleName e dict untypedDict
170+ -- If --main is enabled, need to check that `main` has type Eff eff a for some eff, a
171+ when (Just moduleName == mainModuleName && fst e == Ident C.main) $ do
172+ [eff, a] <- replicateM 2 fresh
173+ ty =?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName [ProperName "Control", ProperName "Monad", ProperName "Eff"])) (ProperName "Eff"))) eff) a
176+ forM tys $ \(ident, (val, ty)) -> do
177+ -- Replace type class dictionary placeholders with actual dictionaries
178+ val' <- replaceTypeClassDictionaries moduleName val
179+ -- Check skolem variables did not escape their scope
180+ skolemEscapeCheck val'
181+ -- Remove type synonyms placeholders, remove duplicate row fields, and replace
182+ -- top-level unification variables with named type variables.
183+ let val'' = overTypes (desaturateAllTypeSynonyms . setifyAll) val'
184+ ty' = varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty
185+ return (ident, (val'', ty'))
187+ -- Apply the substitution that was returned from runUnify to both types and (type-annotated) values
188+ tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
190+typeDictionaryForBindingGroup :: ModuleName -> [(Ident, Value)] -> UnifyT Type Check ([(Ident, (Value, Maybe (Type, Bool)))], M.Map (ModuleName, Ident) (Type, NameKind), [(Ident, Type)])
191+typeDictionaryForBindingGroup moduleName vals = do
193+ -- Map each declaration to a name/value pair, with an optional type, if the declaration is typed
194+ es = map isTyped vals
195+ -- Filter the typed and untyped declarations
196+ typed = filter (isJust . snd . snd) es
197+ untyped = filter (isNothing . snd . snd) es
198+ -- Make a map of names to typed declarations
199+ typedDict = map (\(ident, (_, Just (ty, _))) -> (ident, ty)) typed
201+ -- Create fresh unification variables for the types of untyped declarations
202+ untypedNames <- replicateM (length untyped) fresh
205+ -- Make a map of names to the unification variables of untyped declarations
206+ untypedDict = zip (map fst untyped) untypedNames
207+ -- Create the dictionary of all name/type pairs, which will be added to the environment during type checking
208+ dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable))) $ typedDict ++ untypedDict)
209+ return (es, dict, untypedDict)
211+typeForBindingGroupElement :: ModuleName -> (Ident, (Value, Maybe (Type, Bool))) -> M.Map (ModuleName, Ident) (Type, NameKind) -> [(Ident, Type)] -> UnifyT Type Check (Ident, (Value, Type))
212+typeForBindingGroupElement moduleName e@(_, (val, _)) dict untypedDict = do
213+ -- If the declaration is a function, it has access to other values in the binding group.
214+ -- If not, the generated code might fail at runtime since those values might be undefined.
215+ let dict' = if isFunction val then dict else M.empty
217+ -- Typed declarations
218+ (ident, (val', Just (ty, checkType))) -> do
220+ kind <- liftCheck $ kindOf moduleName ty
221+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
222+ -- Check the type with the new names in scope
223+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
224+ val'' <- bindNames dict' $ if checkType
225+ then TypedValue True <$> check val' ty' <*> pure ty'
226+ else return (TypedValue False val' ty')
227+ return (ident, (val'', ty'))
228+ -- Untyped declarations
229+ (ident, (val', Nothing)) -> do
230+ -- Infer the type with the new names in scope
231+ TypedValue _ val'' ty <- bindNames dict' $ infer val'
232+ ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
233+ return (ident, (TypedValue True val'' ty, ty))
236+-- Check if a value introduces a function
238+isFunction :: Value -> Bool
239+isFunction (Abs _ _) = True
240+isFunction (TypedValue _ val _) = isFunction val
244+-- Check if a value contains a type annotation
246+isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
247+isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
248+isTyped (name, value) = (name, (value, Nothing))
251+-- Map a function over type annotations appearing inside a value
253+overTypes :: (Type -> Type) -> Value -> Value
254+overTypes f = everywhere (mkT f)
257+-- Replace type class dictionary placeholders with inferred type class dictionaries
259+replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
260+replaceTypeClassDictionaries mn = everywhereM' (mkM go)
262+ go (TypeClassDictionary constraint dicts) = do
264+ entails env mn dicts constraint
265+ go other = return other
268+-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
269+-- return a type class dictionary reference.
271+entails :: Environment -> ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, [Type]) -> Check Value
272+entails env moduleName context goal@(className, tys) = do
274+ [] -> throwError $ "No " ++ show className ++ " instance found for " ++ intercalate ", " (map prettyPrintType tys)
275+ (dict : _) -> return dict
277+ go (className', tys') =
278+ [ mkDictionary (canonicalizeDictionary tcd) args
280+ -- Choose type class dictionaries in scope in the current module
282+ -- Make sure the type class name matches the one we are trying to satisfy
283+ , className' == tcdClassName tcd
284+ -- Make sure the type unifies with the type in the type instance definition
285+ , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' (tcdInstanceTypes tcd)
286+ -- Solve any necessary subgoals
287+ , args <- solveSubgoals subst (tcdDependencies tcd) ]
288+ -- Create dictionaries for subgoals which still need to be solved by calling go recursively
289+ -- E.g. the goal (Show a, Show b) => Show (Either a b) can be satisfied if the current type
290+ -- unifies with Either a b, and we can satisfy the subgoals Show a and Show b recursively.
291+ solveSubgoals :: [(String, Type)] -> Maybe [(Qualified ProperName, [Type])] -> [Maybe [Value]]
292+ solveSubgoals _ Nothing = return Nothing
293+ solveSubgoals subst (Just subgoals) = do
294+ dict <- mapM (go . second (map (replaceAllTypeVars subst))) subgoals
296+ -- Make a dictionary from subgoal dictionaries by applying the correct function
297+ mkDictionary :: Qualified Ident -> Maybe [Value] -> Value
298+ mkDictionary fnName Nothing = Var fnName
299+ mkDictionary fnName (Just []) = App (Var fnName) (ObjectLiteral [])
300+ mkDictionary fnName (Just dicts) = foldl App (Var fnName) dicts
301+ -- Filter out type dictionaries which are in scope in the current module
302+ filterModule :: TypeClassDictionaryInScope -> Bool
303+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
304+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
305+ filterModule _ = False
306+ -- Ensure that a substitution is valid
307+ verifySubstitution :: [(String, Type)] -> Maybe [(String, Type)]
308+ verifySubstitution subst = do
309+ let grps = groupBy ((==) `on` fst) subst
310+ guard (all (pairwise (unifiesWith env) . map snd) grps)
311+ return $ map head grps
314+-- Check all values in a list pairwise match a predicate
316+pairwise :: (a -> a -> Bool) -> [a] -> Bool
318+pairwise _ [_] = True
319+pairwise p (x : xs) = all (p x) xs && pairwise p xs
322+-- Check that two types unify
324+unifiesWith :: Environment -> Type -> Type -> Bool
325+unifiesWith _ (TUnknown _) _ = True
326+unifiesWith _ _ (TUnknown _) = True
327+unifiesWith _ (Skolem s1 _) (Skolem s2 _) | s1 == s2 = True
328+unifiesWith _ (TypeVar v1) (TypeVar v2) | v1 == v2 = True
329+unifiesWith _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = True
330+unifiesWith e (TypeApp h1 t1) (TypeApp h2 t2) = unifiesWith e h1 h2 && unifiesWith e t1 t2
331+unifiesWith e (SaturatedTypeSynonym name args) t2 =
332+ case expandTypeSynonym' e name args of
334+ Right t1 -> unifiesWith e t1 t2
335+unifiesWith e t1 t2@(SaturatedTypeSynonym _ _) = unifiesWith e t2 t1
336+unifiesWith _ _ _ = False
339+-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
340+-- and return a substitution from type variables to types which makes the type heads unify.
342+typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
343+typeHeadsAreEqual _ _ (Skolem s1 _) (Skolem s2 _) | s1 == s2 = Just []
344+typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
345+typeHeadsAreEqual _ _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = Just []
346+typeHeadsAreEqual m e (TypeApp h1 t1) (TypeApp h2 t2) = (++) <$> typeHeadsAreEqual m e h1 h2 <*> typeHeadsAreEqual m e t1 t2
347+typeHeadsAreEqual m e (SaturatedTypeSynonym name args) t2 = case expandTypeSynonym' e name args of
349+ Right t1 -> typeHeadsAreEqual m e t1 t2
350+typeHeadsAreEqual _ _ _ _ = Nothing
353+-- Ensure skolem variables do not escape their scope
355+skolemEscapeCheck :: Value -> Check ()
356+skolemEscapeCheck (TypedValue False _ _) = return ()
357+skolemEscapeCheck root@TypedValue{} =
358+ -- Every skolem variable is created when a ForAll type is skolemized.
359+ -- This determines the scope of that skolem variable, which is copied from the SkolemScope
360+ -- field of the ForAll constructor.
361+ -- We traverse the tree top-down, and collect any SkolemScopes introduced by ForAlls.
362+ -- If a Skolem is encountered whose SkolemScope is not in the current list, we have found
363+ -- an escaped skolem variable.
364+ case everythingWithContext [] (++) (mkQ ((,) []) go) root of
366+ ((binding, val) : _) -> throwError $ "Rigid/skolem type variable bound by " ++ maybe "<unknown>" prettyPrintValue binding ++ " has escaped at " ++ prettyPrintValue val
368+ go :: Value -> [(SkolemScope, Value)] -> ([(Maybe Value, Value)], [(SkolemScope, Value)])
369+ go val@(TypedValue _ _ (ForAll _ _ (Just sco))) scos = ([], (sco, val) : scos)
370+ go val@(TypedValue _ _ ty) scos = case collectSkolems ty \\ map fst scos of
371+ (sco : _) -> ([(findBindingScope sco, val)], scos)
374+ collectSkolems :: Type -> [SkolemScope]
375+ collectSkolems = nub . everything (++) (mkQ [] collect)
377+ collect (Skolem _ scope) = [scope]
379+ go _ scos = ([], scos)
380+ findBindingScope :: SkolemScope -> Maybe Value
381+ findBindingScope sco = something (mkQ Nothing go') root
383+ go' val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = Just val
385+skolemEscapeCheck val = throwError $ "Untyped value passed to skolemEscapeCheck: " ++ prettyPrintValue val
388+-- Ensure a row contains no duplicate labels
390+setify :: Type -> Type
391+setify = rowFromList . first (M.toList . M.fromList) . rowToList
394+-- \"Setify\" all rows occuring inside a value
396+setifyAll :: (D.Data d) => d -> d
397+setifyAll = everywhere (mkT setify)
400+-- Replace outermost unsolved unification variables with named type variables
402+varIfUnknown :: Type -> Type
404+ let unks = nub $ unknowns ty
405+ toName = (:) 't' . show
406+ ty' = everywhere (mkT typeToVar) ty
407+ typeToVar :: Type -> Type
408+ typeToVar (TUnknown (Unknown u)) = TypeVar (toName u)
410+ in mkForAll (sort . map (toName . runUnknown) $ unks) ty'
413+-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
414+-- or TypeClassDictionary values.
416+-- This is necessary during type checking to avoid unifying a polymorphic type with a
417+-- unification variable.
419+instantiatePolyTypeWithUnknowns :: Value -> Type -> UnifyT Type Check (Value, Type)
420+instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
421+ ty' <- replaceVarWithUnknown ident ty
422+ instantiatePolyTypeWithUnknowns val ty'
423+instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
424+ dicts <- getTypeClassDictionaries
425+ (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
426+ return (foldl App val (map (flip TypeClassDictionary dicts) constraints), ty')
427+instantiatePolyTypeWithUnknowns val ty = return (val, ty)
430+-- Replace a single type variable with a new unification variable
432+replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
433+replaceVarWithUnknown ident ty = do
435+ return $ replaceTypeVars ident tu ty
438+-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
439+-- better error messages during unification.
441+replaceAllTypeSynonyms' :: (D.Data d) => Environment -> d -> Either String d
442+replaceAllTypeSynonyms' env d =
444+ syns = map (\(name, (args, _)) -> (name, length args)) . M.toList $ typeSynonyms env
446+ saturateAllTypeSynonyms syns d
448+replaceAllTypeSynonyms :: (Functor m, Monad m, MonadState CheckState m, MonadError String m) => (D.Data d) => d -> m d
449+replaceAllTypeSynonyms d = do
451+ either throwError return $ replaceAllTypeSynonyms' env d
454+-- \"Desaturate\" @SaturatedTypeSynonym@s
456+desaturateAllTypeSynonyms :: (D.Data d) => d -> d
457+desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
459+ replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
460+ replaceSaturatedTypeSynonym t = t
463+-- Replace a type synonym and its arguments with the aliased type
465+expandTypeSynonym' :: Environment -> Qualified ProperName -> [Type] -> Either String Type
466+expandTypeSynonym' env name args =
467+ case M.lookup name (typeSynonyms env) of
468+ Just (synArgs, body) -> do
469+ let repl = replaceAllTypeVars (zip synArgs args) body
470+ replaceAllTypeSynonyms' env repl
471+ Nothing -> error "Type synonym was not defined"
473+expandTypeSynonym :: (Functor m, Monad m, MonadState CheckState m, MonadError String m) => Qualified ProperName -> [Type] -> m Type
474+expandTypeSynonym name args = do
476+ either throwError return $ expandTypeSynonym' env name args
479+-- Ensure a set of property names and value does not contain duplicate labels
481+ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
482+ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
485+-- Infer a type for a value, rethrowing any error to provide a more useful error message
487+infer :: Value -> UnifyT Type Check Value
488+infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
491+-- Infer a type for a value
493+infer' :: Value -> UnifyT Type Check Value
494+infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
495+infer' v@(StringLiteral _) = return $ TypedValue True v tyString
496+infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
497+infer' (ArrayLiteral vals) = do
498+ ts <- mapM infer vals
500+ forM_ ts $ \(TypedValue _ _ t) -> els =?= TypeApp tyArray t
501+ return $ TypedValue True (ArrayLiteral ts) els
502+infer' (ObjectLiteral ps) = do
503+ ensureNoDuplicateProperties ps
504+ ts <- mapM (infer . snd) ps
505+ let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
506+ ty = Object $ rowFromList (fields, REmpty)
507+ return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
508+infer' (ObjectUpdate o ps) = do
509+ ensureNoDuplicateProperties ps
511+ newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
512+ let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
513+ oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
514+ let oldTy = Object $ rowFromList (oldTys, row)
515+ o' <- TypedValue True <$> check o oldTy <*> pure oldTy
516+ return $ TypedValue True (ObjectUpdate o' newVals) $ Object $ rowFromList (newTys, row)
517+infer' (Accessor prop val) = do
518+ typed@(TypedValue _ _ objTy) <- infer val
519+ propTy <- inferProperty objTy prop
524+ _ <- subsumes Nothing objTy (Object (RCons prop field rest))
525+ return $ TypedValue True (Accessor prop typed) field
526+ Just ty -> return $ TypedValue True (Accessor prop typed) ty
527+infer' (Abs (Left arg) ret) = do
529+ Just moduleName <- checkCurrentModule <$> get
530+ bindLocalVariables moduleName [(arg, ty)] $ do
531+ body@(TypedValue _ _ bodyTy) <- infer' ret
532+ return $ TypedValue True (Abs (Left arg) body) $ function ty bodyTy
533+infer' (Abs (Right _) _) = error "Binder was not desugared"
534+infer' (App f arg) = do
535+ f'@(TypedValue _ _ ft) <- infer f
536+ (ret, app) <- checkFunctionApplication f' ft arg Nothing
537+ return $ TypedValue True app ret
538+infer' (Var var) = do
539+ Just moduleName <- checkCurrentModule <$> get
540+ ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
542+ ConstrainedType constraints ty' -> do
543+ dicts <- getTypeClassDictionaries
544+ return $ TypedValue True (foldl App (Var var) (map (flip TypeClassDictionary dicts) constraints)) ty'
545+ _ -> return $ TypedValue True (Var var) ty
546+infer' v@(Constructor c) = do
548+ case M.lookup c (dataConstructors env) of
549+ Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
550+ Just (_, ty) -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
551+ return $ TypedValue True v ty'
552+infer' (Case vals binders) = do
553+ ts <- mapM infer vals
555+ binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
556+ return $ TypedValue True (Case ts binders') ret
557+infer' (IfThenElse cond th el) = do
558+ cond' <- check cond tyBoolean
559+ v2@(TypedValue _ _ t2) <- infer th
560+ v3@(TypedValue _ _ t3) <- infer el
562+ return $ TypedValue True (IfThenElse cond' v2 v3) t2
563+infer' (Let ds val) = do
564+ (ds', val'@(TypedValue _ _ valTy)) <- inferLetBinding [] ds val infer
565+ return $ TypedValue True (Let ds' val') valTy
566+infer' (TypedValue checkType val ty) = do
567+ Just moduleName <- checkCurrentModule <$> get
568+ kind <- liftCheck $ kindOf moduleName ty
569+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
570+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
571+ val' <- if checkType then check val ty' else return val
572+ return $ TypedValue True val' ty'
573+infer' _ = error "Invalid argument to infer"
575+inferLetBinding :: [Declaration] -> [Declaration] -> Value -> (Value -> UnifyT Type Check Value) -> UnifyT Type Check ([Declaration], Value)
576+inferLetBinding seen [] ret j = (,) seen <$> j ret
577+inferLetBinding seen (ValueDeclaration ident nameKind [] Nothing val : rest) ret j = do
579+ Just moduleName <- checkCurrentModule <$> get
580+ TypedValue _ val' valTy' <- bindNames (M.singleton (moduleName, ident) (valTy, nameKind)) $ infer val
582+ bindNames (M.singleton (moduleName, ident) (valTy', nameKind)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] Nothing val']) rest ret j
583+inferLetBinding seen (BindingGroupDeclaration ds : rest) ret j = do
584+ Just moduleName <- checkCurrentModule <$> get
585+ (es, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName (map (\(i, _, v) -> (i, v)) ds)
586+ ds' <- forM es $ \e -> do
587+ (ident, (val', _)) <- typeForBindingGroupElement moduleName e dict untypedDict
588+ return $ (ident, LocalVariable, val')
589+ bindNames dict $ inferLetBinding (seen ++ [BindingGroupDeclaration ds']) rest ret j
590+inferLetBinding _ _ _ _ = error "Invalid argument to fromValueDeclaration"
593+-- Infer the type of a property inside a record with a given type
595+inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
596+inferProperty (Object row) prop = do
597+ let (props, _) = rowToList row
598+ return $ lookup prop props
599+inferProperty (SaturatedTypeSynonym name args) prop = do
600+ replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
601+ inferProperty replaced prop
602+inferProperty (ForAll ident ty _) prop = do
603+ replaced <- replaceVarWithUnknown ident ty
604+ inferProperty replaced prop
605+inferProperty _ _ = return Nothing
608+-- Infer the types of variables brought into scope by a binder
610+inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
611+inferBinder _ NullBinder = return M.empty
612+inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
613+inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
614+inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
615+inferBinder val (VarBinder name) = return $ M.singleton name val
616+inferBinder val (ConstructorBinder ctor binders) = do
618+ case M.lookup ctor (dataConstructors env) of
620+ (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contain constraints") ty
621+ fn' <- replaceAllTypeSynonyms fn
625+ _ <- subsumes Nothing val ty'
627+ go (binder : binders') (TypeApp (TypeApp t obj) ret) | t == tyFunction =
628+ M.union <$> inferBinder obj binder <*> go binders' ret
629+ go _ _ = throwError $ "Wrong number of arguments to constructor " ++ show ctor
630+ _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
631+inferBinder val (ObjectBinder props) = do
634+ m1 <- inferRowProperties row rest props
638+ inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
639+ inferRowProperties nrow row [] = nrow =?= row >> return M.empty
640+ inferRowProperties nrow row ((name, binder):binders) = do
642+ m1 <- inferBinder propTy binder
643+ m2 <- inferRowProperties nrow (RCons name propTy row) binders
644+ return $ m1 `M.union` m2
645+inferBinder val (ArrayBinder binders) = do
647+ m1 <- M.unions <$> mapM (inferBinder el) binders
648+ val =?= TypeApp tyArray el
650+inferBinder val (ConsBinder headBinder tailBinder) = do
652+ m1 <- inferBinder el headBinder
653+ m2 <- inferBinder val tailBinder
654+ val =?= TypeApp tyArray el
655+ return $ m1 `M.union` m2
656+inferBinder val (NamedBinder name binder) = do
657+ m <- inferBinder val binder
658+ return $ M.insert name val m
661+-- Check the types of the return values in a set of binders in a case statement
663+checkBinders :: [Type] -> Type -> [CaseAlternative] -> UnifyT Type Check [CaseAlternative]
664+checkBinders _ _ [] = return []
665+checkBinders nvals ret (CaseAlternative binders grd val : bs) = do
666+ Just moduleName <- checkCurrentModule <$> get
667+ m1 <- M.unions <$> zipWithM inferBinder nvals binders
668+ r <- bindLocalVariables moduleName (M.toList m1) $ do
669+ val' <- TypedValue True <$> check val ret <*> pure ret
671+ Nothing -> return $ CaseAlternative binders Nothing val'
673+ g' <- check g tyBoolean
674+ return $ CaseAlternative binders (Just g') val'
675+ rs <- checkBinders nvals ret bs
679+-- Generate a new skolem constant
681+newSkolemConstant :: UnifyT Type Check Int
682+newSkolemConstant = runUnknown <$> fresh'
685+-- Generate a new skolem scope
687+newSkolemScope :: UnifyT Type Check SkolemScope
688+newSkolemScope = SkolemScope . runUnknown <$> fresh'
691+-- Skolemize a type variable by replacing its instances with fresh skolem constants
693+skolemize :: String -> Int -> SkolemScope -> Type -> Type
694+skolemize ident sko scope = replaceTypeVars ident (Skolem sko scope)
697+-- Introduce skolem scope at every occurence of a ForAll
699+introduceSkolemScope :: Type -> UnifyT Type Check Type
700+introduceSkolemScope = everywhereM (mkM go)
702+ go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
703+ go other = return other
706+-- Check the type of a value, rethrowing errors to provide a better error message
708+check :: Value -> Type -> UnifyT Type Check Value
709+check val ty = rethrow errorMessage $ check' val ty
712+ "Error checking type of term " ++
713+ prettyPrintValue val ++
715+ prettyPrintType ty ++
720+-- Check the type of a value
722+check' :: Value -> Type -> UnifyT Type Check Value
723+check' val (ForAll ident ty _) = do
724+ scope <- newSkolemScope
725+ sko <- newSkolemConstant
726+ let sk = skolemize ident sko scope ty
727+ val' <- check val sk
728+ return $ TypedValue True val' (ForAll ident ty (Just scope))
729+check' val t@(ConstrainedType constraints ty) = do
730+ dictNames <- forM constraints $ \(Qualified _ (ProperName className), _) -> do
731+ n <- liftCheck freshDictionaryName
732+ return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
733+ val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
734+ TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
735+ constraints) $ check val ty
736+ return $ TypedValue True (foldr (Abs . Left) val' dictNames) t
737+check' val (SaturatedTypeSynonym name args) = do
738+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
739+ val' <- check val ty
740+ return $ TypedValue True val' ty
741+check' val u@(TUnknown _) = do
742+ val'@(TypedValue _ _ ty) <- infer val
743+ -- Don't unify an unknown with an inferred polytype
744+ (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
746+ return $ TypedValue True val'' ty'
747+check' v@(NumericLiteral _) t | t == tyNumber =
748+ return $ TypedValue True v t
749+check' v@(StringLiteral _) t | t == tyString =
750+ return $ TypedValue True v t
751+check' v@(BooleanLiteral _) t | t == tyBoolean =
752+ return $ TypedValue True v t
753+check' (ArrayLiteral vals) t@(TypeApp a ty) = do
755+ array <- ArrayLiteral <$> forM vals (`check` ty)
756+ return $ TypedValue True array t
757+check' (Abs (Left arg) ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
758+ Just moduleName <- checkCurrentModule <$> get
759+ ret' <- bindLocalVariables moduleName [(arg, argTy)] $ check ret retTy
760+ return $ TypedValue True (Abs (Left arg) ret') ty
761+check' (Abs (Right _) _) _ = error "Binder was not desugared"
762+check' (App f arg) ret = do
763+ f'@(TypedValue _ _ ft) <- infer f
764+ (_, app) <- checkFunctionApplication f' ft arg (Just ret)
765+ return $ TypedValue True app ret
766+check' v@(Var var) ty = do
767+ Just moduleName <- checkCurrentModule <$> get
768+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
769+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
770+ v' <- subsumes (Just v) repl ty'
772+ Nothing -> throwError "Unable to check type subsumption"
773+ Just v'' -> return $ TypedValue True v'' ty'
774+check' (TypedValue checkType val ty1) ty2 = do
775+ Just moduleName <- checkCurrentModule <$> get
776+ kind <- liftCheck $ kindOf moduleName ty1
777+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
778+ ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
779+ val' <- subsumes (Just val) ty1' ty2
781+ Nothing -> throwError "Unable to check type subsumption"
783+ val''' <- if checkType then check val'' ty1' else return val''
784+ return $ TypedValue checkType (TypedValue True val''' ty1) ty2
785+check' (Case vals binders) ret = do
786+ vals' <- mapM infer vals
787+ let ts = map (\(TypedValue _ _ t) -> t) vals'
788+ binders' <- checkBinders ts ret binders
789+ return $ TypedValue True (Case vals' binders') ret
790+check' (IfThenElse cond th el) ty = do
791+ cond' <- check cond tyBoolean
794+ return $ TypedValue True (IfThenElse cond' th' el') ty
795+check' (ObjectLiteral ps) t@(Object row) = do
796+ ensureNoDuplicateProperties ps
797+ ps' <- checkProperties ps row False
798+ return $ TypedValue True (ObjectLiteral ps') t
799+check' (ObjectUpdate obj ps) t@(Object row) = do
800+ ensureNoDuplicateProperties ps
801+ us <- zip (map fst ps) <$> replicateM (length ps) fresh
802+ let (propsToCheck, rest) = rowToList row
803+ propsToRemove = map fst ps
804+ remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
805+ obj' <- check obj (Object (rowFromList (us ++ remainingProps, rest)))
806+ ps' <- checkProperties ps row True
807+ return $ TypedValue True (ObjectUpdate obj' ps') t
808+check' (Accessor prop val) ty = do
810+ val' <- check val (Object (RCons prop ty rest))
811+ return $ TypedValue True (Accessor prop val') ty
812+check' (Constructor c) ty = do
814+ case M.lookup c (dataConstructors env) of
815+ Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
817+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
818+ _ <- subsumes Nothing repl ty
819+ return $ TypedValue True (Constructor c) ty
820+check' (Let ds val) ty = do
821+ (ds', val') <- inferLetBinding [] ds val (flip check ty)
822+ return $ TypedValue True (Let ds' val') ty
823+check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
826+-- Check the type of a collection of named record fields
828+-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
830+checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Type Check [(String, Value)]
831+checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
832+ go [] [] REmpty = return []
833+ go [] [] u@(TUnknown _) = do u =?= REmpty
835+ go [] [] (Skolem _ _) | lax = return []
836+ go [] ((p, _): _) _ | lax = return []
837+ | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
838+ go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
839+ go ((p,v):ps') [] u@(TUnknown _) = do
840+ v'@(TypedValue _ _ ty) <- infer v
842+ u =?= RCons p ty rest
843+ ps'' <- go ps' [] rest
844+ return $ (p, v') : ps''
845+ go ((p,v):ps') ts r =
848+ v'@(TypedValue _ _ ty) <- infer v
850+ r =?= RCons p ty rest
851+ ps'' <- go ps' ts rest
852+ return $ (p, v') : ps''
855+ ps'' <- go ps' (delete (p, ty) ts) r
856+ return $ (p, v') : ps''
857+ go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
860+-- Check the type of a function application, rethrowing errors to provide a better error message
862+checkFunctionApplication :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
863+checkFunctionApplication fn fnTy arg ret = rethrow errorMessage $ checkFunctionApplication' fn fnTy arg ret
865+ errorMessage msg = "Error applying function of type "
866+ ++ prettyPrintType fnTy
867+ ++ " to argument " ++ prettyPrintValue arg
871+-- Check the type of a function application
873+checkFunctionApplication' :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
874+checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg ret = do
875+ tyFunction' =?= tyFunction
876+ _ <- maybe (return Nothing) (subsumes Nothing retTy) ret
877+ subst <- unifyCurrentSubstitution <$> UnifyT get
878+ arg' <- check arg (subst $? argTy)
879+ return (retTy, App fn arg')
880+checkFunctionApplication' fn (ForAll ident ty _) arg ret = do
881+ replaced <- replaceVarWithUnknown ident ty
882+ checkFunctionApplication fn replaced arg ret
883+checkFunctionApplication' fn u@(TUnknown _) arg ret = do
885+ TypedValue _ arg' t <- infer arg
886+ (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
887+ return $ TypedValue True arg'' t'
888+ let ty = (\(TypedValue _ _ t) -> t) arg'
889+ ret' <- maybe fresh return ret
890+ u =?= function ty ret'
891+ return (ret', App fn arg')
892+checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
893+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
894+ checkFunctionApplication fn ty arg ret
895+checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
896+ dicts <- getTypeClassDictionaries
897+ checkFunctionApplication' (foldl App fn (map (flip TypeClassDictionary dicts) constraints)) fnTy arg ret
898+checkFunctionApplication' _ fnTy arg _ = throwError $ "Cannot apply a function of type "
899+ ++ prettyPrintType fnTy
900+ ++ " to argument " ++ prettyPrintValue arg
903+-- Check whether one type subsumes another, rethrowing errors to provide a better error message
905+subsumes :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
906+subsumes val ty1 ty2 = rethrow errorMessage $ subsumes' val ty1 ty2
908+ errorMessage msg = "Error checking that type "
909+ ++ prettyPrintType ty1
910+ ++ " subsumes type "
911+ ++ prettyPrintType ty2
915+-- Check whether one type subsumes another
917+subsumes' :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
918+subsumes' val (ForAll ident ty1 _) ty2 = do
919+ replaced <- replaceVarWithUnknown ident ty1
920+ subsumes val replaced ty2
921+subsumes' val ty1 (ForAll ident ty2 sco) =
924+ sko <- newSkolemConstant
925+ let sk = skolemize ident sko sco' ty2
927+ Nothing -> throwError "Skolem variable scope is unspecified"
928+subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
929+ _ <- subsumes Nothing arg2 arg1
930+ _ <- subsumes Nothing ret1 ret2
932+subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
933+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
934+ subsumes val ty1 ty2
935+subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
936+ ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
937+ subsumes val ty1 ty2
938+subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
939+ dicts <- getTypeClassDictionaries
940+ _ <- subsumes' Nothing ty1 ty2
941+ return . Just $ foldl App val (map (flip TypeClassDictionary dicts) constraints)
942+subsumes' val (Object r1) (Object r2) = do
944+ (ts1, r1') = rowToList r1
945+ (ts2, r2') = rowToList r2
946+ ts1' = sortBy (comparing fst) ts1
947+ ts2' = sortBy (comparing fst) ts2
948+ go ts1' ts2' r1' r2'
951+ go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
952+ go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
953+ go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
954+ | p1 == p2 = do _ <- subsumes Nothing ty1 ty2
956+ | p1 < p2 = do rest <- fresh
957+ r2' =?= RCons p1 ty1 rest
958+ go ts1 ((p2, ty2) : ts2) r1' rest
959+ | otherwise = do rest <- fresh
960+ r1' =?= RCons p2 ty2 rest
961+ go ((p1, ty1) : ts1) ts2 rest r2'
962+subsumes' val ty1 ty2@(Object _) = subsumes val ty2 ty1
963+subsumes' val ty1 ty2 = do