@@ -1,960 +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 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.Values
52−import Language.PureScript.Types
53−import Language.PureScript.Kinds
54−import Language.PureScript.Names
55−import Language.PureScript.TypeChecker.Monad
56−import Language.PureScript.TypeChecker.Kinds
57−import Language.PureScript.TypeChecker.Synonyms
58−import Language.PureScript.Pretty
60−import Control.Monad.State
61−import Control.Monad.Error
62−import Control.Monad.Unify
64−import Control.Applicative
65−import Control.Arrow (Arrow(..))
67−import qualified Data.Map as M
68−import Data.Function (on)
69−import Data.Ord (comparing)
71−instance Partial Type where
73− isUnknown (TUnknown u) = Just u
74− isUnknown _ = Nothing
76−instance Unifiable Check Type where
80−-- Unify two types, updating the current substitution
82−unifyTypes :: Type -> Type -> UnifyT Type Check ()
83−unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $
86− unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
87− unifyTypes' (TUnknown u) t = u =:= t
88− unifyTypes' t (TUnknown u) = u =:= t
89− unifyTypes' (SaturatedTypeSynonym name args) ty = do
90− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ args
92− unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
93− unifyTypes' (ForAll ident1 ty1 sc1) (ForAll ident2 ty2 sc2) =
95− (Just sc1', Just sc2') -> do
96− sko <- newSkolemConstant
97− let sk1 = skolemize ident1 sko sc1' ty1
98− let sk2 = skolemize ident2 sko sc2' ty2
100− _ -> throwError (prettyPrintType ty1)
101− unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
102− sko <- newSkolemConstant
103− let sk = skolemize ident sko sc ty1
105− unifyTypes' ForAll{} _ = throwError "Skolem variable scope is unspecified"
106− unifyTypes' ty f@ForAll{} = f `unifyTypes` ty
107− unifyTypes' (Object row1) (Object row2) = row1 =?= row2
108− unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
109− unifyTypes' (TypeConstructor c1) (TypeConstructor c2) = do
111− Just moduleName <- checkCurrentModule <$> get
112− guardWith ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".") (typeConstructorsAreEqual env moduleName c1 c2)
113− unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
116− unifyTypes' (Skolem s1 _) (Skolem s2 _) | s1 == s2 = return ()
117− unifyTypes' r1@RCons{} r2 = unifyRows r1 r2
118− unifyTypes' r1 r2@RCons{} = unifyRows r1 r2
119− unifyTypes' r1@REmpty r2 = unifyRows r1 r2
120− unifyTypes' r1 r2@REmpty = unifyRows r1 r2
121− unifyTypes' t3 t4 = throwError $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
124−-- Unify two rows, updating the current substitution
126−-- Common labels are first identified, and unified. Remaining labels and types are unified with a
127−-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
130−unifyRows :: Type -> Type -> UnifyT Type Check ()
133− (s1, r1') = rowToList r1
134− (s2, r2') = rowToList r2
135− int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
136− sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
137− sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
139− forM_ int (uncurry (=?=))
140− unifyRows' sd1 r1' sd2 r2'
142− unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
143− unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
144− unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
145− unifyRows' ((name, ty):row) r others u@(TUnknown un) = do
147− forM_ row $ \(_, t) -> occursCheck un t
149− u =?= RCons name ty u'
150− unifyRows' row r others u'
151− unifyRows' [] REmpty [] REmpty = return ()
152− unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
153− unifyRows' [] (Skolem s1 _) [] (Skolem s2 _) | s1 == s2 = return ()
154− unifyRows' sd3 r3 sd4 r4 = throwError $ "Cannot unify (" ++ prettyPrintRow (rowFromList (sd3, r3)) ++ ") with (" ++ prettyPrintRow (rowFromList (sd4, r4)) ++ ")."
157−-- Ensure type constructors are equal after canonicalization
159−typeConstructorsAreEqual :: Environment -> ModuleName -> Qualified ProperName -> Qualified ProperName -> Bool
160−typeConstructorsAreEqual env moduleName = (==) `on` canonicalizeType moduleName env
163−-- Infer the types of multiple mutually-recursive values, and return elaborated values including
164−-- type class dictionaries and type annotations.
166−typesOf :: Maybe ModuleName -> ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
167−typesOf mainModuleName moduleName vals = do
168− tys <- fmap tidyUp . liftUnify $ do
170− -- Map each declaration to a name/value pair, with an optional type, if the declaration is typed
171− es = map isTyped vals
172− -- Filter the typed and untyped declarations
173− typed = filter (isJust . snd . snd) es
174− untyped = filter (isNothing . snd . snd) es
175− -- Make a map of names to typed declarations
176− typedDict = map (\(ident, (_, Just (ty, _))) -> (ident, ty)) typed
177− -- Create fresh unification variables for the types of untyped declarations
178− untypedNames <- replicateM (length untyped) fresh
180− -- Make a map of names to the unification variables of untyped declarations
181− untypedDict = zip (map fst untyped) untypedNames
182− -- Create the dictionary of all name/type pairs, which will be added to the environment during type checking
183− dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable))) $ typedDict ++ untypedDict)
184− forM es $ \e@(_, (val, _)) -> do
185− -- If the declaration is a function, it has access to other values in the binding group.
186− -- If not, the generated code might fail at runtime since those values might be undefined.
187− let dict' = if isFunction val then dict else M.empty
188− triple@(_, (val', ty)) <- case e of
189− -- Typed declarations
190− (ident, (val', Just (ty, checkType))) -> do
192− kind <- liftCheck $ kindOf moduleName ty
193− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
194− -- Check the type with the new names in scope
195− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
196− val'' <- bindNames dict' $ if checkType
197− then TypedValue True <$> check val' ty' <*> pure ty'
198− else return (TypedValue False val' ty')
199− return (ident, (val'', ty'))
200− -- Untyped declarations
201− (ident, (val', Nothing)) -> do
202− -- Infer the type with the new names in scope
203− TypedValue _ val'' ty <- bindNames dict' $ infer val'
204− ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
205− return (ident, (TypedValue True val'' ty, ty))
206− -- If --main is enabled, need to check that `main` has type Eff eff a for some eff, a
207− when (Just moduleName == mainModuleName && fst e == Ident "main") $ do
208− [eff, a] <- replicateM 2 fresh
209− ty =?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName [ProperName "Control", ProperName "Monad", ProperName "Eff"])) (ProperName "Eff"))) eff) a
210− -- Make sure unification variables do not escape
213− forM tys $ \(ident, (val, ty)) -> do
214− -- Replace type class dictionary placeholders with actual dictionaries
215− val' <- replaceTypeClassDictionaries moduleName val
216− -- Check skolem variables did not escape their scope
217− skolemEscapeCheck val'
218− -- Remove type synonyms placeholders, remove duplicate row fields, and replace
219− -- top-level unification variables with named type variables.
220− let val'' = overTypes (desaturateAllTypeSynonyms . setifyAll) val'
221− ty' = varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty
222− return (ident, (val'', ty'))
224− -- Apply the substitution that was returned from runUnify to both types and (type-annotated) values
225− tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
228−-- Check if a value introduces a function
230−isFunction :: Value -> Bool
231−isFunction (Abs _ _) = True
232−isFunction (TypedValue _ val _) = isFunction val
236−-- Check if a value contains a type annotation
238−isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
239−isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
240−isTyped (name, value) = (name, (value, Nothing))
243−-- Map a function over type annotations appearing inside a value
245−overTypes :: (Type -> Type) -> Value -> Value
246−overTypes f = everywhere (mkT f)
249−-- Replace type class dictionary placeholders with inferred type class dictionaries
251−replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
252−replaceTypeClassDictionaries mn = everywhereM' (mkM go)
254− go (TypeClassDictionary constraint dicts) = entails mn dicts constraint
255− go other = return other
258−-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
259−-- return a type class dictionary reference.
261−entails :: ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, [Type]) -> Check Value
262−entails moduleName context goal@(className, tys) = do
265− [] -> throwError $ "No " ++ show className ++ " instance found for " ++ intercalate ", " (map prettyPrintType tys)
266− (dict : _) -> return dict
268− go env (className', tys') =
269− [ mkDictionary (canonicalizeDictionary tcd) args
271− -- Choose type class dictionaries in scope in the current module
273− -- Make sure the type class name matches the one we are trying to satisfy
274− , typeConstructorsAreEqual env moduleName className' (tcdClassName tcd)
275− -- Make sure the type unifies with the type in the type instance definition
276− , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' (tcdInstanceTypes tcd)
277− -- Solve any necessary subgoals
278− , args <- solveSubgoals env subst (tcdDependencies tcd) ]
279− -- Create dictionaries for subgoals which still need to be solved by calling go recursively
280− -- E.g. the goal (Show a, Show b) => Show (Either a b) can be satisfied if the current type
281− -- unifies with Either a b, and we can satisfy the subgoals Show a and Show b recursively.
282− solveSubgoals :: Environment -> [(String, Type)] -> Maybe [(Qualified ProperName, [Type])] -> [Maybe [Value]]
283− solveSubgoals _ _ Nothing = return Nothing
284− solveSubgoals env subst (Just subgoals) = do
285− dict <- mapM (go env . second (map (replaceAllTypeVars subst))) subgoals
287− -- Make a dictionary from subgoal dictionaries by applying the correct function
288− mkDictionary :: Qualified Ident -> Maybe [Value] -> Value
289− mkDictionary fnName Nothing = Var fnName
290− mkDictionary fnName (Just []) = App (Var fnName) (ObjectLiteral [])
291− mkDictionary fnName (Just dicts) = foldl App (Var fnName) dicts
292− -- Filter out type dictionaries which are in scope in the current module
293− filterModule :: TypeClassDictionaryInScope -> Bool
294− filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
295− filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
296− filterModule _ = False
297− -- Resolve a type class dictionary in scope to an actual value by following any (TCDAlias) pointers
298− -- which originated from module imports
299− canonicalizeDictionary :: TypeClassDictionaryInScope -> Qualified Ident
300− canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDRegular, tcdName = nm }) = nm
301− canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDAlias nm }) = nm
302− -- Ensure that a substitution is valid
303− verifySubstitution :: [(String, Type)] -> Maybe [(String, Type)]
304− verifySubstitution subst = do
305− let grps = groupBy ((==) `on` fst) subst
306− guard (all ((==) 1 . length . nubBy ((==) `on` snd)) grps)
307− return $ map head grps
310−-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
311−-- and return a substitution from type variables to types which makes the type heads unify.
313−typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
314−typeHeadsAreEqual _ _ (Skolem s1 _) (Skolem s2 _) | s1 == s2 = Just []
315−typeHeadsAreEqual _ _ (TypeVar v) t = Just [(v, t)]
316−typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
317−typeHeadsAreEqual m e (TypeConstructor c1) (TypeConstructor c2) | typeConstructorsAreEqual e m c1 c2 = Just []
318−typeHeadsAreEqual m e (TypeApp h1 (TypeVar v)) (TypeApp h2 arg) = (:) (v, arg) <$> typeHeadsAreEqual m e h1 h2
319−typeHeadsAreEqual m e t1@(TypeApp _ _) t2@(TypeApp _ (TypeVar _)) = typeHeadsAreEqual m e t2 t1
320−typeHeadsAreEqual m e (SaturatedTypeSynonym name args) t2 = case expandTypeSynonym' e m name args of
322− Right t1 -> typeHeadsAreEqual m e t1 t2
323−typeHeadsAreEqual _ _ _ _ = Nothing
326−-- Ensure unsolved unification variables do not escape
328−escapeCheck :: Value -> Type -> UnifyT Type Check ()
329−escapeCheck value ty = do
330− subst <- unifyCurrentSubstitution <$> UnifyT get
331− let visibleUnknowns = nub $ unknowns $ subst $? ty
332− let allUnknowns = findAllTypes value
333− forM_ allUnknowns $ \t -> do
334− let unsolvedUnknowns = nub . unknowns $ subst $? t
335− guardWith "Escape check fails" $ null $ unsolvedUnknowns \\ visibleUnknowns
338−-- Find all type annotations occuring inside a value
340−findAllTypes :: Value -> [Type]
341−findAllTypes = everything (++) (mkQ [] go)
343− go (TypedValue _ _ ty) = [ty]
347−-- Ensure skolem variables do not escape their scope
349−skolemEscapeCheck :: Value -> Check ()
350−skolemEscapeCheck (TypedValue False _ _) = return ()
351−skolemEscapeCheck root@TypedValue{} =
352− -- Every skolem variable is created when a ForAll type is skolemized.
353− -- This determines the scope of that skolem variable, which is copied from the SkolemScope
354− -- field of the ForAll constructor.
355− -- We traverse the tree top-down, and collect any SkolemScopes introduced by ForAlls.
356− -- If a Skolem is encountered whose SkolemScope is not in the current list, we have found
357− -- an escaped skolem variable.
358− case everythingWithContext [] (++) (mkQ ((,) []) go) root of
360− ((binding, val) : _) -> throwError $ "Rigid/skolem type variable bound by " ++ maybe "<unknown>" prettyPrintValue binding ++ " has escaped at " ++ prettyPrintValue val
362− go :: Value -> [(SkolemScope, Value)] -> ([(Maybe Value, Value)], [(SkolemScope, Value)])
363− go val@(TypedValue _ _ (ForAll _ _ (Just sco))) scos = ([], (sco, val) : scos)
364− go val@(TypedValue _ _ ty) scos = case collectSkolems ty \\ map fst scos of
365− (sco : _) -> ([(findBindingScope sco, val)], scos)
368− collectSkolems :: Type -> [SkolemScope]
369− collectSkolems = nub . everything (++) (mkQ [] collect)
371− collect (Skolem _ scope) = [scope]
373− go _ scos = ([], scos)
374− findBindingScope :: SkolemScope -> Maybe Value
375− findBindingScope sco = something (mkQ Nothing go') root
377− go' val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = Just val
379−skolemEscapeCheck val = throwError $ "Untyped value passed to skolemEscapeCheck: " ++ prettyPrintValue val
382−-- Ensure a row contains no duplicate labels
384−setify :: Type -> Type
385−setify = rowFromList . first (M.toList . M.fromList) . rowToList
388−-- \"Setify\" all rows occuring inside a value
390−setifyAll :: (D.Data d) => d -> d
391−setifyAll = everywhere (mkT setify)
394−-- Replace outermost unsolved unification variables with named type variables
396−varIfUnknown :: Type -> Type
398− let unks = nub $ unknowns ty
399− toName = (:) 't' . show
400− ty' = everywhere (mkT typeToVar) ty
401− typeToVar :: Type -> Type
402− typeToVar (TUnknown (Unknown u)) = TypeVar (toName u)
404− in mkForAll (sort . map (toName . runUnknown) $ unks) ty'
407−-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
408−-- or TypeClassDictionary values.
410−-- This is necessary during type checking to avoid unifying a polymorphic type with a
411−-- unification variable.
413−instantiatePolyTypeWithUnknowns :: Value -> Type -> UnifyT Type Check (Value, Type)
414−instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
415− ty' <- replaceVarWithUnknown ident ty
416− instantiatePolyTypeWithUnknowns val ty'
417−instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
419− Just moduleName <- checkCurrentModule <$> get
420− dicts <- getTypeClassDictionaries
421− (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
422− return (foldl App val (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints)), ty')
423−instantiatePolyTypeWithUnknowns val ty = return (val, ty)
426−-- Replace a single type variable with a new unification variable
428−replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
429−replaceVarWithUnknown ident ty = do
431− return $ replaceTypeVars ident tu ty
434−-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
435−-- better error messages during unification.
437−replaceAllTypeSynonyms' :: (D.Data d) => Environment -> ModuleName -> d -> Either String d
438−replaceAllTypeSynonyms' env moduleName d =
440− syns = map (\((path, name), (args, _)) -> ((path, name), length args)) . M.toList $ typeSynonyms env
442− saturateAllTypeSynonyms env moduleName syns d
444−replaceAllTypeSynonyms :: (Functor m, Monad m, MonadState CheckState m, MonadError String m) => (D.Data d) => d -> m d
445−replaceAllTypeSynonyms d = do
447− Just moduleName <- checkCurrentModule <$> get
448− either throwError return $ replaceAllTypeSynonyms' env moduleName d
451−-- \"Desaturate\" @SaturatedTypeSynonym@s
453−desaturateAllTypeSynonyms :: (D.Data d) => d -> d
454−desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
456− replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
457− replaceSaturatedTypeSynonym t = t
460−-- Replace a type synonym and its arguments with the aliased type
462−expandTypeSynonym' :: Environment -> ModuleName -> Qualified ProperName -> [Type] -> Either String Type
463−expandTypeSynonym' env moduleName name args =
464− case M.lookup (canonicalizeType moduleName env name) (typeSynonyms env) of
465− Just (synArgs, body) -> do
466− let repl = replaceAllTypeVars (zip synArgs args) body
467− replaceAllTypeSynonyms' env moduleName repl
468− Nothing -> error "Type synonym was not defined"
470−expandTypeSynonym :: (Functor m, Monad m, MonadState CheckState m, MonadError String m) => Qualified ProperName -> [Type] -> m Type
471−expandTypeSynonym name args = do
473− Just moduleName <- checkCurrentModule <$> get
474− either throwError return $ expandTypeSynonym' env moduleName name args
477−-- Ensure a set of property names and value does not contain duplicate labels
479−ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
480−ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
483−-- Infer a type for a value, rethrowing any error to provide a more useful error message
485−infer :: Value -> UnifyT Type Check Value
486−infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
489−-- Infer a type for a value
491−infer' :: Value -> UnifyT Type Check Value
492−infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
493−infer' v@(StringLiteral _) = return $ TypedValue True v tyString
494−infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
495−infer' (ArrayLiteral vals) = do
496− ts <- mapM infer vals
498− forM_ ts $ \(TypedValue _ _ t) -> els =?= TypeApp tyArray t
499− return $ TypedValue True (ArrayLiteral ts) els
500−infer' (ObjectLiteral ps) = do
501− ensureNoDuplicateProperties ps
502− ts <- mapM (infer . snd) ps
503− let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
504− ty = Object $ rowFromList (fields, REmpty)
505− return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
506−infer' (ObjectUpdate o ps) = do
507− ensureNoDuplicateProperties ps
509− newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
510− let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
511− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
512− let oldTy = Object $ rowFromList (oldTys, row)
513− o' <- TypedValue True <$> check o oldTy <*> pure oldTy
514− return $ TypedValue True (ObjectUpdate o' newVals) $ Object $ rowFromList (newTys, row)
515−infer' (Accessor prop val) = do
516− typed@(TypedValue _ _ objTy) <- infer val
517− propTy <- inferProperty objTy prop
522− _ <- subsumes Nothing objTy (Object (RCons prop field rest))
523− return $ TypedValue True (Accessor prop typed) field
524− Just ty -> return $ TypedValue True (Accessor prop typed) ty
525−infer' (Abs (Left arg) ret) = do
527− Just moduleName <- checkCurrentModule <$> get
528− bindLocalVariables moduleName [(arg, ty)] $ do
529− body@(TypedValue _ _ bodyTy) <- infer' ret
530− return $ TypedValue True (Abs (Left arg) body) $ function ty bodyTy
531−infer' (Abs (Right _) _) = error "Binder was not desugared"
532−infer' (App f arg) = do
533− f'@(TypedValue _ _ ft) <- infer f
534− (ret, app) <- checkFunctionApplication f' ft arg
535− return $ TypedValue True app ret
536−infer' (Var var) = do
537− Just moduleName <- checkCurrentModule <$> get
538− ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
540− ConstrainedType constraints ty' -> do
542− dicts <- getTypeClassDictionaries
543− return $ TypedValue True (foldl App (Var var) (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))) ty'
544− _ -> return $ TypedValue True (Var var) ty
545−infer' v@(Constructor c) = do
547− Just moduleName <- checkCurrentModule <$> get
548− case M.lookup (qualify moduleName 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' (TypedValue checkType val ty) = do
564− Just moduleName <- checkCurrentModule <$> get
565− kind <- liftCheck $ kindOf moduleName ty
566− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
567− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
568− val' <- if checkType then check val ty' else return val
569− return $ TypedValue True val' ty'
570−infer' _ = error "Invalid argument to infer"
573−-- Infer the type of a property inside a record with a given type
575−inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
576−inferProperty (Object row) prop = do
577− let (props, _) = rowToList row
578− return $ lookup prop props
579−inferProperty (SaturatedTypeSynonym name args) prop = do
580− replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
581− inferProperty replaced prop
582−inferProperty (ForAll ident ty _) prop = do
583− replaced <- replaceVarWithUnknown ident ty
584− inferProperty replaced prop
585−inferProperty _ _ = return Nothing
588−-- Infer the types of variables brought into scope by a binder
590−inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
591−inferBinder _ NullBinder = return M.empty
592−inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
593−inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
594−inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
595−inferBinder val (VarBinder name) = return $ M.singleton name val
596−inferBinder val (ConstructorBinder ctor binders) = do
598− Just moduleName <- checkCurrentModule <$> get
599− case M.lookup (qualify moduleName ctor) (dataConstructors env) of
601− (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contains constraints") ty
605− subsumes Nothing val ty'
607− go (binder : binders') (TypeApp (TypeApp t obj) ret) | t == tyFunction =
608− M.union <$> inferBinder obj binder <*> go binders' ret
609− go _ _ = throwError $ "Wrong number of arguments to constructor " ++ show ctor
610− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
611−inferBinder val (ObjectBinder props) = do
614− m1 <- inferRowProperties row rest props
618− inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
619− inferRowProperties nrow row [] = nrow =?= row >> return M.empty
620− inferRowProperties nrow row ((name, binder):binders) = do
622− m1 <- inferBinder propTy binder
623− m2 <- inferRowProperties nrow (RCons name propTy row) binders
624− return $ m1 `M.union` m2
625−inferBinder val (ArrayBinder binders) = do
627− m1 <- M.unions <$> mapM (inferBinder el) binders
628− val =?= TypeApp tyArray el
630−inferBinder val (ConsBinder headBinder tailBinder) = do
632− m1 <- inferBinder el headBinder
633− m2 <- inferBinder val tailBinder
634− val =?= TypeApp tyArray el
635− return $ m1 `M.union` m2
636−inferBinder val (NamedBinder name binder) = do
637− m <- inferBinder val binder
638− return $ M.insert name val m
641−-- Check the types of the return values in a set of binders in a case statement
643−checkBinders :: [Type] -> Type -> [([Binder], Maybe Guard, Value)] -> UnifyT Type Check [([Binder], Maybe Guard, Value)]
644−checkBinders _ _ [] = return []
645−checkBinders nvals ret ((binders, grd, val):bs) = do
646− Just moduleName <- checkCurrentModule <$> get
647− m1 <- M.unions <$> zipWithM inferBinder nvals binders
648− r <- bindLocalVariables moduleName (M.toList m1) $ do
649− val' <- TypedValue True <$> check val ret <*> pure ret
651− Nothing -> return (binders, Nothing, val')
653− g' <- check g tyBoolean
654− return (binders, Just g', val')
655− rs <- checkBinders nvals ret bs
659−-- Check that a local variable name is not already used
661−assignVariable :: Ident -> UnifyT Type Check ()
662−assignVariable name = do
663− env <- checkEnv <$> get
664− Just moduleName <- checkCurrentModule <$> get
665− case M.lookup (moduleName, name) (names env) of
666− Just _ -> UnifyT . lift . throwError $ "Variable with name " ++ show name ++ " already exists."
670−-- Generate a new skolem constant
672−newSkolemConstant :: UnifyT Type Check Int
673−newSkolemConstant = runUnknown <$> fresh'
676−-- Generate a new skolem scope
678−newSkolemScope :: UnifyT Type Check SkolemScope
679−newSkolemScope = SkolemScope . runUnknown <$> fresh'
682−-- Skolemize a type variable by replacing its instances with fresh skolem constants
684−skolemize :: String -> Int -> SkolemScope -> Type -> Type
685−skolemize ident sko scope = replaceTypeVars ident (Skolem sko scope)
688−-- Introduce skolem scope at every occurence of a ForAll
690−introduceSkolemScope :: Type -> UnifyT Type Check Type
691−introduceSkolemScope = everywhereM (mkM go)
693− go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
694− go other = return other
697−-- Check the type of a value, rethrowing errors to provide a better error message
699−check :: Value -> Type -> UnifyT Type Check Value
700−check val ty = rethrow errorMessage $ check' val ty
703− "Error checking type of term " ++
704− prettyPrintValue val ++
706− prettyPrintType ty ++
711−-- Check the type of a value
713−check' :: Value -> Type -> UnifyT Type Check Value
714−check' val (ForAll ident ty _) = do
715− scope <- newSkolemScope
716− sko <- newSkolemConstant
717− let sk = skolemize ident sko scope ty
718− val' <- check val sk
719− return $ TypedValue True val' (ForAll ident ty (Just scope))
720−check' val t@(ConstrainedType constraints ty) = do
722− Just moduleName <- checkCurrentModule <$> get
723− dictNames <- forM constraints $ \(Qualified _ (ProperName className), _) -> do
724− n <- liftCheck freshDictionaryName
725− return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
726− val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
727− TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
728− (qualifyAllUnqualifiedNames moduleName env constraints)) $
730− return $ TypedValue True (foldr (Abs . Left) val' dictNames) t
731−check' val (SaturatedTypeSynonym name args) = do
732− ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
733− val' <- check val ty
734− return $ TypedValue True val' ty
735−check' val u@(TUnknown _) = do
736− val'@(TypedValue _ _ ty) <- infer val
737− -- Don't unify an unknown with an inferred polytype
738− (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
740− return $ TypedValue True val'' ty'
741−check' v@(NumericLiteral _) t | t == tyNumber =
742− return $ TypedValue True v t
743−check' v@(StringLiteral _) t | t == tyString =
744− return $ TypedValue True v t
745−check' v@(BooleanLiteral _) t | t == tyBoolean =
746− return $ TypedValue True v t
747−check' (ArrayLiteral vals) t@(TypeApp a ty) | a == tyArray = do
748− array <- ArrayLiteral <$> forM vals (`check` ty)
749− return $ TypedValue True array t
750−check' (Abs (Left arg) ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
751− Just moduleName <- checkCurrentModule <$> get
752− ret' <- bindLocalVariables moduleName [(arg, argTy)] $ check ret retTy
753− return $ TypedValue True (Abs (Left arg) ret') ty
754−check' (Abs (Right _) _) _ = error "Binder was not desugared"
755−check' (App f arg) ret = do
756− f'@(TypedValue _ _ ft) <- infer f
757− (ret', app) <- checkFunctionApplication f' ft arg
758− subsumes Nothing ret' ret
759− return $ TypedValue True app ret
760−check' v@(Var var) ty = do
761− Just moduleName <- checkCurrentModule <$> get
762− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
763− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
764− v' <- subsumes (Just v) repl ty'
766− Nothing -> throwError "Unable to check type subsumption"
767− Just v'' -> return $ TypedValue True v'' ty'
768−check' (TypedValue checkType val ty1) ty2 = do
769− Just moduleName <- checkCurrentModule <$> get
770− kind <- liftCheck $ kindOf moduleName ty1
771− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
772− ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
773− val' <- subsumes (Just val) ty1' ty2
775− Nothing -> throwError "Unable to check type subsumption"
777− val''' <- if checkType then check val'' ty1 else return val''
778− return $ TypedValue checkType (TypedValue True val''' ty1) ty2
779−check' (Case vals binders) ret = do
780− vals' <- mapM infer vals
781− let ts = map (\(TypedValue _ _ t) -> t) vals'
782− binders' <- checkBinders ts ret binders
783− return $ TypedValue True (Case vals' binders') ret
784−check' (IfThenElse cond th el) ty = do
785− cond' <- check cond tyBoolean
788− return $ TypedValue True (IfThenElse cond' th' el') ty
789−check' (ObjectLiteral ps) t@(Object row) = do
790− ensureNoDuplicateProperties ps
791− ps' <- checkProperties ps row False
792− return $ TypedValue True (ObjectLiteral ps') t
793−check' (ObjectUpdate obj ps) t@(Object row) = do
794− ensureNoDuplicateProperties ps
795− us <- zip (map fst ps) <$> replicateM (length ps) fresh
796− let (propsToCheck, rest) = rowToList row
797− propsToRemove = map fst ps
798− remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
799− obj' <- check obj (Object (rowFromList (us ++ remainingProps, rest)))
800− ps' <- checkProperties ps row True
801− return $ TypedValue True (ObjectUpdate obj' ps') t
802−check' (Accessor prop val) ty = do
804− val' <- check val (Object (RCons prop ty rest))
805− return $ TypedValue True (Accessor prop val') ty
806−check' (Constructor c) ty = do
808− Just moduleName <- checkCurrentModule <$> get
809− case M.lookup (qualify moduleName c) (dataConstructors env) of
810− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
812− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
813− _ <- subsumes Nothing repl ty
814− return $ TypedValue True (Constructor c) ty
815−check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
818−-- Check the type of a collection of named record fields
820−-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
822−checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Type Check [(String, Value)]
823−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
824− go [] [] REmpty = return []
825− go [] [] u@(TUnknown _) = do u =?= REmpty
827− go [] [] (Skolem _ _) | lax = return []
828− go [] ((p, _): _) _ | lax = return []
829− | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
830− go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
831− go ((p,v):ps') [] u@(TUnknown _) = do
832− v'@(TypedValue _ _ ty) <- infer v
834− u =?= RCons p ty rest
835− ps'' <- go ps' [] rest
836− return $ (p, v') : ps''
837− go ((p,v):ps') ts r =
840− v'@(TypedValue _ _ ty) <- infer v
842− r =?= RCons p ty rest
843− ps'' <- go ps' ts rest
844− return $ (p, v') : ps''
847− ps'' <- go ps' (delete (p, ty) ts) r
848− return $ (p, v') : ps''
849− go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
852−-- Check the type of a function application, rethrowing errors to provide a better error message
854−checkFunctionApplication :: Value -> Type -> Value -> UnifyT Type Check (Type, Value)
855−checkFunctionApplication fn fnTy arg = rethrow errorMessage $ checkFunctionApplication' fn fnTy arg
857− errorMessage msg = "Error applying function of type "
858− ++ prettyPrintType fnTy
859− ++ " to argument " ++ prettyPrintValue arg
863−-- Check the type of a function application
865−checkFunctionApplication' :: Value -> Type -> Value -> UnifyT Type Check (Type, Value)
866−checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg = do
867− tyFunction' =?= tyFunction
868− arg' <- check arg argTy
869− return (retTy, App fn arg')
870−checkFunctionApplication' fn (ForAll ident ty _) arg = do
871− replaced <- replaceVarWithUnknown ident ty
872− checkFunctionApplication fn replaced arg
873−checkFunctionApplication' fn u@(TUnknown _) arg = do
875− TypedValue _ arg' t <- infer arg
876− (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
877− return $ TypedValue True arg'' t'
878− let ty = (\(TypedValue _ _ t) -> t) arg'
880− u =?= function ty ret
881− return (ret, App fn arg')
882−checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg = do
883− ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
884− checkFunctionApplication fn ty arg
885−checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg = do
887− dicts <- getTypeClassDictionaries
888− Just moduleName <- checkCurrentModule <$> get
889− checkFunctionApplication' (foldl App fn (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))) fnTy arg
890−checkFunctionApplication' _ fnTy arg = throwError $ "Cannot apply a function of type "
891− ++ prettyPrintType fnTy
892− ++ " to argument " ++ prettyPrintValue arg
895−-- Check whether one type subsumes another, rethrowing errors to provide a better error message
897−subsumes :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
898−subsumes val ty1 ty2 = rethrow errorMessage $ subsumes' val ty1 ty2
900− errorMessage msg = "Error checking that type "
901− ++ prettyPrintType ty1
902− ++ " subsumes type "
903− ++ prettyPrintType ty2
907−-- Check whether one type subsumes another
909−subsumes' :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
910−subsumes' val (ForAll ident ty1 _) ty2 = do
911− replaced <- replaceVarWithUnknown ident ty1
912− subsumes val replaced ty2
913−subsumes' val ty1 (ForAll ident ty2 sco) =
916− sko <- newSkolemConstant
917− let sk = skolemize ident sko sco' ty2
919− Nothing -> throwError "Skolem variable scope is unspecified"
920−subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
921− subsumes Nothing arg2 arg1
922− subsumes Nothing ret1 ret2
924−subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
925− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
926− subsumes val ty1 ty2
927−subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
928− ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
929− subsumes val ty1 ty2
930−subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
932− dicts <- getTypeClassDictionaries
933− Just moduleName <- checkCurrentModule <$> get
934− _ <- subsumes' Nothing ty1 ty2
935− return . Just $ foldl App val (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))
936−subsumes' val (Object r1) (Object r2) = do
938− (ts1, r1') = rowToList r1
939− (ts2, r2') = rowToList r2
940− ts1' = sortBy (comparing fst) ts1
941− ts2' = sortBy (comparing fst) ts2
942− go ts1' ts2' r1' r2'
945− go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
946− go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
947− go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
948− | p1 == p2 = do subsumes Nothing ty1 ty2
950− | p1 < p2 = do rest <- fresh
951− r2' =?= RCons p1 ty1 rest
952− go ts1 ((p2, ty2) : ts2) r1' rest
953− | p1 > p2 = do rest <- fresh
954− r1' =?= RCons p2 ty2 rest
955− go ((p1, ty1) : ts1) ts2 rest r2'
956−subsumes' val ty1 ty2@(Object _) = subsumes val ty2 ty1
957−subsumes' val ty1 ty2 = do