@@ -1,981 +0,0 @@
1−-----------------------------------------------------------------------------
3−-- Module : Language.PureScript.TypeChecker.Types
4−-- Copyright : (c) Phil Freeman 2013
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
12−-- This module implements the type checker
14−-----------------------------------------------------------------------------
16−{-# OPTIONS_GHC -fno-warn-orphans #-}
17−{-# LANGUAGE FlexibleInstances #-}
18−{-# LANGUAGE FlexibleContexts #-}
19−{-# LANGUAGE MultiParamTypeClasses #-}
21−module Language.PureScript.TypeChecker.Types (
26− The following functions represent the corresponding type checking judgements:
29− Synthesize a type for a value
32− Check a value has a given type
35− Check an object with a given type contains specified properties
37− checkFunctionApplication
38− Check a function of a given type returns a value of another type when applied to its arguments
41− Check a type subsumes another type
45−import Data.Maybe (maybeToList, isNothing, isJust, fromMaybe)
46−import qualified Data.Data as D
48− (everythingWithContext, mkM, everywhereM, everything, mkT,
49− something, everywhere, mkQ)
50−import Data.Generics.Extras
52−import Language.PureScript.Declarations
53−import Language.PureScript.Types
54−import Language.PureScript.Kinds
55−import Language.PureScript.Names
56−import Language.PureScript.TypeClassDictionaries
57−import Language.PureScript.TypeChecker.Monad
58−import Language.PureScript.TypeChecker.Kinds
59−import Language.PureScript.TypeChecker.Synonyms
60−import Language.PureScript.Pretty
61−import Language.PureScript.Environment
62−import 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 Data.Function (on)
73−import Data.Ord (comparing)
74−import Data.Monoid ((<>))
76−instance Partial Type where
78− isUnknown (TUnknown u) = Just u
79− isUnknown _ = Nothing
81−instance Unifiable Check Type where
85−-- Unify two types, updating the current substitution
87−unifyTypes :: Type -> Type -> UnifyT Type Check ()
88−unifyTypes t1 t2 = rethrow (mkUnifyErrorStack ("Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2) Nothing <>) $
91− unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
92− unifyTypes' (TUnknown u) t = u =:= t
93− unifyTypes' t (TUnknown u) = u =:= t
94− unifyTypes' (SaturatedTypeSynonym name args) ty = do
95− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ args
97− unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
98− unifyTypes' (ForAll ident1 ty1 sc1) (ForAll ident2 ty2 sc2) =
100− (Just sc1', Just sc2') -> do
101− sko <- newSkolemConstant
102− let sk1 = skolemize ident1 sko sc1' ty1
103− let sk2 = skolemize ident2 sko sc2' ty2
104− sk1 `unifyTypes` sk2
105− _ -> error "Skolemized type variable was not given a scope"
106− unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
107− sko <- newSkolemConstant
108− let sk = skolemize ident sko sc ty1
110− unifyTypes' ForAll{} _ = throwError . strMsg $ "Skolem variable scope is unspecified"
111− unifyTypes' ty f@ForAll{} = f `unifyTypes` ty
112− unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
113− unifyTypes' (TypeConstructor c1) (TypeConstructor c2) =
114− guardWith (strMsg ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".")) (c1 == c2)
115− unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
118− unifyTypes' (Skolem s1 _) (Skolem s2 _) | s1 == s2 = return ()
119− unifyTypes' r1@RCons{} r2 = unifyRows r1 r2
120− unifyTypes' r1 r2@RCons{} = unifyRows r1 r2
121− unifyTypes' r1@REmpty r2 = unifyRows r1 r2
122− unifyTypes' r1 r2@REmpty = unifyRows r1 r2
123− unifyTypes' t@(ConstrainedType _ _) _ = throwError . strMsg $ "Attempted to unify a constrained type " ++ prettyPrintType t ++ " with another type."
124− unifyTypes' t3 t4@(ConstrainedType _ _) = unifyTypes' t4 t3
125− unifyTypes' t3 t4 = throwError . strMsg $ "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 . strMsg $ "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 (strMsg $ "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 . strMsg $ "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 $ mkUnifyErrorStack ("Rigid/skolem type variable " ++ maybe "" (("bound by " ++) . prettyPrintValue) binding ++ " has escaped.") (Just (ValueError 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 $ mkUnifyErrorStack "Untyped value passed to skolemEscapeCheck" (Just (ValueError 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 :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => (D.Data d) => d -> m d
449−replaceAllTypeSynonyms d = do
451− either (throwError . strMsg) 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 :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Qualified ProperName -> [Type] -> m Type
474−expandTypeSynonym name args = do
476− either (throwError . strMsg) return $ expandTypeSynonym' env name args
478−expandAllTypeSynonyms :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
479−expandAllTypeSynonyms = everywhereM' (mkM go)
481− go (SaturatedTypeSynonym name args) = expandTypeSynonym name args
482− go other = return other
485−-- Ensure a set of property names and value does not contain duplicate labels
487−ensureNoDuplicateProperties :: (Error e, MonadError e m) => [(String, Value)] -> m ()
488−ensureNoDuplicateProperties ps = guardWith (strMsg "Duplicate property names") $ length (nub . map fst $ ps) == length ps
491−-- Infer a type for a value, rethrowing any error to provide a more useful error message
493−infer :: Value -> UnifyT Type Check Value
494−infer val = rethrow (mkUnifyErrorStack "Error inferring type of value" (Just (ValueError val)) <>) $ infer' val
497−-- Infer a type for a value
499−infer' :: Value -> UnifyT Type Check Value
500−infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
501−infer' v@(StringLiteral _) = return $ TypedValue True v tyString
502−infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
503−infer' (ArrayLiteral vals) = do
504− ts <- mapM infer vals
506− forM_ ts $ \(TypedValue _ _ t) -> els =?= TypeApp tyArray t
507− return $ TypedValue True (ArrayLiteral ts) els
508−infer' (ObjectLiteral ps) = do
509− ensureNoDuplicateProperties ps
510− ts <- mapM (infer . snd) ps
511− let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
512− ty = TypeApp tyObject $ rowFromList (fields, REmpty)
513− return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
514−infer' (ObjectUpdate o ps) = do
515− ensureNoDuplicateProperties ps
517− newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
518− let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
519− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
520− let oldTy = TypeApp tyObject $ rowFromList (oldTys, row)
521− o' <- TypedValue True <$> check o oldTy <*> pure oldTy
522− return $ TypedValue True (ObjectUpdate o' newVals) $ TypeApp tyObject $ rowFromList (newTys, row)
523−infer' (Accessor prop val) = do
524− typed@(TypedValue _ _ objTy) <- infer val
525− propTy <- inferProperty objTy prop
530− _ <- subsumes Nothing objTy (TypeApp tyObject (RCons prop field rest))
531− return $ TypedValue True (Accessor prop typed) field
532− Just ty -> return $ TypedValue True (Accessor prop typed) ty
533−infer' (Abs (Left arg) ret) = do
535− Just moduleName <- checkCurrentModule <$> get
536− bindLocalVariables moduleName [(arg, ty)] $ do
537− body@(TypedValue _ _ bodyTy) <- infer' ret
538− return $ TypedValue True (Abs (Left arg) body) $ function ty bodyTy
539−infer' (Abs (Right _) _) = error "Binder was not desugared"
540−infer' (App f arg) = do
541− f'@(TypedValue _ _ ft) <- infer f
542− (ret, app) <- checkFunctionApplication f' ft arg Nothing
543− return $ TypedValue True app ret
544−infer' (Var var) = do
545− Just moduleName <- checkCurrentModule <$> get
546− ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
548− ConstrainedType constraints ty' -> do
549− dicts <- getTypeClassDictionaries
550− return $ TypedValue True (foldl App (Var var) (map (flip TypeClassDictionary dicts) constraints)) ty'
551− _ -> return $ TypedValue True (Var var) ty
552−infer' v@(Constructor c) = do
554− case M.lookup c (dataConstructors env) of
555− Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
556− Just (_, ty) -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
557− return $ TypedValue True v ty'
558−infer' (Case vals binders) = do
559− ts <- mapM infer vals
561− binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
562− return $ TypedValue True (Case ts binders') ret
563−infer' (IfThenElse cond th el) = do
564− cond' <- check cond tyBoolean
565− v2@(TypedValue _ _ t2) <- infer th
566− v3@(TypedValue _ _ t3) <- infer el
568− return $ TypedValue True (IfThenElse cond' v2 v3) t2
569−infer' (Let ds val) = do
570− (ds', val'@(TypedValue _ _ valTy)) <- inferLetBinding [] ds val infer
571− return $ TypedValue True (Let ds' val') valTy
572−infer' (TypedValue checkType val ty) = do
573− Just moduleName <- checkCurrentModule <$> get
574− kind <- liftCheck $ kindOf moduleName ty
575− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
576− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
577− val' <- if checkType then check val ty' else return val
578− return $ TypedValue True val' ty'
579−infer' (PositionedValue pos val) = rethrowWithPosition pos $ infer' val
580−infer' _ = error "Invalid argument to infer"
582−inferLetBinding :: [Declaration] -> [Declaration] -> Value -> (Value -> UnifyT Type Check Value) -> UnifyT Type Check ([Declaration], Value)
583−inferLetBinding seen [] ret j = (,) seen <$> j ret
584−inferLetBinding seen (ValueDeclaration ident nameKind [] Nothing val : rest) ret j = do
586− Just moduleName <- checkCurrentModule <$> get
587− TypedValue _ val' valTy' <- bindNames (M.singleton (moduleName, ident) (valTy, nameKind)) $ infer val
589− bindNames (M.singleton (moduleName, ident) (valTy', nameKind)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] Nothing val']) rest ret j
590−inferLetBinding seen (BindingGroupDeclaration ds : rest) ret j = do
591− Just moduleName <- checkCurrentModule <$> get
592− (es, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName (map (\(i, _, v) -> (i, v)) ds)
593− ds' <- forM es $ \e -> do
594− (ident, (val', _)) <- typeForBindingGroupElement moduleName e dict untypedDict
595− return $ (ident, LocalVariable, val')
596− bindNames dict $ inferLetBinding (seen ++ [BindingGroupDeclaration ds']) rest ret j
597−inferLetBinding _ _ _ _ = error "Invalid argument to fromValueDeclaration"
600−-- Infer the type of a property inside a record with a given type
602−inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
603−inferProperty (TypeApp obj row) prop | obj == tyObject = do
604− let (props, _) = rowToList row
605− return $ lookup prop props
606−inferProperty (SaturatedTypeSynonym name args) prop = do
607− replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
608− inferProperty replaced prop
609−inferProperty (ForAll ident ty _) prop = do
610− replaced <- replaceVarWithUnknown ident ty
611− inferProperty replaced prop
612−inferProperty _ _ = return Nothing
615−-- Infer the types of variables brought into scope by a binder
617−inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
618−inferBinder _ NullBinder = return M.empty
619−inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
620−inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
621−inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
622−inferBinder val (VarBinder name) = return $ M.singleton name val
623−inferBinder val (ConstructorBinder ctor binders) = do
625− case M.lookup ctor (dataConstructors env) of
627− (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contain constraints") ty
628− fn' <- replaceAllTypeSynonyms fn
632− _ <- subsumes Nothing val ty'
634− go (binder : binders') (TypeApp (TypeApp t obj) ret) | t == tyFunction =
635− M.union <$> inferBinder obj binder <*> go binders' ret
636− go _ _ = throwError . strMsg $ "Wrong number of arguments to constructor " ++ show ctor
637− _ -> throwError . strMsg $ "Constructor " ++ show ctor ++ " is not defined"
638−inferBinder val (ObjectBinder props) = do
641− m1 <- inferRowProperties row rest props
642− val =?= TypeApp tyObject row
645− inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
646− inferRowProperties nrow row [] = nrow =?= row >> return M.empty
647− inferRowProperties nrow row ((name, binder):binders) = do
649− m1 <- inferBinder propTy binder
650− m2 <- inferRowProperties nrow (RCons name propTy row) binders
651− return $ m1 `M.union` m2
652−inferBinder val (ArrayBinder binders) = do
654− m1 <- M.unions <$> mapM (inferBinder el) binders
655− val =?= TypeApp tyArray el
657−inferBinder val (ConsBinder headBinder tailBinder) = do
659− m1 <- inferBinder el headBinder
660− m2 <- inferBinder val tailBinder
661− val =?= TypeApp tyArray el
662− return $ m1 `M.union` m2
663−inferBinder val (NamedBinder name binder) = do
664− m <- inferBinder val binder
665− return $ M.insert name val m
666−inferBinder val (PositionedBinder pos binder) =
667− rethrowWithPosition pos $ inferBinder val binder
670−-- Check the types of the return values in a set of binders in a case statement
672−checkBinders :: [Type] -> Type -> [CaseAlternative] -> UnifyT Type Check [CaseAlternative]
673−checkBinders _ _ [] = return []
674−checkBinders nvals ret (CaseAlternative binders grd val : bs) = do
675− Just moduleName <- checkCurrentModule <$> get
676− m1 <- M.unions <$> zipWithM inferBinder nvals binders
677− r <- bindLocalVariables moduleName (M.toList m1) $ do
678− val' <- TypedValue True <$> check val ret <*> pure ret
680− Nothing -> return $ CaseAlternative binders Nothing val'
682− g' <- check g tyBoolean
683− return $ CaseAlternative binders (Just g') val'
684− rs <- checkBinders nvals ret bs
688−-- Generate a new skolem constant
690−newSkolemConstant :: UnifyT Type Check Int
691−newSkolemConstant = runUnknown <$> fresh'
694−-- Generate a new skolem scope
696−newSkolemScope :: UnifyT Type Check SkolemScope
697−newSkolemScope = SkolemScope . runUnknown <$> fresh'
700−-- Skolemize a type variable by replacing its instances with fresh skolem constants
702−skolemize :: String -> Int -> SkolemScope -> Type -> Type
703−skolemize ident sko scope = replaceTypeVars ident (Skolem sko scope)
706−-- Introduce skolem scope at every occurence of a ForAll
708−introduceSkolemScope :: Type -> UnifyT Type Check Type
709−introduceSkolemScope = everywhereM (mkM go)
711− go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
712− go other = return other
715−-- Check the type of a value, rethrowing errors to provide a better error message
717−check :: Value -> Type -> UnifyT Type Check Value
718−check val ty = rethrow (mkUnifyErrorStack errorMessage (Just (ValueError val)) <>) $ check' val ty
721− "Error checking type of term " ++
722− prettyPrintValue val ++
727−-- Check the type of a value
729−check' :: Value -> Type -> UnifyT Type Check Value
730−check' val (ForAll ident ty _) = do
731− scope <- newSkolemScope
732− sko <- newSkolemConstant
733− let sk = skolemize ident sko scope ty
734− val' <- check val sk
735− return $ TypedValue True val' (ForAll ident ty (Just scope))
736−check' val t@(ConstrainedType constraints ty) = do
737− dictNames <- forM constraints $ \(Qualified _ (ProperName className), _) -> do
738− n <- liftCheck freshDictionaryName
739− return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
740− val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
741− TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
742− constraints) $ check val ty
743− return $ TypedValue True (foldr (Abs . Left) val' dictNames) t
744−check' val (SaturatedTypeSynonym name args) = do
745− ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
747−check' val u@(TUnknown _) = do
748− val'@(TypedValue _ _ ty) <- infer val
749− -- Don't unify an unknown with an inferred polytype
750− (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
752− return $ TypedValue True val'' ty'
753−check' v@(NumericLiteral _) t | t == tyNumber =
754− return $ TypedValue True v t
755−check' v@(StringLiteral _) t | t == tyString =
756− return $ TypedValue True v t
757−check' v@(BooleanLiteral _) t | t == tyBoolean =
758− return $ TypedValue True v t
759−check' (ArrayLiteral vals) t@(TypeApp a ty) = do
761− array <- ArrayLiteral <$> forM vals (`check` ty)
762− return $ TypedValue True array t
763−check' (Abs (Left arg) ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
764− Just moduleName <- checkCurrentModule <$> get
765− ret' <- bindLocalVariables moduleName [(arg, argTy)] $ check ret retTy
766− return $ TypedValue True (Abs (Left arg) ret') ty
767−check' (Abs (Right _) _) _ = error "Binder was not desugared"
768−check' (App f arg) ret = do
769− f'@(TypedValue _ _ ft) <- infer f
770− (_, app) <- checkFunctionApplication f' ft arg (Just ret)
771− return $ TypedValue True app ret
772−check' v@(Var var) ty = do
773− Just moduleName <- checkCurrentModule <$> get
774− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
775− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
776− v' <- subsumes (Just v) repl ty'
778− Nothing -> throwError . strMsg $ "Unable to check type subsumption"
779− Just v'' -> return $ TypedValue True v'' ty'
780−check' (TypedValue checkType val ty1) ty2 = do
781− Just moduleName <- checkCurrentModule <$> get
782− kind <- liftCheck $ kindOf moduleName ty1
783− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
784− ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
785− val' <- subsumes (Just val) ty1' ty2
787− Nothing -> throwError . strMsg $ "Unable to check type subsumption"
789− val''' <- if checkType then check val'' ty1' else return val''
790− return $ TypedValue checkType (TypedValue True val''' ty1) ty2
791−check' (Case vals binders) ret = do
792− vals' <- mapM infer vals
793− let ts = map (\(TypedValue _ _ t) -> t) vals'
794− binders' <- checkBinders ts ret binders
795− return $ TypedValue True (Case vals' binders') ret
796−check' (IfThenElse cond th el) ty = do
797− cond' <- check cond tyBoolean
800− return $ TypedValue True (IfThenElse cond' th' el') ty
801−check' (ObjectLiteral ps) t@(TypeApp obj row) | obj == tyObject = do
802− ensureNoDuplicateProperties ps
803− ps' <- checkProperties ps row False
804− return $ TypedValue True (ObjectLiteral ps') t
805−check' (ObjectUpdate obj ps) t@(TypeApp o row) | o == tyObject = do
806− ensureNoDuplicateProperties ps
807− us <- zip (map fst ps) <$> replicateM (length ps) fresh
808− let (propsToCheck, rest) = rowToList row
809− propsToRemove = map fst ps
810− remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
811− obj' <- check obj (TypeApp tyObject (rowFromList (us ++ remainingProps, rest)))
812− ps' <- checkProperties ps row True
813− return $ TypedValue True (ObjectUpdate obj' ps') t
814−check' (Accessor prop val) ty = do
816− val' <- check val (TypeApp tyObject (RCons prop ty rest))
817− return $ TypedValue True (Accessor prop val') ty
818−check' (Constructor c) ty = do
820− case M.lookup c (dataConstructors env) of
821− Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
823− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
824− _ <- subsumes Nothing repl ty
825− return $ TypedValue True (Constructor c) ty
826−check' (Let ds val) ty = do
827− (ds', val') <- inferLetBinding [] ds val (flip check ty)
828− return $ TypedValue True (Let ds' val') ty
829−check' val ty | containsTypeSynonyms ty = do
830− ty' <- introduceSkolemScope <=< expandAllTypeSynonyms $ ty
832−check' (PositionedValue pos val) ty =
833− rethrowWithPosition pos $ check val ty
834−check' val ty = throwError $ mkUnifyErrorStack ("Value does not have type " ++ prettyPrintType ty) (Just (ValueError val))
836−containsTypeSynonyms :: Type -> Bool
837−containsTypeSynonyms = everything (||) (mkQ False go) where
838− go (SaturatedTypeSynonym _ _) = True
842−-- Check the type of a collection of named record fields
844−-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
846−checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Type Check [(String, Value)]
847−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
848− go [] [] REmpty = return []
849− go [] [] u@(TUnknown _) = do u =?= REmpty
851− go [] [] (Skolem _ _) | lax = return []
852− go [] ((p, _): _) _ | lax = return []
853− | otherwise = throwError $ mkUnifyErrorStack ("Object does not have property " ++ p) (Just (ValueError (ObjectLiteral ps)))
854− go ((p,_):_) [] REmpty = throwError $ mkUnifyErrorStack ("Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row) (Just (ValueError (ObjectLiteral ps)))
855− go ((p,v):ps') [] u@(TUnknown _) = do
856− v'@(TypedValue _ _ ty) <- infer v
858− u =?= RCons p ty rest
859− ps'' <- go ps' [] rest
860− return $ (p, v') : ps''
861− go ((p,v):ps') ts r =
864− v'@(TypedValue _ _ ty) <- infer v
866− r =?= RCons p ty rest
867− ps'' <- go ps' ts rest
868− return $ (p, v') : ps''
871− ps'' <- go ps' (delete (p, ty) ts) r
872− return $ (p, v') : ps''
873− go _ _ _ = throwError $ mkUnifyErrorStack ("Object does not have type " ++ prettyPrintType (TypeApp tyObject row)) (Just (ValueError (ObjectLiteral ps)))
876−-- Check the type of a function application, rethrowing errors to provide a better error message
878−checkFunctionApplication :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
879−checkFunctionApplication fn fnTy arg ret = rethrow (mkUnifyErrorStack errorMessage (Just (ValueError fn)) <>) $ checkFunctionApplication' fn fnTy arg ret
881− errorMessage = "Error applying function of type "
882− ++ prettyPrintType fnTy
883− ++ " to argument " ++ prettyPrintValue arg
886−-- Check the type of a function application
888−checkFunctionApplication' :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
889−checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg ret = do
890− tyFunction' =?= tyFunction
891− _ <- maybe (return Nothing) (subsumes Nothing retTy) ret
892− subst <- unifyCurrentSubstitution <$> UnifyT get
893− arg' <- check arg (subst $? argTy)
894− return (retTy, App fn arg')
895−checkFunctionApplication' fn (ForAll ident ty _) arg ret = do
896− replaced <- replaceVarWithUnknown ident ty
897− checkFunctionApplication fn replaced arg ret
898−checkFunctionApplication' fn u@(TUnknown _) arg ret = do
900− TypedValue _ arg' t <- infer arg
901− (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
902− return $ TypedValue True arg'' t'
903− let ty = (\(TypedValue _ _ t) -> t) arg'
904− ret' <- maybe fresh return ret
905− u =?= function ty ret'
906− return (ret', App fn arg')
907−checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
908− ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
909− checkFunctionApplication fn ty arg ret
910−checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
911− dicts <- getTypeClassDictionaries
912− checkFunctionApplication' (foldl App fn (map (flip TypeClassDictionary dicts) constraints)) fnTy arg ret
913−checkFunctionApplication' _ fnTy arg _ = throwError . strMsg $ "Cannot apply a function of type "
914− ++ prettyPrintType fnTy
915− ++ " to argument " ++ prettyPrintValue arg
918−-- Check whether one type subsumes another, rethrowing errors to provide a better error message
920−subsumes :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
921−subsumes val ty1 ty2 = rethrow (mkUnifyErrorStack errorMessage (ValueError <$> val) <>) $ subsumes' val ty1 ty2
923− errorMessage = "Error checking that type "
924− ++ prettyPrintType ty1
925− ++ " subsumes type "
926− ++ prettyPrintType ty2
929−-- Check whether one type subsumes another
931−subsumes' :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
932−subsumes' val (ForAll ident ty1 _) ty2 = do
933− replaced <- replaceVarWithUnknown ident ty1
934− subsumes val replaced ty2
935−subsumes' val ty1 (ForAll ident ty2 sco) =
938− sko <- newSkolemConstant
939− let sk = skolemize ident sko sco' ty2
941− Nothing -> throwError . strMsg $ "Skolem variable scope is unspecified"
942−subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
943− _ <- subsumes Nothing arg2 arg1
944− _ <- subsumes Nothing ret1 ret2
946−subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
947− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
948− subsumes val ty1 ty2
949−subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
950− ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
951− subsumes val ty1 ty2
952−subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
953− dicts <- getTypeClassDictionaries
954− _ <- subsumes' Nothing ty1 ty2
955− return . Just $ foldl App val (map (flip TypeClassDictionary dicts) constraints)
956−subsumes' val (TypeApp f1 r1) (TypeApp f2 r2) | f1 == tyObject && f2 == tyObject = do
958− (ts1, r1') = rowToList r1
959− (ts2, r2') = rowToList r2
960− ts1' = sortBy (comparing fst) ts1
961− ts2' = sortBy (comparing fst) ts2
962− go ts1' ts2' r1' r2'
965− go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
966− go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
967− go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
968− | p1 == p2 = do _ <- subsumes Nothing ty1 ty2
970− | p1 < p2 = do rest <- fresh
971− r2' =?= RCons p1 ty1 rest
972− go ts1 ((p2, ty2) : ts2) r1' rest
973− | otherwise = do rest <- fresh
974− r1' =?= RCons p2 ty2 rest
975− go ((p1, ty1) : ts1) ts2 rest r2'
976−subsumes' val ty1 ty2@(TypeApp obj _) | obj == tyObject = subsumes val ty2 ty1
977−subsumes' val ty1 ty2 = do