@@ -1,753 +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
13−-----------------------------------------------------------------------------
15−{-# LANGUAGE DeriveDataTypeable, FlexibleContexts #-}
17−module Language.PureScript.TypeChecker.Types (
22−import Data.Maybe (isJust, fromMaybe)
24−import qualified Data.Data as D
26− (extT, something, everywhere, everywhereM, everything,
27− everywhereBut, mkT, mkM, mkQ, extM, extQ)
29−import Language.PureScript.Values
30−import Language.PureScript.Types
31−import Language.PureScript.Kinds
32−import Language.PureScript.Names
33−import Language.PureScript.TypeChecker.Monad
34−import Language.PureScript.TypeChecker.Kinds
35−import Language.PureScript.TypeChecker.Synonyms
36−import Language.PureScript.Pretty
37−import Language.PureScript.Unknown
39−import Control.Monad.State
40−import Control.Monad.Error
42−import Control.Applicative
43−import Control.Arrow (Arrow(..), Kleisli(..), (***), (&&&), second)
44−import qualified Control.Category as C
46−import qualified Data.Map as M
48−instance Unifiable Type where
50− isUnknown (TUnknown u) = Just u
51− isUnknown _ = Nothing
53− apply s (TUnknown u) = runSubstitution s u
54− apply s (SaturatedTypeSynonym name tys) = SaturatedTypeSynonym name $ map (apply s) tys
55− apply s (ForAll idents ty) = ForAll idents $ apply s ty
56− apply s (Array t) = Array (apply s t)
57− apply s (Object r) = Object (apply s r)
58− apply s (Function args ret) = Function (map (apply s) args) (apply s ret)
59− apply s (TypeApp t1 t2) = TypeApp (apply s t1) (apply s t2)
61− unknowns (TUnknown (Unknown u)) = [u]
62− unknowns (SaturatedTypeSynonym _ tys) = concatMap unknowns tys
63− unknowns (ForAll idents ty) = unknowns ty
64− unknowns (Array t) = unknowns t
65− unknowns (Object r) = unknowns r
66− unknowns (Function args ret) = concatMap unknowns args ++ unknowns ret
67− unknowns (TypeApp t1 t2) = unknowns t1 ++ unknowns t2
70−instance Unifiable Row where
72− isUnknown (RUnknown u) = Just u
73− isUnknown _ = Nothing
76− (s1, r1') = rowToList r1
77− (s2, r2') = rowToList r2
78− int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
79− sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
80− sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
82− forM_ int (uncurry (~~))
83− unifyRows sd1 r1' sd2 r2'
85− unifyRows :: [(String, Type)] -> Row -> [(String, Type)] -> Row -> Subst ()
86− unifyRows [] (RUnknown u) sd r = replace u (rowFromList (sd, r))
87− unifyRows sd r [] (RUnknown u) = replace u (rowFromList (sd, r))
88− unifyRows ns@((name, ty):row) r others u@(RUnknown un) = do
90− forM row $ \(_, ty) -> occursCheck un ty
92− u ~~ RCons name ty u'
93− unifyRows row r others u'
94− unifyRows [] REmpty [] REmpty = return ()
95− unifyRows [] (RowVar v1) [] (RowVar v2) | v1 == v2 = return ()
96− unifyRows [] (RSkolem s1) [] (RSkolem s2) | s1 == s2 = return ()
97− unifyRows sd1 r1 sd2 r2 = throwError $ "Cannot unify " ++ prettyPrintRow (rowFromList (sd1, r1)) ++ " with " ++ prettyPrintRow (rowFromList (sd2, r2)) ++ "."
98− apply s (RUnknown u) = runSubstitution s u
99− apply s (RCons name ty r) = RCons name (apply s ty) (apply s r)
101− unknowns (RUnknown (Unknown u)) = [u]
102− unknowns (RCons _ ty r) = unknowns ty ++ unknowns r
105−unifyTypes :: Type -> Type -> Subst ()
106−unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $ do
109− unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
110− unifyTypes' (TUnknown u) t = replace u t
111− unifyTypes' t (TUnknown u) = replace u t
112− unifyTypes' (SaturatedTypeSynonym name1 args1) (SaturatedTypeSynonym name2 args2)
113− | name1 == name2 = zipWithM_ unifyTypes args1 args2
114− unifyTypes' (SaturatedTypeSynonym name args) ty = do
115− ty1 <- expandTypeSynonym name args
117− unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
118− unifyTypes' (ForAll ident1 ty1) (ForAll ident2 ty2) = do
119− sk <- skolemize ident1 ty1
120− replaced <- replaceVarWithUnknown ident2 ty2
121− sk `unifyTypes` replaced
122− unifyTypes' (ForAll ident ty1) ty2 = do
123− sk <- skolemize ident ty1
125− unifyTypes' ty f@(ForAll _ _) = f `unifyTypes` ty
126− unifyTypes' Number Number = return ()
127− unifyTypes' String String = return ()
128− unifyTypes' Boolean Boolean = return ()
129− unifyTypes' (Array s) (Array t) = s `unifyTypes` t
130− unifyTypes' (Object row1) (Object row2) = row1 ~~ row2
131− unifyTypes' (Function args1 ret1) (Function args2 ret2) = do
132− guardWith "Function applied to incorrect number of args" $ length args1 == length args2
133− zipWithM_ unifyTypes args1 args2
134− ret1 `unifyTypes` ret2
135− unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
136− unifyTypes' (TypeConstructor c1) (TypeConstructor c2) = do
137− modulePath <- checkModulePath `fmap` get
138− guardWith ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".") (qualify modulePath c1 == qualify modulePath c2)
139− unifyTypes' (TypeApp t1 t2) (TypeApp t3 t4) = do
142− unifyTypes' (Skolem s1) (Skolem s2) | s1 == s2 = return ()
143− unifyTypes' t1 t2 = throwError $ "Cannot unify " ++ prettyPrintType t1 ++ " with " ++ prettyPrintType t2 ++ "."
145−isFunction :: Value -> Bool
146−isFunction (Abs _ _) = True
147−isFunction (TypedValue untyped _) = isFunction untyped
150−typeOf :: Maybe Ident -> Value -> Check Type
152− (ty, sub, checks) <- runSubst $ case name of
153− Just ident | isFunction val ->
155− TypedValue val ty -> do
156− kind <- liftCheck $ kindOf ty
157− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
158− ty' <- replaceAllTypeSynonyms ty
159− modulePath <- checkModulePath <$> get
160− bindNames (M.singleton (modulePath, ident) (ty, LocalVariable)) $ check val ty'
164− modulePath <- checkModulePath <$> get
165− ty <- bindNames (M.singleton (modulePath, ident) (me, LocalVariable)) $ infer val
169− escapeCheck checks ty sub
170− skolemEscapeCheck ty
171− return $ varIfUnknown $ desaturateAllTypeSynonyms $ setifyAll ty
173−escapeCheck :: [AnyUnifiable] -> Type -> Substitution -> Check ()
174−escapeCheck checks ty sub =
176− visibleUnknowns = nub $ unknowns ty
178− forM_ checks $ \check -> case check of
179− AnyUnifiable t -> do
180− let unsolvedUnknowns = nub . unknowns $ apply sub t
181− guardWith "Escape check fails" $ null $ unsolvedUnknowns \\ visibleUnknowns
183−skolemEscapeCheck :: Type -> Check ()
184−skolemEscapeCheck ty =
185− case something (extQ (mkQ Nothing findSkolems) findRSkolems) ty of
186− Nothing -> return ()
187− Just _ -> throwError "Skolem variables cannot escape. Consider adding a type signature."
189− findSkolems (Skolem _) = return ()
190− findSkolems _ = mzero
191− findRSkolems (RSkolem _) = return ()
192− findRSkolems _ = mzero
195−setify = rowFromList . first (M.toList . M.fromList) . rowToList
197−setifyAll :: (D.Data d) => d -> d
198−setifyAll = everywhere (mkT setify)
200−varIfUnknown :: Type -> Type
202− let unks = nub $ unknowns ty
203− toName = (:) 't' . show
204− ty' = everywhere (mkT rowToVar) . everywhere (mkT typeToVar) $ ty
205− typeToVar :: Type -> Type
206− typeToVar (TUnknown (Unknown u)) = TypeVar (toName u)
208− rowToVar :: Row -> Row
209− rowToVar (RUnknown (Unknown u)) = RowVar (toName u)
211− in mkForAll (sort . map toName $ unks) ty'
213−replaceAllTypeVars :: (D.Data d) => [(String, Type)] -> d -> d
214−replaceAllTypeVars = foldl' (\f (name, ty) -> replaceTypeVars name ty . f) id
216−replaceTypeVars :: (D.Data d) => String -> Type -> d -> d
217−replaceTypeVars name t = everywhereBut (mkQ False isShadowed) (mkT replace)
219− replace (TypeVar v) | v == name = t
221− isShadowed (ForAll v _) | v == name = True
222− isShadowed _ = False
224−replaceRowVars :: (D.Data d) => String -> Row -> d -> d
225−replaceRowVars name r = everywhere (mkT replace)
227− replace (RowVar v) | v == name = r
230−replaceAllVarsWithUnknowns :: Type -> Subst Type
231−replaceAllVarsWithUnknowns (ForAll ident ty) = replaceVarWithUnknown ident ty >>= replaceAllVarsWithUnknowns
232−replaceAllVarsWithUnknowns ty = return ty
234−replaceVarWithUnknown :: String -> Type -> Subst Type
235−replaceVarWithUnknown ident ty = do
238− return $ replaceRowVars ident ru . replaceTypeVars ident tu $ ty
240−replaceAllTypeSynonyms :: (Functor m, MonadState CheckState m, MonadError String m) => (D.Data d) => d -> m d
241−replaceAllTypeSynonyms d = do
243− let syns = map (\((path, name), (args, _)) -> (Qualified path name, length args)) . M.toList $ typeSynonyms env
244− either throwError return $ saturateAllTypeSynonyms syns d
246−desaturateAllTypeSynonyms :: (D.Data d) => d -> d
247−desaturateAllTypeSynonyms = everywhere (mkT replace)
249− replace (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
252−expandAllTypeSynonyms :: Type -> Subst Type
253−expandAllTypeSynonyms (SaturatedTypeSynonym name args) = expandTypeSynonym name args >>= expandAllTypeSynonyms
254−expandAllTypeSynonyms ty = return ty
256−expandTypeSynonym :: Qualified ProperName -> [Type] -> Subst Type
257−expandTypeSynonym name args = do
259− modulePath <- checkModulePath `fmap` get
260− case M.lookup (qualify modulePath name) (typeSynonyms env) of
261− Just (synArgs, body) -> return $ replaceAllTypeVars (zip synArgs args) body
262− Nothing -> error "Type synonym was not defined"
264−ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
265−ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
267−infer :: Value -> Subst Type
268−infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ do
273−infer' :: Value -> Subst Type
274−infer' (NumericLiteral _) = return Number
275−infer' (StringLiteral _) = return String
276−infer' (BooleanLiteral _) = return Boolean
277−infer' (ArrayLiteral vals) = do
278− ts <- mapM (infer) vals
280− forM_ ts $ \t -> arr ~~ Array t
282−infer' (Unary op val) = do
285−infer' (Binary op left right) = do
288− inferBinary op t1 t2
289−infer' (ObjectLiteral ps) = do
290− ensureNoDuplicateProperties ps
291− ts <- mapM (infer . snd) ps
292− let fields = zipWith (\(name, _) t -> (name, t)) ps ts
293− return $ Object $ rowFromList (fields, REmpty)
294−infer' (ObjectUpdate o ps) = do
295− ensureNoDuplicateProperties ps
297− newTys <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
298− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
299− check o $ Object $ rowFromList (oldTys, row)
300− return $ Object $ rowFromList (newTys, row)
301−infer' (Indexer index val) = do
304− check val (Array el)
306−infer' (Accessor prop val) = do
308− propTy <- inferProperty obj prop
313− obj `subsumes` Object (RCons prop field rest)
315− Just ty -> return ty
316−infer' (Abs args ret) = do
317− ts <- replicateM (length args) fresh
318− bindLocalVariables (zip args ts) $ do
320− return $ Function ts body
321−infer' app@(App _ _) = do
322− let (f, argss) = unfoldApplication app
325− checkFunctionApplications ft argss ret
327−infer' (Var var@(Qualified mp name)) = do
328− ty <- lookupVariable var
329− replaceAllTypeSynonyms ty
330−infer' (Block ss) = do
332− (allCodePathsReturn, _) <- checkBlock M.empty ret ss
333− guardWith "Block is missing a return statement" allCodePathsReturn
335−infer' (Constructor c) = do
337− modulePath <- checkModulePath `fmap` get
338− case M.lookup (qualify modulePath c) (dataConstructors env) of
339− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
340− Just ty -> replaceAllTypeSynonyms ty
341−infer' (Case val binders) = do
344− checkBinders t1 ret binders
346−infer' (IfThenElse cond th el) = do
352−infer' (TypedValue val ty) = do
353− kind <- liftCheck $ kindOf ty
354− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
355− ty' <- replaceAllTypeSynonyms ty
359−inferProperty :: Type -> String -> Subst (Maybe Type)
360−inferProperty (Object row) prop = do
361− let (props, _) = rowToList row
362− return $ lookup prop props
363−inferProperty (SaturatedTypeSynonym name args) prop = do
364− replaced <- expandTypeSynonym name args
365− inferProperty replaced prop
366−inferProperty (ForAll ident ty) prop = do
367− replaced <- replaceVarWithUnknown ident ty
368− inferProperty replaced prop
369−inferProperty _ prop = return Nothing
371−inferUnary :: UnaryOperator -> Type -> Subst Type
373− case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
374− (valTy, resTy) -> do
378−checkUnary :: UnaryOperator -> Value -> Type -> Subst ()
379−checkUnary op val res =
380− case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
381− (valTy, resTy) -> do
385−unaryOps :: [(UnaryOperator, (Type, Type))]
386−unaryOps = [ (Negate, (Number, Number))
387− , (Not, (Boolean, Boolean))
388− , (BitwiseNot, (Number, Number))
391−inferBinary :: BinaryOperator -> Type -> Type -> Subst Type
392−inferBinary op left right | isEqualityTest op = do
395−inferBinary op left right =
396− case fromMaybe (error "Invalid operator") $ lookup op binaryOps of
397− (valTy, resTy) -> do
402−checkBinary :: BinaryOperator -> Value -> Value -> Type -> Subst ()
403−checkBinary op left right res | isEqualityTest op = do
408−checkBinary op left right res =
409− case fromMaybe (error "Invalid operator") $ lookup op binaryOps of
410− (valTy, resTy) -> do
415−isEqualityTest :: BinaryOperator -> Bool
416−isEqualityTest EqualTo = True
417−isEqualityTest NotEqualTo = True
418−isEqualityTest _ = False
420−binaryOps :: [(BinaryOperator, (Type, Type))]
421−binaryOps = [ (Add, (Number, Number))
422− , (Subtract, (Number, Number))
423− , (Multiply, (Number, Number))
424− , (Divide, (Number, Number))
425− , (Modulus, (Number, Number))
426− , (BitwiseAnd, (Number, Number))
427− , (BitwiseOr, (Number, Number))
428− , (BitwiseXor, (Number, Number))
429− , (ShiftRight, (Number, Number))
430− , (ZeroFillShiftRight, (Number, Number))
431− , (And, (Boolean, Boolean))
432− , (Or, (Boolean, Boolean))
433− , (Concat, (String, String))
434− , (Modulus, (Number, Number))
435− , (LessThan, (Number, Boolean))
436− , (LessThanOrEqualTo, (Number, Boolean))
437− , (GreaterThan, (Number, Boolean))
438− , (GreaterThanOrEqualTo, (Number, Boolean))
441−inferBinder :: Type -> Binder -> Subst (M.Map Ident Type)
442−inferBinder _ NullBinder = return M.empty
443−inferBinder val (StringBinder _) = val ~~ String >> return M.empty
444−inferBinder val (NumberBinder _) = val ~~ Number >> return M.empty
445−inferBinder val (BooleanBinder _) = val ~~ Boolean >> return M.empty
446−inferBinder val (VarBinder name) = return $ M.singleton name val
447−inferBinder val (NullaryBinder ctor) = do
449− modulePath <- checkModulePath <$> get
450− case M.lookup (qualify modulePath ctor) (dataConstructors env) of
454− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
455−inferBinder val (UnaryBinder ctor binder) = do
457− modulePath <- checkModulePath <$> get
458− case M.lookup (qualify modulePath ctor) (dataConstructors env) of
460− Function [obj] ret <- replaceAllVarsWithUnknowns ty
462− inferBinder obj binder
463− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
464−inferBinder val (ObjectBinder props) = do
467− m1 <- inferRowProperties row rest props
471− inferRowProperties :: Row -> Row -> [(String, Binder)] -> Subst (M.Map Ident Type)
472− inferRowProperties nrow row [] = nrow ~~ row >> return M.empty
473− inferRowProperties nrow row ((name, binder):binders) = do
475− m1 <- inferBinder propTy binder
476− m2 <- inferRowProperties nrow (RCons name propTy row) binders
477− return $ m1 `M.union` m2
478−inferBinder val (ArrayBinder binders rest) = do
480− m1 <- M.unions <$> mapM (inferBinder el) binders
483− Nothing -> return m1
485− m2 <- inferBinder val binder
486− return $ m1 `M.union` m2
487−inferBinder val (NamedBinder name binder) = do
488− m <- inferBinder val binder
489− return $ M.insert name val m
491−inferGuardedBinder :: Type -> Binder -> Subst (M.Map Ident Type)
492−inferGuardedBinder val (GuardedBinder cond binder) = do
493− m1 <- inferBinder val binder
494− bindLocalVariables (M.toList m1) $ check cond Boolean
496−inferGuardedBinder val b = inferBinder val b
498−checkBinders :: Type -> Type -> [(Binder, Value)] -> Subst ()
499−checkBinders _ _ [] = return ()
500−checkBinders nval ret ((binder, val):bs) = do
501− m1 <- inferGuardedBinder nval binder
502− bindLocalVariables (M.toList m1) $ check val ret
503− checkBinders nval ret bs
505−assignVariable :: Ident -> Subst ()
506−assignVariable name = do
507− env <- checkEnv <$> get
508− modulePath <- checkModulePath <$> get
509− case M.lookup (modulePath, name) (names env) of
510− Just (_, LocalVariable) -> throwError $ "Variable with name " ++ show name ++ " already exists."
513−checkStatement :: M.Map Ident Type -> Type -> Statement -> Subst (Bool, M.Map Ident Type)
514−checkStatement mass ret (VariableIntroduction name val) = do
517− return (False, M.insert name t mass)
518−checkStatement mass ret (Assignment ident val) = do
520− case M.lookup ident mass of
521− Nothing -> throwError $ "No local variable with name " ++ show ident
522− Just ty -> do t ~~ ty
523− return (False, mass)
524−checkStatement mass ret (While val inner) = do
526− (allCodePathsReturn, _) <- checkBlock mass ret inner
527− return (allCodePathsReturn, mass)
528−checkStatement mass ret (If ifst) = do
529− allCodePathsReturn <- checkIfStatement mass ret ifst
530− return (allCodePathsReturn, mass)
531−checkStatement mass ret (For ident start end inner) = do
532− assignVariable ident
535− (allCodePathsReturn, _) <- bindLocalVariables [(ident, Number)] $ checkBlock mass ret inner
536− return (allCodePathsReturn, mass)
537−checkStatement mass ret (ForEach ident vals inner) = do
538− assignVariable ident
540− check vals (Array val)
541− (allCodePathsReturn, _) <- bindLocalVariables [(ident, val)] $ checkBlock mass ret inner
542− guardWith "Cannot return from within a foreach block" $ not allCodePathsReturn
543− return (False, mass)
544−checkStatement mass ret (Return val) = do
548−checkIfStatement :: M.Map Ident Type -> Type -> IfStatement -> Subst Bool
549−checkIfStatement mass ret (IfStatement val thens Nothing) = do
551− _ <- checkBlock mass ret thens
553−checkIfStatement mass ret (IfStatement val thens (Just elses)) = do
555− (allCodePathsReturn1, _) <- checkBlock mass ret thens
556− allCodePathsReturn2 <- checkElseStatement mass ret elses
557− return $ allCodePathsReturn1 && allCodePathsReturn2
559−checkElseStatement :: M.Map Ident Type -> Type -> ElseStatement -> Subst Bool
560−checkElseStatement mass ret (Else elses) = fst <$> checkBlock mass ret elses
561−checkElseStatement mass ret (ElseIf ifst) = checkIfStatement mass ret ifst
563−checkBlock :: M.Map Ident Type -> Type -> [Statement] -> Subst (Bool, M.Map Ident Type)
564−checkBlock mass _ [] = return (False, mass)
565−checkBlock mass ret (s:ss) = do
566− (b1, mass1) <- checkStatement mass ret s
567− bindLocalVariables (M.toList mass1) $ case (b1, ss) of
568− (True, []) -> return (True, mass1)
569− (True, _) -> throwError "Unreachable code"
570− (False, ss) -> checkBlock mass1 ret ss
572−skolemize :: String -> Type -> Subst Type
573−skolemize ident ty = do
574− tsk <- Skolem <$> fresh'
575− rsk <- RSkolem <$> fresh'
576− return $ replaceRowVars ident rsk $ replaceTypeVars ident tsk ty
578−check :: Value -> Type -> Subst ()
579−check val ty = rethrow errorMessage $ check' val ty
582− "Error checking type of term " ++
583− prettyPrintValue val ++
585− prettyPrintType ty ++
589−check' :: Value -> Type -> Subst ()
590−check' val (ForAll idents ty) = do
591− sk <- skolemize idents ty
593−check' val u@(TUnknown _) = do
595− -- Don't unify an unknown with an inferred polytype
596− ty' <- replaceAllVarsWithUnknowns ty
598−check' (NumericLiteral _) Number = return ()
599−check' (StringLiteral _) String = return ()
600−check' (BooleanLiteral _) Boolean = return ()
601−check' (Unary op val) ty = checkUnary op val ty
602−check' (Binary op left right) ty = checkBinary op left right ty
603−check' (ArrayLiteral vals) (Array ty) = forM_ vals (\val -> check val ty)
604−check' (Indexer index vals) ty = check index Number >> check vals (Array ty)
605−check' (Abs args ret) (Function argTys retTy) = do
606− guardWith "Incorrect number of function arguments" (length args == length argTys)
607− bindLocalVariables (zip args argTys) $ check ret retTy
608−check' app@(App _ _) ret = do
609− let (f, argss) = unfoldApplication app
611− checkFunctionApplications ft argss ret
612−check' v@(Var var@(Qualified mp name)) ty = do
613− ty1 <- lookupVariable var
614− repl <- replaceAllTypeSynonyms ty1
616−check' (TypedValue val ty1) ty2 = do
617− kind <- liftCheck $ kindOf ty1
618− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
621−check' (Case val binders) ret = do
623− checkBinders t1 ret binders
624−check' (IfThenElse cond th el) ty = do
628−check' (ObjectLiteral ps) (Object row) = do
629− ensureNoDuplicateProperties ps
630− checkProperties ps row False
631−check' (ObjectUpdate obj ps) (Object row) = do
632− ensureNoDuplicateProperties ps
633− us <- zip (map fst ps) <$> replicateM (length ps) fresh
634− let (propsToCheck, rest) = rowToList row
635− propsToRemove = map fst ps
636− remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
637− check obj (Object (rowFromList (us ++ remainingProps, rest)))
638− checkProperties ps row True
639−check' (Accessor prop val) ty = do
641− check val (Object (RCons prop ty rest))
642−check' (Block ss) ret = do
643− (allCodePathsReturn, _) <- checkBlock M.empty ret ss
644− guardWith "Block is missing a return statement" allCodePathsReturn
645−check' (Constructor c) ty = do
647− modulePath <- checkModulePath <$> get
648− case M.lookup (qualify modulePath c) (dataConstructors env) of
649− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
651− repl <- replaceAllTypeSynonyms ty1
653−check' val (SaturatedTypeSynonym name args) = do
654− ty <- expandTypeSynonym name args
656−check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
658−checkProperties :: [(String, Value)] -> Row -> Bool -> Subst ()
659−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
660− go [] [] REmpty = return ()
661− go [] [] u@(RUnknown _) = u ~~ REmpty
662− go [] [] (RSkolem _) | lax = return ()
663− go [] ((p, _): _) _ | lax = return ()
664− | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
665− go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
666− go ((p,v):ps) [] u@(RUnknown _) = do
669− u ~~ RCons p ty rest
671− go ((p,v):ps) ts r =
676− r ~~ RCons p ty rest
680− go ps (delete (p, ty) ts) r
681− go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
683−unfoldApplication :: Value -> (Value, [[Value]])
684−unfoldApplication = go []
686− go argss (App f args) = go (args:argss) f
687− go argss f = (f, argss)
689−checkFunctionApplications :: Type -> [[Value]] -> Type -> Subst ()
690−checkFunctionApplications _ [] _ = error "Nullary function application"
691−checkFunctionApplications fnTy [args] ret = checkFunctionApplication fnTy args ret
692−checkFunctionApplications fnTy (args:argss) ret = do
693− argTys <- mapM (infer) args
694− f <- inferFunctionApplication fnTy argTys
695− checkFunctionApplications f argss ret
697−checkFunctionApplication :: Type -> [Value] -> Type -> Subst ()
698−checkFunctionApplication fnTy args ret = rethrow errorMessage $ checkFunctionApplication' fnTy args ret
700− errorMessage msg = "Error applying function of type "
701− ++ prettyPrintType fnTy
702− ++ " to arguments " ++ intercalate ", " (map prettyPrintValue args)
703− ++ ", expecting value of type "
704− ++ prettyPrintType ret ++ ":\n" ++ msg
706−inferFunctionApplication :: Type -> [Type] -> Subst Type
707−inferFunctionApplication (Function argTys retTy) args = do
708− guardWith "Incorrect number of function arguments" (length args == length argTys)
709− zipWithM subsumes args argTys
711−inferFunctionApplication (ForAll ident ty) args = do
712− replaced <- replaceVarWithUnknown ident ty
713− inferFunctionApplication replaced args
714−inferFunctionApplication u@(TUnknown _) args = do
716− args' <- mapM replaceAllVarsWithUnknowns args
717− u ~~ Function args' ret
719−inferFunctionApplication (SaturatedTypeSynonym name tyArgs) args = do
720− ty <- expandTypeSynonym name tyArgs
721− inferFunctionApplication ty args
722−inferFunctionApplication fnTy args = throwError $ "Cannot apply function of type "
723− ++ prettyPrintType fnTy
724− ++ " to argument(s) of type(s) " ++ intercalate ", " (map prettyPrintType args)
726−checkFunctionApplication' :: Type -> [Value] -> Type -> Subst ()
727−checkFunctionApplication' (Function argTys retTy) args ret = do
728− guardWith "Incorrect number of function arguments" (length args == length argTys)
729− zipWithM (check) args argTys
730− retTy `subsumes` ret
731−checkFunctionApplication' (ForAll ident ty) args ret = do
732− replaced <- replaceVarWithUnknown ident ty
733− checkFunctionApplication replaced args ret
734−checkFunctionApplication' u@(TUnknown _) args ret = do
735− tyArgs <- mapM (\arg -> infer arg >>= replaceAllVarsWithUnknowns) args
736− u ~~ Function tyArgs ret
737−checkFunctionApplication' (SaturatedTypeSynonym name tyArgs) args ret = do
738− ty <- expandTypeSynonym name tyArgs
739− checkFunctionApplication' ty args ret
740−checkFunctionApplication' fnTy args ret = throwError $ "Applying a function of type "
741− ++ prettyPrintType fnTy
742− ++ " to argument(s) " ++ intercalate ", " (map prettyPrintValue args)
743− ++ " does not yield a value of type " ++ prettyPrintType ret ++ "."
745−subsumes :: Type -> Type -> Subst ()
746−subsumes (ForAll ident ty1) ty2 = do
747− replaced <- replaceVarWithUnknown ident ty1
748− replaced `subsumes` ty2
749−subsumes (Function args1 ret1) (Function args2 ret2) = do
750− zipWithM subsumes args2 args1
751− ret1 `subsumes` ret2
752−subsumes ty1 ty2 = ty1 ~~ ty2