@@ -1,882 +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 DeriveDataTypeable #-}
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− (mkM, everywhereM, everything, mkT, something, everywhere, mkQ)
50−import Language.PureScript.Values
51−import Language.PureScript.Types
52−import Language.PureScript.Kinds
53−import Language.PureScript.Names
54−import Language.PureScript.TypeChecker.Monad
55−import Language.PureScript.TypeChecker.Kinds
56−import Language.PureScript.TypeChecker.Synonyms
57−import Language.PureScript.Pretty
59−import Control.Monad.State
60−import Control.Monad.Error
61−import Control.Monad.Reader
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)
70−instance Partial Type where
72− isUnknown (TUnknown u) = Just u
73− isUnknown _ = Nothing
75−instance Unifiable Check Type where
79−-- Unify two types, updating the current substitution
81−unifyTypes :: Type -> Type -> UnifyT Type Check ()
82−unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $ do
85− unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
86− unifyTypes' (TUnknown u) t = u =:= t
87− unifyTypes' t (TUnknown u) = u =:= t
88− unifyTypes' (SaturatedTypeSynonym name args) ty = do
89− ty1 <- expandTypeSynonym name args
91− unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
92− unifyTypes' (ForAll ident1 ty1) (ForAll ident2 ty2) = do
93− sk <- skolemize ident1 ty1
94− replaced <- replaceVarWithUnknown ident2 ty2
95− sk `unifyTypes` replaced
96− unifyTypes' (ForAll ident ty1) ty2 = do
97− sk <- skolemize ident ty1
99− unifyTypes' ty f@(ForAll _ _) = f `unifyTypes` ty
100− unifyTypes' (Object row1) (Object row2) = row1 =?= row2
101− unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
102− unifyTypes' (TypeConstructor c1) (TypeConstructor c2) = do
104− Just moduleName <- checkCurrentModule <$> get
105− guardWith ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".") (typeConstructorsAreEqual env moduleName c1 c2)
106− unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
109− unifyTypes' (Skolem s1) (Skolem s2) | s1 == s2 = return ()
110− unifyTypes' r1@(RCons _ _ _) r2 = unifyRows r1 r2
111− unifyTypes' r1 r2@(RCons _ _ _) = unifyRows r1 r2
112− unifyTypes' r1@REmpty r2 = unifyRows r1 r2
113− unifyTypes' r1 r2@REmpty = unifyRows r1 r2
114− unifyTypes' t3 t4 = throwError $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
117−-- Unify two rows, updating the current substitution
119−-- Common labels are first identified, and unified. Remaining labels and types are unified with a
120−-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
123−unifyRows :: Type -> Type -> UnifyT Type Check ()
126− (s1, r1') = rowToList r1
127− (s2, r2') = rowToList r2
128− int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
129− sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
130− sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
132− forM_ int (uncurry (=?=))
133− unifyRows' sd1 r1' sd2 r2'
135− unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
136− unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
137− unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
138− unifyRows' ((name, ty):row) r others u@(TUnknown un) = do
140− forM_ row $ \(_, t) -> occursCheck un t
142− u =?= RCons name ty u'
143− unifyRows' row r others u'
144− unifyRows' [] REmpty [] REmpty = return ()
145− unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
146− unifyRows' [] (Skolem s1) [] (Skolem s2) | s1 == s2 = return ()
147− unifyRows' sd3 r3 sd4 r4 = throwError $ "Cannot unify " ++ prettyPrintRow (rowFromList (sd3, r3)) ++ " with " ++ prettyPrintRow (rowFromList (sd4, r4)) ++ "."
150−-- Ensure type constructors are equal after canonicalization
152−typeConstructorsAreEqual :: Environment -> ModuleName -> Qualified ProperName -> Qualified ProperName -> Bool
153−typeConstructorsAreEqual env moduleName = (==) `on` canonicalizeType moduleName env
156−-- Infer the types of multiple mutually-recursive values, and return elaborated values including
157−-- type class dictionaries and type annotations.
159−typesOf :: ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
160−typesOf moduleName vals = do
161− tys <- fmap tidyUp . liftUnify $ do
162− let es = map isTyped vals
163− typed = filter (isJust . snd . snd) es
164− untyped = filter (isNothing . snd . snd) es
165− typedDict = map (\(ident, (_, Just ty)) -> (ident, ty)) typed
166− untypedNames <- replicateM (length untyped) fresh
167− let untypedDict = zip (map fst untyped) untypedNames
168− dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable))) $ (map (id *** fst) typedDict) ++ untypedDict)
170− triple@(_, (val, ty)) <- case e of
171− (ident, (val, Just (ty, checkType))) -> do
172− kind <- liftCheck $ kindOf moduleName ty
173− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
174− ty' <- replaceAllTypeSynonyms ty
175− val' <- bindNames dict $ if checkType then check val ty' else return val
176− return (ident, (val', ty'))
177− (ident, (val, Nothing)) -> do
178− TypedValue _ val' ty <- bindNames dict $ infer val
179− ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
180− return (ident, (val', ty))
181− when (moduleName == ModuleName (ProperName "Main") && fst e == Ident "main") $ do
182− [eff, a] <- replicateM 2 fresh
183− ty =?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName (ProperName "Eff"))) (ProperName "Eff"))) eff) a
186− forM_ tys $ skolemEscapeCheck . snd . snd
187− forM tys $ \(ident, (val, ty)) -> do
188− val' <- replaceTypeClassDictionaries moduleName val
189− return (ident, (overTypes (desaturateAllTypeSynonyms . setifyAll) $ val'
190− , varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty))
192− tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
195−-- Check if a value contains a type annotation
197−isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
198−isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
199−isTyped (name, value) = (name, (value, Nothing))
202−-- Map a function over type annotations appearing inside a value
204−overTypes :: (Type -> Type) -> Value -> Value
205−overTypes f = everywhere (mkT f)
208−-- Replace type class dictionary placeholders with inferred type class dictionaries
210−replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
211−replaceTypeClassDictionaries mn = everywhereM (mkM go)
213− go (TypeClassDictionary constraint dicts) = entails mn dicts constraint
214− go other = return other
217−-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
218−-- return a type class dictionary reference.
220−entails :: ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, Type) -> Check Value
221−entails moduleName context goal@(className, ty) = do
224− [] -> throwError $ "No " ++ show className ++ " instance found for " ++ prettyPrintType ty
225− (dict : _) -> return dict
227− go env (className', ty') =
228− [ mkDictionary (canonicalizeDictionary tcd) args
231− , typeConstructorsAreEqual env moduleName className' (tcdClassName tcd)
232− , subst <- maybeToList $ typeHeadsAreEqual moduleName env ty' (tcdInstanceType tcd)
233− , args <- solveSubgoals env subst (tcdDependencies tcd) ]
234− solveSubgoals :: Environment -> [(String, Type)] -> Maybe [(Qualified ProperName, Type)] -> [Maybe [Value]]
235− solveSubgoals _ _ Nothing = return Nothing
236− solveSubgoals env subst (Just subgoals) = do
237− dict <- mapM (go env) (replaceAllTypeVars subst subgoals)
239− mkDictionary :: Qualified Ident -> Maybe [Value] -> Value
240− mkDictionary fnName Nothing = Var fnName
241− mkDictionary fnName (Just dicts) = foldl App (Var fnName) dicts
242− filterModule :: TypeClassDictionaryInScope -> Bool
243− filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
244− filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
245− filterModule _ = False
246− canonicalizeDictionary :: TypeClassDictionaryInScope -> Qualified Ident
247− canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDRegular, tcdName = nm }) = nm
248− canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDAlias nm }) = nm
251−-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
252−-- and return a substitution from type variables to types which makes the type heads unify.
254−typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
255−typeHeadsAreEqual _ _ (Skolem s1) (Skolem s2) | s1 == s2 = Just []
256−typeHeadsAreEqual m e (TypeConstructor c1) (TypeConstructor c2) | typeConstructorsAreEqual e m c1 c2 = Just []
257−typeHeadsAreEqual m e (TypeApp h1 (TypeVar v)) (TypeApp h2 arg) = (:) (v, arg) <$> typeHeadsAreEqual m e h1 h2
258−typeHeadsAreEqual m e t1@(TypeApp _ _) t2@(TypeApp _ (TypeVar _)) = typeHeadsAreEqual m e t2 t1
259−typeHeadsAreEqual _ _ _ _ = Nothing
262−-- Ensure unsolved unification variables do not escape
264−escapeCheck :: Value -> Type -> UnifyT Type Check ()
265−escapeCheck value ty = do
266− subst <- unifyCurrentSubstitution <$> UnifyT get
267− let visibleUnknowns = nub $ unknowns $ subst $? ty
268− let allUnknowns = findAllTypes value
269− forM_ allUnknowns $ \t -> do
270− let unsolvedUnknowns = nub . unknowns $ subst $? t
271− guardWith ("Escape check fails" ++ show (subst $? ty, subst $? t)) $ null $ unsolvedUnknowns \\ visibleUnknowns
274−-- Find all type annotations occuring inside a value
276−findAllTypes :: Value -> [Type]
277−findAllTypes = everything (++) (mkQ [] go)
279− go (TypedValue _ _ ty) = [ty]
283−-- Ensure skolem variables do not escape their scope
285−skolemEscapeCheck :: Type -> Check ()
286−skolemEscapeCheck ty =
287− case something (mkQ Nothing findSkolems) ty of
288− Nothing -> return ()
289− Just _ -> throwError $ "Skolem variables cannot escape. Consider adding a type signature."
291− findSkolems (Skolem _) = return ()
292− findSkolems _ = mzero
295−-- Ensure a row contains no duplicate labels
297−setify :: Type -> Type
298−setify = rowFromList . first (M.toList . M.fromList) . rowToList
301−-- \"Setify\" all rows occuring inside a value
303−setifyAll :: (D.Data d) => d -> d
304−setifyAll = everywhere (mkT setify)
307−-- Replace outermost unsolved unification variables with named type variables
309−varIfUnknown :: Type -> Type
311− let unks = nub $ unknowns ty
312− toName = (:) 't' . show
313− ty' = everywhere (mkT typeToVar) $ ty
314− typeToVar :: Type -> Type
315− typeToVar (TUnknown (Unknown u)) = TypeVar (toName u)
317− in mkForAll (sort . map (toName . runUnknown) $ unks) ty'
320−-- Replace named type variables with types
322−replaceAllTypeVars :: (D.Data d) => [(String, Type)] -> d -> d
323−replaceAllTypeVars = foldl' (\f (name, ty) -> replaceTypeVars name ty . f) id
326−-- Replace named type variables with new unification variables
328−replaceAllVarsWithUnknowns :: Type -> UnifyT Type Check Type
329−replaceAllVarsWithUnknowns (ForAll ident ty) = replaceVarWithUnknown ident ty >>= replaceAllVarsWithUnknowns
330−replaceAllVarsWithUnknowns ty = return ty
333−-- Replace a single type variable with a new unification variable
335−replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
336−replaceVarWithUnknown ident ty = do
338− return $ replaceTypeVars ident tu $ ty
341−-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
342−-- better error messages during unification.
344−replaceAllTypeSynonyms :: (Functor m, MonadState CheckState m, MonadError String m) => (D.Data d) => d -> m d
345−replaceAllTypeSynonyms d = do
347− Just moduleName <- checkCurrentModule <$> get
348− let syns = map (\((path, name), (args, _)) -> ((path, name), length args)) . M.toList $ typeSynonyms env
349− either throwError return $ saturateAllTypeSynonyms env moduleName syns d
352−-- \"Desaturate\" @SaturatedTypeSynonym@s
354−desaturateAllTypeSynonyms :: (D.Data d) => d -> d
355−desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
357− replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
358− replaceSaturatedTypeSynonym t = t
361−-- Replace a type synonym and its arguments with the aliased type
363−expandTypeSynonym :: Qualified ProperName -> [Type] -> UnifyT Type Check Type
364−expandTypeSynonym name args = do
366− Just moduleName <- checkCurrentModule <$> get
367− case M.lookup (canonicalizeType moduleName env name) (typeSynonyms env) of
368− Just (synArgs, body) -> return $ replaceAllTypeVars (zip synArgs args) body
369− Nothing -> error "Type synonym was not defined"
372−-- Ensure a set of property names and value does not contain duplicate labels
374−ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
375−ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
378−-- Infer a type for a value, rethrowing any error to provide a more useful error message
380−infer :: Value -> UnifyT Type Check Value
381−infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
384−-- Infer a type for a value
386−infer' :: Value -> UnifyT Type Check Value
387−infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
388−infer' v@(StringLiteral _) = return $ TypedValue True v tyString
389−infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
390−infer' (ArrayLiteral vals) = do
391− ts <- mapM infer vals
393− forM_ ts $ \(TypedValue _ _ t) -> els =?= TypeApp tyArray t
394− return $ TypedValue True (ArrayLiteral ts) els
395−infer' (ObjectLiteral ps) = do
396− ensureNoDuplicateProperties ps
397− ts <- mapM (infer . snd) ps
398− let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
399− ty = Object $ rowFromList (fields, REmpty)
400− return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
401−infer' (ObjectUpdate o ps) = do
402− ensureNoDuplicateProperties ps
404− newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
405− let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
406− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
407− o' <- check o $ Object $ rowFromList (oldTys, row)
408− return $ TypedValue True (ObjectUpdate o' newVals) $ Object $ rowFromList (newTys, row)
409−infer' (Accessor prop val) = do
410− typed@(TypedValue _ _ objTy) <- infer val
411− propTy <- inferProperty objTy prop
416− _ <- subsumes Nothing objTy (Object (RCons prop field rest))
417− return $ TypedValue True (Accessor prop typed) field
418− Just ty -> return $ TypedValue True (Accessor prop typed) ty
419−infer' (Abs arg ret) = do
421− Just moduleName <- checkCurrentModule <$> get
422− bindLocalVariables moduleName [(arg, ty)] $ do
423− body@(TypedValue _ _ bodyTy) <- infer' ret
424− return $ TypedValue True (Abs arg body) $ function ty bodyTy
425−infer' (App f arg) = do
426− f'@(TypedValue _ _ ft) <- infer f
428− app <- checkFunctionApplication f' ft arg ret
429− return $ TypedValue True app ret
430−infer' (Var var) = do
431− Just moduleName <- checkCurrentModule <$> get
432− ty <- lookupVariable moduleName var
433− ty' <- replaceAllTypeSynonyms ty
435− ConstrainedType constraints _ -> do
437− dicts <- getTypeClassDictionaries
438− return $ TypedValue True (foldl App (Var var) (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))) ty'
439− _ -> return $ TypedValue True (Var var) ty'
440−infer' (Block ss) = do
442− (allCodePathsReturn, _, ss') <- checkBlock M.empty ret ss
443− guardWith "Block is missing a return statement" allCodePathsReturn
444− return $ TypedValue True (Block ss') ret
445−infer' v@(Constructor c) = do
447− Just moduleName <- checkCurrentModule <$> get
448− case M.lookup (qualify moduleName c) (dataConstructors env) of
449− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
450− Just (ty, _) -> do ty' <- replaceAllTypeSynonyms ty
451− return $ TypedValue True v ty'
452−infer' (Case vals binders) = do
453− ts <- mapM infer vals
455− binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
456− return $ TypedValue True (Case ts binders') ret
457−infer' (IfThenElse cond th el) = do
458− cond' <- check cond tyBoolean
459− v2@(TypedValue _ _ t2) <- infer th
460− v3@(TypedValue _ _ t3) <- infer el
462− return $ TypedValue True (IfThenElse cond' v2 v3) t2
463−infer' (TypedValue checkType val ty) = do
464− Just moduleName <- checkCurrentModule <$> get
465− kind <- liftCheck $ kindOf moduleName ty
466− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
467− ty' <- replaceAllTypeSynonyms ty
468− val' <- if checkType then check val ty' else return val
469− return $ TypedValue True val' ty
470−infer' _ = error "Invalid argument to infer"
473−-- Infer the type of a property inside a record with a given type
475−inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
476−inferProperty (Object row) prop = do
477− let (props, _) = rowToList row
478− return $ lookup prop props
479−inferProperty (SaturatedTypeSynonym name args) prop = do
480− replaced <- expandTypeSynonym name args
481− inferProperty replaced prop
482−inferProperty (ForAll ident ty) prop = do
483− replaced <- replaceVarWithUnknown ident ty
484− inferProperty replaced prop
485−inferProperty _ _ = return Nothing
488−-- Infer the types of variables brought into scope by a binder
490−inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
491−inferBinder _ NullBinder = return M.empty
492−inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
493−inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
494−inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
495−inferBinder val (VarBinder name) = return $ M.singleton name val
496−inferBinder val (NullaryBinder ctor) = do
498− Just moduleName <- checkCurrentModule <$> get
499− case M.lookup (qualify moduleName ctor) (dataConstructors env) of
501− _ <- subsumes Nothing ty val
503− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
504−inferBinder val (UnaryBinder ctor binder) = do
506− Just moduleName <- checkCurrentModule <$> get
507− case M.lookup (qualify moduleName ctor) (dataConstructors env) of
509− fn <- replaceAllVarsWithUnknowns ty
511− TypeApp (TypeApp t obj) ret | t == tyFunction -> do
512− _ <- subsumes Nothing val ret
513− inferBinder obj binder
514− _ -> throwError $ "Constructor " ++ show ctor ++ " is not a unary constructor"
515− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
516−inferBinder val (ObjectBinder props) = do
519− m1 <- inferRowProperties row rest props
523− inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
524− inferRowProperties nrow row [] = nrow =?= row >> return M.empty
525− inferRowProperties nrow row ((name, binder):binders) = do
527− m1 <- inferBinder propTy binder
528− m2 <- inferRowProperties nrow (RCons name propTy row) binders
529− return $ m1 `M.union` m2
530−inferBinder val (ArrayBinder binders) = do
532− m1 <- M.unions <$> mapM (inferBinder el) binders
533− val =?= TypeApp tyArray el
535−inferBinder val (ConsBinder headBinder tailBinder) = do
537− m1 <- inferBinder el headBinder
538− m2 <- inferBinder val tailBinder
539− val =?= TypeApp tyArray el
540− return $ m1 `M.union` m2
541−inferBinder val (NamedBinder name binder) = do
542− m <- inferBinder val binder
543− return $ M.insert name val m
546−-- Check the types of the return values in a set of binders in a case statement
548−checkBinders :: [Type] -> Type -> [([Binder], Maybe Guard, Value)] -> UnifyT Type Check [([Binder], Maybe Guard, Value)]
549−checkBinders _ _ [] = return []
550−checkBinders nvals ret ((binders, grd, val):bs) = do
551− Just moduleName <- checkCurrentModule <$> get
552− m1 <- M.unions <$> zipWithM inferBinder nvals binders
553− r <- bindLocalVariables moduleName (M.toList m1) $ do
554− val' <- check val ret
556− Nothing -> return (binders, Nothing, val')
558− g' <- check g tyBoolean
559− return (binders, Just g', val')
560− rs <- checkBinders nvals ret bs
564−-- Check that a local variable name is not already used
566−assignVariable :: Ident -> UnifyT Type Check ()
567−assignVariable name = do
568− env <- checkEnv <$> get
569− Just moduleName <- checkCurrentModule <$> get
570− case M.lookup (moduleName, name) (names env) of
571− Just _ -> UnifyT . lift . throwError $ "Variable with name " ++ show name ++ " already exists."
575−-- Check the type of the return values of a statement, returning whether or not the statement returns on
578−checkStatement :: M.Map Ident Type -> Type -> Statement -> UnifyT Type Check (Bool, M.Map Ident Type, Statement)
579−checkStatement mass _ (VariableIntroduction name val) = do
581− val'@(TypedValue _ _ t) <- infer val
582− return (False, M.insert name t mass, VariableIntroduction name val')
583−checkStatement mass _ (Assignment ident val) = do
584− val'@(TypedValue _ _ t) <- infer val
585− case M.lookup ident mass of
586− Nothing -> throwError $ "No local variable with name " ++ show ident
587− Just ty -> do t =?= ty
588− return (False, mass, Assignment ident val')
589−checkStatement mass ret (While val inner) = do
590− val' <- check val tyBoolean
591− (allCodePathsReturn, _, inner') <- checkBlock mass ret inner
592− return (allCodePathsReturn, mass, While val' inner')
593−checkStatement mass ret (If ifst) = do
594− (allCodePathsReturn, ifst') <- checkIfStatement mass ret ifst
595− return (allCodePathsReturn, mass, If ifst')
596−checkStatement mass ret (For ident start end inner) = do
597− Just moduleName <- checkCurrentModule <$> get
598− assignVariable ident
599− start' <- check start tyNumber
600− end' <- check end tyNumber
601− (allCodePathsReturn, _, inner') <- bindLocalVariables moduleName [(ident, tyNumber)] $ checkBlock mass ret inner
602− return (allCodePathsReturn, mass, For ident start' end' inner')
603−checkStatement mass ret (Return val) = do
604− val' <- check val ret
605− return (True, mass, Return val')
608−-- Check the type of an if-then-else statement
610−checkIfStatement :: M.Map Ident Type -> Type -> IfStatement -> UnifyT Type Check (Bool, IfStatement)
611−checkIfStatement mass ret (IfStatement val thens Nothing) = do
612− val' <- check val tyBoolean
613− (_, _, thens') <- checkBlock mass ret thens
614− return (False, IfStatement val' thens' Nothing)
615−checkIfStatement mass ret (IfStatement val thens (Just elses)) = do
616− val' <- check val tyBoolean
617− (allCodePathsReturn1, _, thens') <- checkBlock mass ret thens
618− (allCodePathsReturn2, elses') <- checkElseStatement mass ret elses
619− return (allCodePathsReturn1 && allCodePathsReturn2, IfStatement val' thens' (Just elses'))
622−-- Check the type of an else statement
624−checkElseStatement :: M.Map Ident Type -> Type -> ElseStatement -> UnifyT Type Check (Bool, ElseStatement)
625−checkElseStatement mass ret (Else elses) = do
626− (allCodePathsReturn, _, elses') <- checkBlock mass ret elses
627− return (allCodePathsReturn, Else elses')
628−checkElseStatement mass ret (ElseIf ifst) = (id *** ElseIf) <$> checkIfStatement mass ret ifst
631−-- Check the type of the return value of a block of statements
633−checkBlock :: M.Map Ident Type -> Type -> [Statement] -> UnifyT Type Check (Bool, M.Map Ident Type, [Statement])
634−checkBlock mass _ [] = return (False, mass, [])
635−checkBlock mass ret (s:ss) = do
636− Just moduleName <- checkCurrentModule <$> get
637− (b1, mass1, s') <- checkStatement mass ret s
638− bindLocalVariables moduleName (M.toList mass1) $ case (b1, ss) of
639− (True, []) -> return (True, mass1, [s'])
640− (True, _) -> throwError "Unreachable code"
642− (b, m, ss'') <- checkBlock mass1 ret ss'
643− return (b, m, s':ss'')
646−-- Skolemize a type variable by replacing its instances with fresh skolem constants
648−skolemize :: String -> Type -> UnifyT Type Check Type
649−skolemize ident ty = do
650− tsk <- Skolem . runUnknown <$> fresh'
651− return $ replaceTypeVars ident tsk ty
654−-- Check the type of a value, rethrowing errors to provide a better error message
656−check :: Value -> Type -> UnifyT Type Check Value
657−check val ty = rethrow errorMessage $ check' val ty
660− "Error checking type of term " ++
661− prettyPrintValue val ++
663− prettyPrintType ty ++
668−-- Check the type of a value
670−check' :: Value -> Type -> UnifyT Type Check Value
671−check' val (ForAll idents ty) = do
672− sk <- skolemize idents ty
674−check' val (ConstrainedType constraints ty) = do
676− Just moduleName <- checkCurrentModule <$> get
677− dictNames <- flip mapM constraints $ \(Qualified _ (ProperName className), _) -> do
678− n <- liftCheck freshDictionaryName
679− return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
680− val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
681− TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
682− (qualifyAllUnqualifiedNames moduleName env constraints)) $
684− return $ foldr Abs val' dictNames
685−check' val u@(TUnknown _) = do
686− val'@(TypedValue _ _ ty) <- infer val
687− -- Don't unify an unknown with an inferred polytype
688− ty' <- replaceAllVarsWithUnknowns ty
691−check' v@(NumericLiteral _) t | t == tyNumber = return v
692−check' v@(StringLiteral _) t | t == tyString = return v
693−check' v@(BooleanLiteral _) t | t == tyBoolean = return v
694−check' (ArrayLiteral vals) (TypeApp a ty) | a == tyArray = ArrayLiteral <$> forM vals (\val -> check val ty)
695−check' (Abs arg ret) (TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
696− Just moduleName <- checkCurrentModule <$> get
697− ret' <- bindLocalVariables moduleName [(arg, argTy)] $ check ret retTy
698− return $ Abs arg ret'
699−check' (App f arg) ret = do
700− f'@(TypedValue _ _ ft) <- infer f
701− app <- checkFunctionApplication f' ft arg ret
703−check' v@(Var var) ty = do
704− Just moduleName <- checkCurrentModule <$> get
705− ty1 <- lookupVariable moduleName var
706− repl <- replaceAllTypeSynonyms ty1
707− ty' <- replaceAllTypeSynonyms ty
708− v' <- subsumes (Just v) repl ty'
710− Nothing -> throwError "Unable to check type subsumption"
711− Just v'' -> return v''
712−check' (TypedValue checkType val ty1) ty2 = do
713− Just moduleName <- checkCurrentModule <$> get
714− kind <- liftCheck $ kindOf moduleName ty1
715− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
716− val' <- subsumes (Just val) ty1 ty2
718− Nothing -> throwError "Unable to check type subsumption"
720− val''' <- if checkType then check val'' ty1 else return val''
721− return $ TypedValue True val''' ty1
722−check' (Case vals binders) ret = do
723− vals' <- mapM infer vals
724− let ts = map (\(TypedValue _ _ t) -> t) vals'
725− binders' <- checkBinders ts ret binders
726− return $ Case vals' binders'
727−check' (IfThenElse cond th el) ty = do
728− cond' <- check cond tyBoolean
731− return $ IfThenElse cond' th' el'
732−check' (ObjectLiteral ps) (Object row) = do
733− ensureNoDuplicateProperties ps
734− ps' <- checkProperties ps row False
735− return $ ObjectLiteral ps'
736−check' (ObjectUpdate obj ps) (Object row) = do
737− ensureNoDuplicateProperties ps
738− us <- zip (map fst ps) <$> replicateM (length ps) fresh
739− let (propsToCheck, rest) = rowToList row
740− propsToRemove = map fst ps
741− remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
742− obj' <- check obj (Object (rowFromList (us ++ remainingProps, rest)))
743− ps' <- checkProperties ps row True
744− return $ ObjectUpdate obj' ps'
745−check' (Accessor prop val) ty = do
747− val' <- check val (Object (RCons prop ty rest))
748− return $ Accessor prop val'
749−check' (Block ss) ret = do
750− (allCodePathsReturn, _, ss') <- checkBlock M.empty ret ss
751− guardWith "Block is missing a return statement" allCodePathsReturn
753−check' (Constructor c) ty = do
755− Just moduleName <- checkCurrentModule <$> get
756− case M.lookup (qualify moduleName c) (dataConstructors env) of
757− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
759− repl <- replaceAllTypeSynonyms ty1
760− _ <- subsumes Nothing repl ty
761− return $ Constructor c
762−check' val (SaturatedTypeSynonym name args) = do
763− ty <- expandTypeSynonym name args
765−check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
768−-- Check the type of a collection of named record fields
770−-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
772−checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Type Check [(String, Value)]
773−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
774− go [] [] REmpty = return []
775− go [] [] u@(TUnknown _) = do u =?= REmpty
777− go [] [] (Skolem _) | lax = return []
778− go [] ((p, _): _) _ | lax = return []
779− | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
780− go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
781− go ((p,v):ps') [] u@(TUnknown _) = do
782− v'@(TypedValue _ _ ty) <- infer v
784− u =?= RCons p ty rest
785− ps'' <- go ps' [] rest
786− return $ (p, v') : ps''
787− go ((p,v):ps') ts r =
790− v'@(TypedValue _ _ ty) <- infer v
792− r =?= RCons p ty rest
793− ps'' <- go ps' ts rest
794− return $ (p, v') : ps''
797− ps'' <- go ps' (delete (p, ty) ts) r
798− return $ (p, v') : ps''
799− go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
802−-- Check the type of a function application, rethrowing errors to provide a better error message
804−checkFunctionApplication :: Value -> Type -> Value -> Type -> UnifyT Type Check Value
805−checkFunctionApplication fn fnTy arg ret = rethrow errorMessage $ checkFunctionApplication' fn fnTy arg ret
807− errorMessage msg = "Error applying function of type "
808− ++ prettyPrintType fnTy
809− ++ " to argument " ++ prettyPrintValue arg
813−-- Check the type of a function application
815−checkFunctionApplication' :: Value -> Type -> Value -> Type -> UnifyT Type Check Value
816−checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg ret = do
817− tyFunction' =?= tyFunction
818− arg' <- check arg argTy
819− _ <- subsumes Nothing retTy ret
820− return $ App fn arg'
821−checkFunctionApplication' fn (ForAll ident ty) arg ret = do
822− replaced <- replaceVarWithUnknown ident ty
823− checkFunctionApplication fn replaced arg ret
824−checkFunctionApplication' fn u@(TUnknown _) arg ret = do
826− TypedValue _ v t <- infer arg
827− TypedValue True v <$> replaceAllVarsWithUnknowns t
828− let ty = (\(TypedValue _ _ t) -> t) arg'
829− u =?= function ty ret
830− return $ App fn arg'
831−checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
832− ty <- expandTypeSynonym name tyArgs
833− checkFunctionApplication fn ty arg ret
834−checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
836− dicts <- getTypeClassDictionaries
837− Just moduleName <- checkCurrentModule <$> get
838− checkFunctionApplication' (foldl App fn (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))) fnTy arg ret
839−checkFunctionApplication' _ fnTy arg ret = throwError $ "Applying a function of type "
840− ++ prettyPrintType fnTy
841− ++ " to argument(s) " ++ prettyPrintValue arg
842− ++ " does not yield a value of type " ++ prettyPrintType ret ++ "."
845−-- Check whether one type subsumes another, rethrowing errors to provide a better error message
847−subsumes :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
848−subsumes val ty1 ty2 = rethrow errorMessage $ subsumes' val ty1 ty2
850− errorMessage msg = "Error checking that type "
851− ++ prettyPrintType ty1
852− ++ " subsumes type "
853− ++ prettyPrintType ty2
857−-- Check whether one type subsumes another
859−subsumes' :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
860−subsumes' val (ForAll ident ty1) ty2 = do
861− replaced <- replaceVarWithUnknown ident ty1
862− subsumes val replaced ty2
863−subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
864− subsumes Nothing arg2 arg1
865− subsumes Nothing ret1 ret2
867−subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
868− ty1 <- expandTypeSynonym name tyArgs
869− subsumes val ty1 ty2
870−subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
871− ty2 <- expandTypeSynonym name tyArgs
872− subsumes val ty1 ty2
873−subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
875− dicts <- getTypeClassDictionaries
876− Just moduleName <- checkCurrentModule <$> get
877− _ <- subsumes' Nothing ty1 ty2
878− return . Just $ foldl App val (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))
879−subsumes' val ty1 ty2 = do