@@ -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 (fromMaybe)
23−import qualified Data.Data as D
25− (mkT, something, everywhere, everywhereBut, mkQ, extQ)
27−import Language.PureScript.Values
28−import Language.PureScript.Types
29−import Language.PureScript.Kinds
30−import Language.PureScript.Names
31−import Language.PureScript.TypeChecker.Monad
32−import Language.PureScript.TypeChecker.Kinds
33−import Language.PureScript.TypeChecker.Synonyms
34−import Language.PureScript.Pretty
35−import Language.PureScript.Unknown
37−import Control.Monad.State
38−import Control.Monad.Error
40−import Control.Applicative
41−import Control.Arrow (Arrow(..))
43−import qualified Data.Map as M
45−instance Unifiable Type where
47− isUnknown (TUnknown u) = Just u
48− isUnknown _ = Nothing
50− apply s (TUnknown u) = runSubstitution s u
51− apply s (SaturatedTypeSynonym name tys) = SaturatedTypeSynonym name $ map (apply s) tys
52− apply s (ForAll idents ty) = ForAll idents $ apply s ty
53− apply s (Array t) = Array (apply s t)
54− apply s (Object r) = Object (apply s r)
55− apply s (Function args ret) = Function (map (apply s) args) (apply s ret)
56− apply s (TypeApp t1 t2) = TypeApp (apply s t1) (apply s t2)
58− unknowns (TUnknown (Unknown u)) = [u]
59− unknowns (SaturatedTypeSynonym _ tys) = concatMap unknowns tys
60− unknowns (ForAll _ ty) = unknowns ty
61− unknowns (Array t) = unknowns t
62− unknowns (Object r) = unknowns r
63− unknowns (Function args ret) = concatMap unknowns args ++ unknowns ret
64− unknowns (TypeApp t1 t2) = unknowns t1 ++ unknowns t2
67−instance Unifiable Row where
69− isUnknown (RUnknown u) = Just u
70− isUnknown _ = Nothing
73− (s1, r1') = rowToList r1
74− (s2, r2') = rowToList r2
75− int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
76− sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
77− sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
79− forM_ int (uncurry (~~))
80− unifyRows sd1 r1' sd2 r2'
82− unifyRows :: [(String, Type)] -> Row -> [(String, Type)] -> Row -> Subst ()
83− unifyRows [] (RUnknown u) sd r = replace u (rowFromList (sd, r))
84− unifyRows sd r [] (RUnknown u) = replace u (rowFromList (sd, r))
85− unifyRows ((name, ty):row) r others u@(RUnknown un) = do
87− forM row $ \(_, t) -> occursCheck un t
89− u ~~ RCons name ty u'
90− unifyRows row r others u'
91− unifyRows [] REmpty [] REmpty = return ()
92− unifyRows [] (RowVar v1) [] (RowVar v2) | v1 == v2 = return ()
93− unifyRows [] (RSkolem s1) [] (RSkolem s2) | s1 == s2 = return ()
94− unifyRows sd3 r3 sd4 r4 = throwError $ "Cannot unify " ++ prettyPrintRow (rowFromList (sd3, r3)) ++ " with " ++ prettyPrintRow (rowFromList (sd4, r4)) ++ "."
95− apply s (RUnknown u) = runSubstitution s u
96− apply s (RCons name ty r) = RCons name (apply s ty) (apply s r)
98− unknowns (RUnknown (Unknown u)) = [u]
99− unknowns (RCons _ ty r) = unknowns ty ++ unknowns r
102−unifyTypes :: Type -> Type -> Subst ()
103−unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $ do
106− unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
107− unifyTypes' (TUnknown u) t = replace u t
108− unifyTypes' t (TUnknown u) = replace u t
109− unifyTypes' (SaturatedTypeSynonym name1 args1) (SaturatedTypeSynonym name2 args2)
110− | name1 == name2 = zipWithM_ unifyTypes args1 args2
111− unifyTypes' (SaturatedTypeSynonym name args) ty = do
112− ty1 <- expandTypeSynonym name args
114− unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
115− unifyTypes' (ForAll ident1 ty1) (ForAll ident2 ty2) = do
116− sk <- skolemize ident1 ty1
117− replaced <- replaceVarWithUnknown ident2 ty2
118− sk `unifyTypes` replaced
119− unifyTypes' (ForAll ident ty1) ty2 = do
120− sk <- skolemize ident ty1
122− unifyTypes' ty f@(ForAll _ _) = f `unifyTypes` ty
123− unifyTypes' Number Number = return ()
124− unifyTypes' String String = return ()
125− unifyTypes' Boolean Boolean = return ()
126− unifyTypes' (Array s) (Array t) = s `unifyTypes` t
127− unifyTypes' (Object row1) (Object row2) = row1 ~~ row2
128− unifyTypes' (Function args1 ret1) (Function args2 ret2) = do
129− guardWith "Function applied to incorrect number of args" $ length args1 == length args2
130− zipWithM_ unifyTypes args1 args2
131− ret1 `unifyTypes` ret2
132− unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
133− unifyTypes' (TypeConstructor c1) (TypeConstructor c2) = do
134− modulePath <- checkModulePath `fmap` get
135− guardWith ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".") (qualify modulePath c1 == qualify modulePath c2)
136− unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
139− unifyTypes' (Skolem s1) (Skolem s2) | s1 == s2 = return ()
140− unifyTypes' t3 t4 = throwError $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
142−isFunction :: Value -> Bool
143−isFunction (Abs _ _) = True
144−isFunction (TypedValue untyped _) = isFunction untyped
147−typeOf :: Maybe Ident -> Value -> Check Type
149− (ty, sub, checks) <- runSubst $ case name of
150− Just ident | isFunction val ->
152− TypedValue value ty -> do
153− kind <- liftCheck $ kindOf ty
154− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
155− ty' <- replaceAllTypeSynonyms ty
156− modulePath <- checkModulePath <$> get
157− bindNames (M.singleton (modulePath, ident) (ty, LocalVariable)) $ check value ty'
161− modulePath <- checkModulePath <$> get
162− ty <- bindNames (M.singleton (modulePath, ident) (me, LocalVariable)) $ infer val
166− escapeCheck checks ty sub
167− skolemEscapeCheck ty
168− return $ varIfUnknown $ desaturateAllTypeSynonyms $ setifyAll ty
170−escapeCheck :: [AnyUnifiable] -> Type -> Substitution -> Check ()
171−escapeCheck checks ty sub =
173− visibleUnknowns = nub $ unknowns ty
175− forM_ checks $ \c -> case c of
176− AnyUnifiable t -> do
177− let unsolvedUnknowns = nub . unknowns $ apply sub t
178− guardWith "Escape check fails" $ null $ unsolvedUnknowns \\ visibleUnknowns
180−skolemEscapeCheck :: Type -> Check ()
181−skolemEscapeCheck ty =
182− case something (extQ (mkQ Nothing findSkolems) findRSkolems) ty of
183− Nothing -> return ()
184− Just _ -> throwError "Skolem variables cannot escape. Consider adding a type signature."
186− findSkolems (Skolem _) = return ()
187− findSkolems _ = mzero
188− findRSkolems (RSkolem _) = return ()
189− findRSkolems _ = mzero
192−setify = rowFromList . first (M.toList . M.fromList) . rowToList
194−setifyAll :: (D.Data d) => d -> d
195−setifyAll = everywhere (mkT setify)
197−varIfUnknown :: Type -> Type
199− let unks = nub $ unknowns ty
200− toName = (:) 't' . show
201− ty' = everywhere (mkT rowToVar) . everywhere (mkT typeToVar) $ ty
202− typeToVar :: Type -> Type
203− typeToVar (TUnknown (Unknown u)) = TypeVar (toName u)
205− rowToVar :: Row -> Row
206− rowToVar (RUnknown (Unknown u)) = RowVar (toName u)
208− in mkForAll (sort . map toName $ unks) ty'
210−replaceAllTypeVars :: (D.Data d) => [(String, Type)] -> d -> d
211−replaceAllTypeVars = foldl' (\f (name, ty) -> replaceTypeVars name ty . f) id
213−replaceTypeVars :: (D.Data d) => String -> Type -> d -> d
214−replaceTypeVars name t = everywhereBut (mkQ False isShadowed) (mkT replaceTypeVar)
216− replaceTypeVar (TypeVar v) | v == name = t
217− replaceTypeVar other = other
218− isShadowed (ForAll v _) | v == name = True
219− isShadowed _ = False
221−replaceRowVars :: (D.Data d) => String -> Row -> d -> d
222−replaceRowVars name r = everywhere (mkT replaceRowVar)
224− replaceRowVar (RowVar v) | v == name = r
225− replaceRowVar other = other
227−replaceAllVarsWithUnknowns :: Type -> Subst Type
228−replaceAllVarsWithUnknowns (ForAll ident ty) = replaceVarWithUnknown ident ty >>= replaceAllVarsWithUnknowns
229−replaceAllVarsWithUnknowns ty = return ty
231−replaceVarWithUnknown :: String -> Type -> Subst Type
232−replaceVarWithUnknown ident ty = do
235− return $ replaceRowVars ident ru . replaceTypeVars ident tu $ ty
237−replaceAllTypeSynonyms :: (Functor m, MonadState CheckState m, MonadError String m) => (D.Data d) => d -> m d
238−replaceAllTypeSynonyms d = do
240− let syns = map (\((path, name), (args, _)) -> (Qualified path name, length args)) . M.toList $ typeSynonyms env
241− either throwError return $ saturateAllTypeSynonyms syns d
243−desaturateAllTypeSynonyms :: (D.Data d) => d -> d
244−desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
246− replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
247− replaceSaturatedTypeSynonym t = t
249−expandTypeSynonym :: Qualified ProperName -> [Type] -> Subst Type
250−expandTypeSynonym name args = do
252− modulePath <- checkModulePath `fmap` get
253− case M.lookup (qualify modulePath name) (typeSynonyms env) of
254− Just (synArgs, body) -> return $ replaceAllTypeVars (zip synArgs args) body
255− Nothing -> error "Type synonym was not defined"
257−ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
258−ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
260−infer :: Value -> Subst Type
261−infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ do
266−infer' :: Value -> Subst Type
267−infer' (NumericLiteral _) = return Number
268−infer' (StringLiteral _) = return String
269−infer' (BooleanLiteral _) = return Boolean
270−infer' (ArrayLiteral vals) = do
271− ts <- mapM (infer) vals
273− forM_ ts $ \t -> els ~~ Array t
275−infer' (Unary op val) = do
278−infer' (Binary op left right) = do
281− inferBinary op t1 t2
282−infer' (ObjectLiteral ps) = do
283− ensureNoDuplicateProperties ps
284− ts <- mapM (infer . snd) ps
285− let fields = zipWith (\(name, _) t -> (name, t)) ps ts
286− return $ Object $ rowFromList (fields, REmpty)
287−infer' (ObjectUpdate o ps) = do
288− ensureNoDuplicateProperties ps
290− newTys <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
291− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
292− check o $ Object $ rowFromList (oldTys, row)
293− return $ Object $ rowFromList (newTys, row)
294−infer' (Indexer index val) = do
297− check val (Array el)
299−infer' (Accessor prop val) = do
301− propTy <- inferProperty obj prop
306− obj `subsumes` Object (RCons prop field rest)
308− Just ty -> return ty
309−infer' (Abs args ret) = do
310− ts <- replicateM (length args) fresh
311− bindLocalVariables (zip args ts) $ do
313− return $ Function ts body
314−infer' app@(App _ _) = do
315− let (f, argss) = unfoldApplication app
318− checkFunctionApplications ft argss ret
320−infer' (Var var) = do
321− ty <- lookupVariable var
322− replaceAllTypeSynonyms ty
323−infer' (Block ss) = do
325− (allCodePathsReturn, _) <- checkBlock M.empty ret ss
326− guardWith "Block is missing a return statement" allCodePathsReturn
328−infer' (Constructor c) = do
330− modulePath <- checkModulePath `fmap` get
331− case M.lookup (qualify modulePath c) (dataConstructors env) of
332− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
333− Just ty -> replaceAllTypeSynonyms ty
334−infer' (Case vals binders) = do
335− ts <- mapM infer vals
337− checkBinders ts ret binders
339−infer' (IfThenElse cond th el) = do
345−infer' (TypedValue val ty) = do
346− kind <- liftCheck $ kindOf ty
347− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
348− ty' <- replaceAllTypeSynonyms ty
351−infer' _ = error "Invalid argument to infer"
353−inferProperty :: Type -> String -> Subst (Maybe Type)
354−inferProperty (Object row) prop = do
355− let (props, _) = rowToList row
356− return $ lookup prop props
357−inferProperty (SaturatedTypeSynonym name args) prop = do
358− replaced <- expandTypeSynonym name args
359− inferProperty replaced prop
360−inferProperty (ForAll ident ty) prop = do
361− replaced <- replaceVarWithUnknown ident ty
362− inferProperty replaced prop
363−inferProperty _ _ = return Nothing
365−inferUnary :: UnaryOperator -> Type -> Subst Type
367− case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
368− (valTy, resTy) -> do
372−checkUnary :: UnaryOperator -> Value -> Type -> Subst ()
373−checkUnary op val res =
374− case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
375− (valTy, resTy) -> do
379−unaryOps :: [(UnaryOperator, (Type, Type))]
380−unaryOps = [ (Negate, (Number, Number))
381− , (Not, (Boolean, Boolean))
382− , (BitwiseNot, (Number, Number))
385−inferBinary :: BinaryOperator -> Type -> Type -> Subst Type
386−inferBinary op left right | isEqualityTest op = do
389−inferBinary op left right =
390− case fromMaybe (error "Invalid operator") $ lookup op binaryOps of
391− (valTy, resTy) -> do
396−checkBinary :: BinaryOperator -> Value -> Value -> Type -> Subst ()
397−checkBinary op left right res | isEqualityTest op = do
402−checkBinary op left right res =
403− case fromMaybe (error "Invalid operator") $ lookup op binaryOps of
404− (valTy, resTy) -> do
409−isEqualityTest :: BinaryOperator -> Bool
410−isEqualityTest EqualTo = True
411−isEqualityTest NotEqualTo = True
412−isEqualityTest _ = False
414−binaryOps :: [(BinaryOperator, (Type, Type))]
415−binaryOps = [ (Add, (Number, Number))
416− , (Subtract, (Number, Number))
417− , (Multiply, (Number, Number))
418− , (Divide, (Number, Number))
419− , (Modulus, (Number, Number))
420− , (BitwiseAnd, (Number, Number))
421− , (BitwiseOr, (Number, Number))
422− , (BitwiseXor, (Number, Number))
423− , (ShiftRight, (Number, Number))
424− , (ZeroFillShiftRight, (Number, Number))
425− , (And, (Boolean, Boolean))
426− , (Or, (Boolean, Boolean))
427− , (Concat, (String, String))
428− , (Modulus, (Number, Number))
429− , (LessThan, (Number, Boolean))
430− , (LessThanOrEqualTo, (Number, Boolean))
431− , (GreaterThan, (Number, Boolean))
432− , (GreaterThanOrEqualTo, (Number, Boolean))
435−inferBinder :: Type -> Binder -> Subst (M.Map Ident Type)
436−inferBinder _ NullBinder = return M.empty
437−inferBinder val (StringBinder _) = val ~~ String >> return M.empty
438−inferBinder val (NumberBinder _) = val ~~ Number >> return M.empty
439−inferBinder val (BooleanBinder _) = val ~~ Boolean >> return M.empty
440−inferBinder val (VarBinder name) = return $ M.singleton name val
441−inferBinder val (NullaryBinder ctor) = do
443− modulePath <- checkModulePath <$> get
444− case M.lookup (qualify modulePath ctor) (dataConstructors env) of
448− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
449−inferBinder val (UnaryBinder ctor binder) = do
451− modulePath <- checkModulePath <$> get
452− case M.lookup (qualify modulePath ctor) (dataConstructors env) of
454− fn <- replaceAllVarsWithUnknowns ty
456− Function [obj] ret -> do
458− inferBinder obj binder
459− _ -> throwError $ "Constructor " ++ show ctor ++ " is not a unary constructor"
460− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
461−inferBinder val (ObjectBinder props) = do
464− m1 <- inferRowProperties row rest props
468− inferRowProperties :: Row -> Row -> [(String, Binder)] -> Subst (M.Map Ident Type)
469− inferRowProperties nrow row [] = nrow ~~ row >> return M.empty
470− inferRowProperties nrow row ((name, binder):binders) = do
472− m1 <- inferBinder propTy binder
473− m2 <- inferRowProperties nrow (RCons name propTy row) binders
474− return $ m1 `M.union` m2
475−inferBinder val (ArrayBinder binders) = do
477− m1 <- M.unions <$> mapM (inferBinder el) binders
480−inferBinder val (ConsBinder headBinder tailBinder) = do
482− m1 <- inferBinder el headBinder
483− m2 <- inferBinder val tailBinder
485− return $ m1 `M.union` m2
486−inferBinder val (NamedBinder name binder) = do
487− m <- inferBinder val binder
488− return $ M.insert name val m
490−checkBinders :: [Type] -> Type -> [([Binder], Maybe Guard, Value)] -> Subst ()
491−checkBinders _ _ [] = return ()
492−checkBinders nvals ret ((binders, grd, val):bs) = do
493− m1 <- M.unions <$> zipWithM inferBinder nvals binders
494− bindLocalVariables (M.toList m1) $ do
497− Nothing -> return ()
498− Just g -> check g Boolean
499− checkBinders nvals ret bs
501−assignVariable :: Ident -> Subst ()
502−assignVariable name = do
503− env <- checkEnv <$> get
504− modulePath <- checkModulePath <$> get
505− case M.lookup (modulePath, name) (names env) of
506− Just (_, LocalVariable) -> throwError $ "Variable with name " ++ show name ++ " already exists."
509−checkStatement :: M.Map Ident Type -> Type -> Statement -> Subst (Bool, M.Map Ident Type)
510−checkStatement mass _ (VariableIntroduction name val) = do
513− return (False, M.insert name t mass)
514−checkStatement mass _ (Assignment ident val) = do
516− case M.lookup ident mass of
517− Nothing -> throwError $ "No local variable with name " ++ show ident
518− Just ty -> do t ~~ ty
519− return (False, mass)
520−checkStatement mass ret (While val inner) = do
522− (allCodePathsReturn, _) <- checkBlock mass ret inner
523− return (allCodePathsReturn, mass)
524−checkStatement mass ret (If ifst) = do
525− allCodePathsReturn <- checkIfStatement mass ret ifst
526− return (allCodePathsReturn, mass)
527−checkStatement mass ret (For ident start end inner) = do
528− assignVariable ident
531− (allCodePathsReturn, _) <- bindLocalVariables [(ident, Number)] $ checkBlock mass ret inner
532− return (allCodePathsReturn, mass)
533−checkStatement mass ret (ForEach ident vals inner) = do
534− assignVariable ident
536− check vals (Array val)
537− (allCodePathsReturn, _) <- bindLocalVariables [(ident, val)] $ checkBlock mass ret inner
538− guardWith "Cannot return from within a foreach block" $ not allCodePathsReturn
539− return (False, mass)
540−checkStatement mass _ (ValueStatement val) = do
542− return (False, mass)
543−checkStatement mass ret (Return val) = do
547−checkIfStatement :: M.Map Ident Type -> Type -> IfStatement -> Subst Bool
548−checkIfStatement mass ret (IfStatement val thens Nothing) = do
550− _ <- checkBlock mass ret thens
552−checkIfStatement mass ret (IfStatement val thens (Just elses)) = do
554− (allCodePathsReturn1, _) <- checkBlock mass ret thens
555− allCodePathsReturn2 <- checkElseStatement mass ret elses
556− return $ allCodePathsReturn1 && allCodePathsReturn2
558−checkElseStatement :: M.Map Ident Type -> Type -> ElseStatement -> Subst Bool
559−checkElseStatement mass ret (Else elses) = fst <$> checkBlock mass ret elses
560−checkElseStatement mass ret (ElseIf ifst) = checkIfStatement mass ret ifst
562−checkBlock :: M.Map Ident Type -> Type -> [Statement] -> Subst (Bool, M.Map Ident Type)
563−checkBlock mass _ [] = return (False, mass)
564−checkBlock mass ret (s:ss) = do
565− (b1, mass1) <- checkStatement mass ret s
566− bindLocalVariables (M.toList mass1) $ case (b1, ss) of
567− (True, []) -> return (True, mass1)
568− (True, _) -> throwError "Unreachable code"
569− (False, ss') -> checkBlock mass1 ret ss'
571−skolemize :: String -> Type -> Subst Type
572−skolemize ident ty = do
573− tsk <- Skolem <$> fresh'
574− rsk <- RSkolem <$> fresh'
575− return $ replaceRowVars ident rsk $ replaceTypeVars ident tsk ty
577−check :: Value -> Type -> Subst ()
578−check val ty = rethrow errorMessage $ check' val ty
581− "Error checking type of term " ++
582− prettyPrintValue val ++
584− prettyPrintType ty ++
588−check' :: Value -> Type -> Subst ()
589−check' val (ForAll idents ty) = do
590− sk <- skolemize idents ty
592−check' val u@(TUnknown _) = do
594− -- Don't unify an unknown with an inferred polytype
595− ty' <- replaceAllVarsWithUnknowns ty
597−check' (NumericLiteral _) Number = return ()
598−check' (StringLiteral _) String = return ()
599−check' (BooleanLiteral _) Boolean = return ()
600−check' (Unary op val) ty = checkUnary op val ty
601−check' (Binary op left right) ty = checkBinary op left right ty
602−check' (ArrayLiteral vals) (Array ty) = forM_ vals (\val -> check val ty)
603−check' (Indexer index vals) ty = check index Number >> check vals (Array ty)
604−check' (Abs args ret) (Function argTys retTy) = do
605− guardWith "Incorrect number of function arguments" (length args == length argTys)
606− bindLocalVariables (zip args argTys) $ check ret retTy
607−check' app@(App _ _) ret = do
608− let (f, argss) = unfoldApplication app
610− checkFunctionApplications ft argss ret
611−check' (Var var) ty = do
612− ty1 <- lookupVariable var
613− repl <- replaceAllTypeSynonyms ty1
615−check' (TypedValue val ty1) ty2 = do
616− kind <- liftCheck $ kindOf ty1
617− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
620−check' (Case vals binders) ret = do
621− ts <- mapM infer vals
622− checkBinders ts ret binders
623−check' (IfThenElse cond th el) ty = do
627−check' (ObjectLiteral ps) (Object row) = do
628− ensureNoDuplicateProperties ps
629− checkProperties ps row False
630−check' (ObjectUpdate obj ps) (Object row) = do
631− ensureNoDuplicateProperties ps
632− us <- zip (map fst ps) <$> replicateM (length ps) fresh
633− let (propsToCheck, rest) = rowToList row
634− propsToRemove = map fst ps
635− remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
636− check obj (Object (rowFromList (us ++ remainingProps, rest)))
637− checkProperties ps row True
638−check' (Accessor prop val) ty = do
640− check val (Object (RCons prop ty rest))
641−check' (Block ss) ret = do
642− (allCodePathsReturn, _) <- checkBlock M.empty ret ss
643− guardWith "Block is missing a return statement" allCodePathsReturn
644−check' (Constructor c) ty = do
646− modulePath <- checkModulePath <$> get
647− case M.lookup (qualify modulePath c) (dataConstructors env) of
648− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
650− repl <- replaceAllTypeSynonyms ty1
652−check' val (SaturatedTypeSynonym name args) = do
653− ty <- expandTypeSynonym name args
655−check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
657−checkProperties :: [(String, Value)] -> Row -> Bool -> Subst ()
658−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
659− go [] [] REmpty = return ()
660− go [] [] u@(RUnknown _) = u ~~ REmpty
661− go [] [] (RSkolem _) | lax = return ()
662− go [] ((p, _): _) _ | lax = return ()
663− | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
664− go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
665− go ((p,v):ps') [] u@(RUnknown _) = do
668− u ~~ RCons p ty rest
670− go ((p,v):ps') ts r =
675− r ~~ RCons p ty rest
679− go ps' (delete (p, ty) ts) r
680− go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
682−unfoldApplication :: Value -> (Value, [[Value]])
683−unfoldApplication = go []
685− go argss (App f args) = go (args:argss) f
686− go argss f = (f, argss)
688−checkFunctionApplications :: Type -> [[Value]] -> Type -> Subst ()
689−checkFunctionApplications _ [] _ = error "Nullary function application"
690−checkFunctionApplications fnTy [args] ret = checkFunctionApplication fnTy args ret
691−checkFunctionApplications fnTy (args:argss) ret = do
692− argTys <- mapM (infer) args
693− f <- inferFunctionApplication fnTy argTys
694− checkFunctionApplications f argss ret
696−checkFunctionApplication :: Type -> [Value] -> Type -> Subst ()
697−checkFunctionApplication fnTy args ret = rethrow errorMessage $ checkFunctionApplication' fnTy args ret
699− errorMessage msg = "Error applying function of type "
700− ++ prettyPrintType fnTy
701− ++ " to arguments " ++ intercalate ", " (map prettyPrintValue args)
702− ++ ", expecting value of type "
703− ++ prettyPrintType ret ++ ":\n" ++ msg
705−inferFunctionApplication :: Type -> [Type] -> Subst Type
706−inferFunctionApplication (Function argTys retTy) args = do
707− guardWith "Incorrect number of function arguments" (length args == length argTys)
708− zipWithM subsumes args argTys
710−inferFunctionApplication (ForAll ident ty) args = do
711− replaced <- replaceVarWithUnknown ident ty
712− inferFunctionApplication replaced args
713−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