@@ -1,741 +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−{-# OPTIONS_GHC -fno-warn-orphans #-}
16−{-# LANGUAGE DeriveDataTypeable, FlexibleContexts #-}
18−module Language.PureScript.TypeChecker.Types (
23−import Data.Maybe (isNothing, isJust, fromMaybe)
24−import qualified Data.Data as D
26− (mkT, something, everywhere, mkQ)
28−import Language.PureScript.Values
29−import Language.PureScript.Types
30−import Language.PureScript.Kinds
31−import Language.PureScript.Names
32−import Language.PureScript.TypeChecker.Monad
33−import Language.PureScript.TypeChecker.Kinds
34−import Language.PureScript.TypeChecker.Synonyms
35−import Language.PureScript.Pretty
36−import Language.PureScript.Unknown
38−import Control.Monad.State
39−import Control.Monad.Error
40−import Control.Monad.Reader
42−import Control.Applicative
43−import Control.Arrow (Arrow(..))
45−import qualified Data.Map as M
46−import Data.Function (on)
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)
60− apply s (RCons name ty r) = RCons name (apply s ty) (apply s r)
62− unknowns (TUnknown (Unknown u)) = [u]
63− unknowns (SaturatedTypeSynonym _ tys) = concatMap unknowns tys
64− unknowns (ForAll _ ty) = unknowns ty
65− unknowns (Array t) = unknowns t
66− unknowns (Object r) = unknowns r
67− unknowns (Function args ret) = concatMap unknowns args ++ unknowns ret
68− unknowns (TypeApp t1 t2) = unknowns t1 ++ unknowns t2
69− unknowns (RCons _ ty r) = unknowns ty ++ unknowns r
72−unifyTypes :: Type -> Type -> Subst ()
73−unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $ do
76− unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
77− unifyTypes' (TUnknown u) t = replace u t
78− unifyTypes' t (TUnknown u) = replace u t
79− unifyTypes' (SaturatedTypeSynonym name args) ty = do
80− ty1 <- expandTypeSynonym name args
82− unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
83− unifyTypes' (ForAll ident1 ty1) (ForAll ident2 ty2) = do
84− sk <- skolemize ident1 ty1
85− replaced <- replaceVarWithUnknown ident2 ty2
86− sk `unifyTypes` replaced
87− unifyTypes' (ForAll ident ty1) ty2 = do
88− sk <- skolemize ident ty1
90− unifyTypes' ty f@(ForAll _ _) = f `unifyTypes` ty
91− unifyTypes' Number Number = return ()
92− unifyTypes' String String = return ()
93− unifyTypes' Boolean Boolean = return ()
94− unifyTypes' (Array s) (Array t) = s `unifyTypes` t
95− unifyTypes' (Object row1) (Object row2) = row1 ~~ row2
96− unifyTypes' (Function args1 ret1) (Function args2 ret2) = do
97− guardWith "Function applied to incorrect number of args" $ length args1 == length args2
98− zipWithM_ unifyTypes args1 args2
99− ret1 `unifyTypes` ret2
100− unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
101− unifyTypes' (TypeConstructor c1) (TypeConstructor c2) = do
103− moduleName <- substCurrentModule `fmap` ask
104− guardWith ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".") (typeConstructorsAreEqual env moduleName c1 c2)
105− unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
108− unifyTypes' (Skolem s1) (Skolem s2) | s1 == s2 = return ()
109− unifyTypes' r1@(RCons _ _ _) r2 = unifyRows r1 r2
110− unifyTypes' r1 r2@(RCons _ _ _) = unifyRows r1 r2
111− unifyTypes' r1@REmpty r2 = unifyRows r1 r2
112− unifyTypes' r1 r2@REmpty = unifyRows r1 r2
113− unifyTypes' t3 t4 = throwError $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
115−unifyRows :: Type -> Type -> Subst ()
118− (s1, r1') = rowToList r1
119− (s2, r2') = rowToList r2
120− int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
121− sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
122− sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
124− forM_ int (uncurry (~~))
125− unifyRows' sd1 r1' sd2 r2'
127− unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> Subst ()
128− unifyRows' [] (TUnknown u) sd r = replace u (rowFromList (sd, r))
129− unifyRows' sd r [] (TUnknown u) = replace u (rowFromList (sd, r))
130− unifyRows' ((name, ty):row) r others u@(TUnknown un) = do
132− forM row $ \(_, t) -> occursCheck un t
134− u ~~ RCons name ty u'
135− unifyRows' row r others u'
136− unifyRows' [] REmpty [] REmpty = return ()
137− unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
138− unifyRows' [] (Skolem s1) [] (Skolem s2) | s1 == s2 = return ()
139− unifyRows' sd3 r3 sd4 r4 = throwError $ "Cannot unify " ++ prettyPrintRow (rowFromList (sd3, r3)) ++ " with " ++ prettyPrintRow (rowFromList (sd4, r4)) ++ "."
141−typeConstructorsAreEqual :: Environment -> ModuleName -> Qualified ProperName -> Qualified ProperName -> Bool
142−typeConstructorsAreEqual env moduleName = (==) `on` canonicalizeType moduleName env
144−typesOf :: ModuleName -> [(Ident, Value)] -> Check [Type]
145−typesOf moduleName vals = do
146− (tys, sub, checks) <- runSubst (SubstContext moduleName) $ do
147− let es = map isTyped vals
148− typed = filter (isJust . snd . snd) es
149− untyped = filter (isNothing . snd . snd) es
150− typedDict = map (\(ident, (_, Just ty)) -> (ident, ty)) typed
151− untypedNames <- replicateM (length untyped) fresh
152− let untypedDict = zip (map fst untyped) untypedNames
153− dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable))) $ typedDict ++ untypedDict)
154− tys <- forM es $ \e -> do
156− (_, (val, Just ty)) -> do
157− kind <- liftCheck $ kindOf moduleName ty
158− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
159− ty' <- replaceAllTypeSynonyms ty
160− bindNames dict $ check val ty'
162− (ident, (val, Nothing)) -> do
163− ty <- bindNames dict $ infer val
164− ty ~~ fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
166− when (moduleName == ModuleName (ProperName "Main") && fst e == Ident "main") $ do
167− [eff, a] <- replicateM 2 fresh
168− ty ~~ TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName (ProperName "Eff"))) (ProperName "Eff"))) eff) a
171− forM tys $ flip (escapeCheck checks) sub
172− forM tys $ skolemEscapeCheck
173− return $ map (varIfUnknown . desaturateAllTypeSynonyms . setifyAll) tys
175−isTyped :: (Ident, Value) -> (Ident, (Value, Maybe Type))
176−isTyped (name, TypedValue value ty) = (name, (value, Just ty))
177−isTyped (name, value) = (name, (value, Nothing))
179−escapeCheck :: [AnyUnifiable] -> Type -> Substitution -> Check ()
180−escapeCheck checks ty sub =
182− visibleUnknowns = nub $ unknowns ty
184− forM_ checks $ \c -> case c of
185− AnyUnifiable t -> do
186− let unsolvedUnknowns = nub . unknowns $ apply sub t
187− guardWith "Escape check fails" $ null $ unsolvedUnknowns \\ visibleUnknowns
189−skolemEscapeCheck :: Type -> Check ()
190−skolemEscapeCheck ty =
191− case something (mkQ Nothing findSkolems) ty of
192− Nothing -> return ()
193− Just _ -> throwError "Skolem variables cannot escape. Consider adding a type signature."
195− findSkolems (Skolem _) = return ()
196− findSkolems _ = mzero
198−setify :: Type -> Type
199−setify = rowFromList . first (M.toList . M.fromList) . rowToList
201−setifyAll :: (D.Data d) => d -> d
202−setifyAll = everywhere (mkT setify)
204−varIfUnknown :: Type -> Type
206− let unks = nub $ unknowns ty
207− toName = (:) 't' . show
208− ty' = everywhere (mkT typeToVar) $ ty
209− typeToVar :: Type -> Type
210− typeToVar (TUnknown (Unknown u)) = TypeVar (toName u)
212− in mkForAll (sort . map toName $ unks) ty'
214−replaceAllTypeVars :: (D.Data d) => [(String, Type)] -> d -> d
215−replaceAllTypeVars = foldl' (\f (name, ty) -> replaceTypeVars name ty . f) id
217−replaceAllVarsWithUnknowns :: Type -> Subst Type
218−replaceAllVarsWithUnknowns (ForAll ident ty) = replaceVarWithUnknown ident ty >>= replaceAllVarsWithUnknowns
219−replaceAllVarsWithUnknowns ty = return ty
221−replaceVarWithUnknown :: String -> Type -> Subst Type
222−replaceVarWithUnknown ident ty = do
224− return $ replaceTypeVars ident tu $ ty
226−replaceAllTypeSynonyms :: (Functor m, MonadState CheckState m, MonadReader SubstContext m, MonadError String m) => (D.Data d) => d -> m d
227−replaceAllTypeSynonyms d = do
229− moduleName <- substCurrentModule <$> ask
230− let syns = map (\((path, name), (args, _)) -> ((path, name), length args)) . M.toList $ typeSynonyms env
231− either throwError return $ saturateAllTypeSynonyms env moduleName syns d
233−desaturateAllTypeSynonyms :: (D.Data d) => d -> d
234−desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
236− replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
237− replaceSaturatedTypeSynonym t = t
239−expandTypeSynonym :: Qualified ProperName -> [Type] -> Subst Type
240−expandTypeSynonym name args = do
242− moduleName <- substCurrentModule `fmap` ask
243− case M.lookup (canonicalizeType moduleName env name) (typeSynonyms env) of
244− Just (synArgs, body) -> return $ replaceAllTypeVars (zip synArgs args) body
245− Nothing -> error "Type synonym was not defined"
247−ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
248−ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
250−infer :: Value -> Subst Type
251−infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ do
256−infer' :: Value -> Subst Type
257−infer' (NumericLiteral _) = return Number
258−infer' (StringLiteral _) = return String
259−infer' (BooleanLiteral _) = return Boolean
260−infer' (ArrayLiteral vals) = do
261− ts <- mapM (infer) vals
263− forM_ ts $ \t -> els ~~ Array t
265−infer' (Unary op val) = do
268−infer' (Binary op left right) = do
271− inferBinary op t1 t2
272−infer' (ObjectLiteral ps) = do
273− ensureNoDuplicateProperties ps
274− ts <- mapM (infer . snd) ps
275− let fields = zipWith (\(name, _) t -> (name, t)) ps ts
276− return $ Object $ rowFromList (fields, REmpty)
277−infer' (ObjectUpdate o ps) = do
278− ensureNoDuplicateProperties ps
280− newTys <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
281− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
282− check o $ Object $ rowFromList (oldTys, row)
283− return $ Object $ rowFromList (newTys, row)
284−infer' (Indexer index val) = do
287− check val (Array el)
289−infer' (Accessor prop val) = do
291− propTy <- inferProperty obj prop
296− obj `subsumes` Object (RCons prop field rest)
298− Just ty -> return ty
299−infer' (Abs args ret) = do
300− ts <- replicateM (length args) fresh
301− moduleName <- substCurrentModule <$> ask
302− bindLocalVariables moduleName (zip args ts) $ do
304− return $ Function ts body
305−infer' app@(App _ _) = do
306− let (f, argss) = unfoldApplication app
309− checkFunctionApplications ft argss ret
311−infer' (Var var) = do
312− moduleName <- substCurrentModule <$> ask
313− ty <- lookupVariable moduleName var
314− replaceAllTypeSynonyms ty
315−infer' (Block ss) = do
317− (allCodePathsReturn, _) <- checkBlock M.empty ret ss
318− guardWith "Block is missing a return statement" allCodePathsReturn
320−infer' (Constructor c) = do
322− moduleName <- substCurrentModule `fmap` ask
323− case M.lookup (qualify moduleName c) (dataConstructors env) of
324− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
325− Just (ty, _) -> replaceAllTypeSynonyms ty
326−infer' (Case vals binders) = do
327− ts <- mapM infer vals
329− checkBinders ts ret binders
331−infer' (IfThenElse cond th el) = do
337−infer' (TypedValue val ty) = do
338− moduleName <- substCurrentModule <$> ask
339− kind <- liftCheck $ kindOf moduleName ty
340− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
341− ty' <- replaceAllTypeSynonyms ty
344−infer' _ = error "Invalid argument to infer"
346−inferProperty :: Type -> String -> Subst (Maybe Type)
347−inferProperty (Object row) prop = do
348− let (props, _) = rowToList row
349− return $ lookup prop props
350−inferProperty (SaturatedTypeSynonym name args) prop = do
351− replaced <- expandTypeSynonym name args
352− inferProperty replaced prop
353−inferProperty (ForAll ident ty) prop = do
354− replaced <- replaceVarWithUnknown ident ty
355− inferProperty replaced prop
356−inferProperty _ _ = return Nothing
358−inferUnary :: UnaryOperator -> Type -> Subst Type
360− case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
361− (valTy, resTy) -> do
365−checkUnary :: UnaryOperator -> Value -> Type -> Subst ()
366−checkUnary op val res =
367− case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
368− (valTy, resTy) -> do
372−unaryOps :: [(UnaryOperator, (Type, Type))]
373−unaryOps = [ (Negate, (Number, Number))
374− , (Not, (Boolean, Boolean))
375− , (BitwiseNot, (Number, Number))
378−inferBinary :: BinaryOperator -> Type -> Type -> Subst Type
379−inferBinary op left right | isEqualityTest op = do
382−inferBinary op left right =
383− case fromMaybe (error "Invalid operator") $ lookup op binaryOps of
384− (valTy, resTy) -> do
389−checkBinary :: BinaryOperator -> Value -> Value -> Type -> Subst ()
390−checkBinary op left right res | isEqualityTest op = do
395−checkBinary op left right res =
396− case fromMaybe (error "Invalid operator") $ lookup op binaryOps of
397− (valTy, resTy) -> do
402−isEqualityTest :: BinaryOperator -> Bool
403−isEqualityTest EqualTo = True
404−isEqualityTest NotEqualTo = True
405−isEqualityTest _ = False
407−binaryOps :: [(BinaryOperator, (Type, Type))]
408−binaryOps = [ (Add, (Number, Number))
409− , (Subtract, (Number, Number))
410− , (Multiply, (Number, Number))
411− , (Divide, (Number, Number))
412− , (Modulus, (Number, Number))
413− , (BitwiseAnd, (Number, Number))
414− , (BitwiseOr, (Number, Number))
415− , (BitwiseXor, (Number, Number))
416− , (ShiftRight, (Number, Number))
417− , (ZeroFillShiftRight, (Number, Number))
418− , (And, (Boolean, Boolean))
419− , (Or, (Boolean, Boolean))
420− , (Concat, (String, String))
421− , (Modulus, (Number, Number))
422− , (LessThan, (Number, Boolean))
423− , (LessThanOrEqualTo, (Number, Boolean))
424− , (GreaterThan, (Number, Boolean))
425− , (GreaterThanOrEqualTo, (Number, Boolean))
428−inferBinder :: Type -> Binder -> Subst (M.Map Ident Type)
429−inferBinder _ NullBinder = return M.empty
430−inferBinder val (StringBinder _) = val ~~ String >> return M.empty
431−inferBinder val (NumberBinder _) = val ~~ Number >> return M.empty
432−inferBinder val (BooleanBinder _) = val ~~ Boolean >> return M.empty
433−inferBinder val (VarBinder name) = return $ M.singleton name val
434−inferBinder val (NullaryBinder ctor) = do
436− moduleName <- substCurrentModule <$> ask
437− case M.lookup (qualify moduleName ctor) (dataConstructors env) of
441− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
442−inferBinder val (UnaryBinder ctor binder) = do
444− moduleName <- substCurrentModule <$> ask
445− case M.lookup (qualify moduleName ctor) (dataConstructors env) of
447− fn <- replaceAllVarsWithUnknowns ty
449− Function [obj] ret -> do
451− inferBinder obj binder
452− _ -> throwError $ "Constructor " ++ show ctor ++ " is not a unary constructor"
453− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
454−inferBinder val (ObjectBinder props) = do
457− m1 <- inferRowProperties row rest props
461− inferRowProperties :: Type -> Type -> [(String, Binder)] -> Subst (M.Map Ident Type)
462− inferRowProperties nrow row [] = nrow ~~ row >> return M.empty
463− inferRowProperties nrow row ((name, binder):binders) = do
465− m1 <- inferBinder propTy binder
466− m2 <- inferRowProperties nrow (RCons name propTy row) binders
467− return $ m1 `M.union` m2
468−inferBinder val (ArrayBinder binders) = do
470− m1 <- M.unions <$> mapM (inferBinder el) binders
473−inferBinder val (ConsBinder headBinder tailBinder) = do
475− m1 <- inferBinder el headBinder
476− m2 <- inferBinder val tailBinder
478− return $ m1 `M.union` m2
479−inferBinder val (NamedBinder name binder) = do
480− m <- inferBinder val binder
481− return $ M.insert name val m
483−checkBinders :: [Type] -> Type -> [([Binder], Maybe Guard, Value)] -> Subst ()
484−checkBinders _ _ [] = return ()
485−checkBinders nvals ret ((binders, grd, val):bs) = do
486− moduleName <- substCurrentModule <$> ask
487− m1 <- M.unions <$> zipWithM inferBinder nvals binders
488− bindLocalVariables moduleName (M.toList m1) $ do
491− Nothing -> return ()
492− Just g -> check g Boolean
493− checkBinders nvals ret bs
495−assignVariable :: Ident -> Subst ()
496−assignVariable name = do
497− env <- checkEnv <$> get
498− moduleName <- substCurrentModule <$> ask
499− case M.lookup (moduleName, name) (names env) of
500− Just (_, LocalVariable) -> throwError $ "Variable with name " ++ show name ++ " already exists."
503−checkStatement :: M.Map Ident Type -> Type -> Statement -> Subst (Bool, M.Map Ident Type)
504−checkStatement mass _ (VariableIntroduction name val) = do
507− return (False, M.insert name t mass)
508−checkStatement mass _ (Assignment ident val) = do
510− case M.lookup ident mass of
511− Nothing -> throwError $ "No local variable with name " ++ show ident
512− Just ty -> do t ~~ ty
513− return (False, mass)
514−checkStatement mass ret (While val inner) = do
516− (allCodePathsReturn, _) <- checkBlock mass ret inner
517− return (allCodePathsReturn, mass)
518−checkStatement mass ret (If ifst) = do
519− allCodePathsReturn <- checkIfStatement mass ret ifst
520− return (allCodePathsReturn, mass)
521−checkStatement mass ret (For ident start end inner) = do
522− moduleName <- substCurrentModule <$> ask
523− assignVariable ident
526− (allCodePathsReturn, _) <- bindLocalVariables moduleName [(ident, Number)] $ checkBlock mass ret inner
527− return (allCodePathsReturn, mass)
528−checkStatement mass ret (Return val) = do
532−checkIfStatement :: M.Map Ident Type -> Type -> IfStatement -> Subst Bool
533−checkIfStatement mass ret (IfStatement val thens Nothing) = do
535− _ <- checkBlock mass ret thens
537−checkIfStatement mass ret (IfStatement val thens (Just elses)) = do
539− (allCodePathsReturn1, _) <- checkBlock mass ret thens
540− allCodePathsReturn2 <- checkElseStatement mass ret elses
541− return $ allCodePathsReturn1 && allCodePathsReturn2
543−checkElseStatement :: M.Map Ident Type -> Type -> ElseStatement -> Subst Bool
544−checkElseStatement mass ret (Else elses) = fst <$> checkBlock mass ret elses
545−checkElseStatement mass ret (ElseIf ifst) = checkIfStatement mass ret ifst
547−checkBlock :: M.Map Ident Type -> Type -> [Statement] -> Subst (Bool, M.Map Ident Type)
548−checkBlock mass _ [] = return (False, mass)
549−checkBlock mass ret (s:ss) = do
550− moduleName <- substCurrentModule <$> ask
551− (b1, mass1) <- checkStatement mass ret s
552− bindLocalVariables moduleName (M.toList mass1) $ case (b1, ss) of
553− (True, []) -> return (True, mass1)
554− (True, _) -> throwError "Unreachable code"
555− (False, ss') -> checkBlock mass1 ret ss'
557−skolemize :: String -> Type -> Subst Type
558−skolemize ident ty = do
559− tsk <- Skolem <$> fresh'
560− return $ replaceTypeVars ident tsk ty
562−check :: Value -> Type -> Subst ()
563−check val ty = rethrow errorMessage $ check' val ty
566− "Error checking type of term " ++
567− prettyPrintValue val ++
569− prettyPrintType ty ++
573−check' :: Value -> Type -> Subst ()
574−check' val (ForAll idents ty) = do
575− sk <- skolemize idents ty
577−check' val u@(TUnknown _) = do
579− -- Don't unify an unknown with an inferred polytype
580− ty' <- replaceAllVarsWithUnknowns ty
582−check' (NumericLiteral _) Number = return ()
583−check' (StringLiteral _) String = return ()
584−check' (BooleanLiteral _) Boolean = return ()
585−check' (Unary op val) ty = checkUnary op val ty
586−check' (Binary op left right) ty = checkBinary op left right ty
587−check' (ArrayLiteral vals) (Array ty) = forM_ vals (\val -> check val ty)
588−check' (Indexer index vals) ty = check index Number >> check vals (Array ty)
589−check' (Abs args ret) (Function argTys retTy) = do
590− moduleName <- substCurrentModule <$> ask
591− guardWith "Incorrect number of function arguments" (length args == length argTys)
592− bindLocalVariables moduleName (zip args argTys) $ check ret retTy
593−check' app@(App _ _) ret = do
594− let (f, argss) = unfoldApplication app
596− checkFunctionApplications ft argss ret
597−check' (Var var) ty = do
598− moduleName <- substCurrentModule <$> ask
599− ty1 <- lookupVariable moduleName var
600− repl <- replaceAllTypeSynonyms ty1
602−check' (TypedValue val ty1) ty2 = do
603− moduleName <- substCurrentModule <$> ask
604− kind <- liftCheck $ kindOf moduleName ty1
605− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
608−check' (Case vals binders) ret = do
609− ts <- mapM infer vals
610− checkBinders ts ret binders
611−check' (IfThenElse cond th el) ty = do
615−check' (ObjectLiteral ps) (Object row) = do
616− ensureNoDuplicateProperties ps
617− checkProperties ps row False
618−check' (ObjectUpdate obj ps) (Object row) = do
619− ensureNoDuplicateProperties ps
620− us <- zip (map fst ps) <$> replicateM (length ps) fresh
621− let (propsToCheck, rest) = rowToList row
622− propsToRemove = map fst ps
623− remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
624− check obj (Object (rowFromList (us ++ remainingProps, rest)))
625− checkProperties ps row True
626−check' (Accessor prop val) ty = do
628− check val (Object (RCons prop ty rest))
629−check' (Block ss) ret = do
630− (allCodePathsReturn, _) <- checkBlock M.empty ret ss
631− guardWith "Block is missing a return statement" allCodePathsReturn
632−check' (Constructor c) ty = do
634− moduleName <- substCurrentModule <$> ask
635− case M.lookup (qualify moduleName c) (dataConstructors env) of
636− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
638− repl <- replaceAllTypeSynonyms ty1
640−check' val (SaturatedTypeSynonym name args) = do
641− ty <- expandTypeSynonym name args
643−check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
645−checkProperties :: [(String, Value)] -> Type -> Bool -> Subst ()
646−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
647− go [] [] REmpty = return ()
648− go [] [] u@(TUnknown _) = u ~~ REmpty
649− go [] [] (Skolem _) | lax = return ()
650− go [] ((p, _): _) _ | lax = return ()
651− | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
652− go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
653− go ((p,v):ps') [] u@(TUnknown _) = do
656− u ~~ RCons p ty rest
658− go ((p,v):ps') ts r =
663− r ~~ RCons p ty rest
667− go ps' (delete (p, ty) ts) r
668− go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
670−unfoldApplication :: Value -> (Value, [[Value]])
671−unfoldApplication = go []
673− go argss (App f args) = go (args:argss) f
674− go argss f = (f, argss)
676−checkFunctionApplications :: Type -> [[Value]] -> Type -> Subst ()
677−checkFunctionApplications _ [] _ = error "Nullary function application"
678−checkFunctionApplications fnTy [args] ret = checkFunctionApplication fnTy args ret
679−checkFunctionApplications fnTy (args:argss) ret = do
680− argTys <- mapM (infer) args
681− f <- inferFunctionApplication fnTy argTys
682− checkFunctionApplications f argss ret
684−checkFunctionApplication :: Type -> [Value] -> Type -> Subst ()
685−checkFunctionApplication fnTy args ret = rethrow errorMessage $ checkFunctionApplication' fnTy args ret
687− errorMessage msg = "Error applying function of type "
688− ++ prettyPrintType fnTy
689− ++ " to arguments " ++ intercalate ", " (map prettyPrintValue args)
690− ++ ", expecting value of type "
691− ++ prettyPrintType ret ++ ":\n" ++ msg
693−inferFunctionApplication :: Type -> [Type] -> Subst Type
694−inferFunctionApplication (Function argTys retTy) args = do
695− guardWith "Incorrect number of function arguments" (length args == length argTys)
696− zipWithM subsumes args argTys
698−inferFunctionApplication (ForAll ident ty) args = do
699− replaced <- replaceVarWithUnknown ident ty
700− inferFunctionApplication replaced args
701−inferFunctionApplication u@(TUnknown _) args = do
704− args' <- mapM replaceAllVarsWithUnknowns args
705− u ~~ Function args' ret
707−inferFunctionApplication (SaturatedTypeSynonym name tyArgs) args = do
708− ty <- expandTypeSynonym name tyArgs
709− inferFunctionApplication ty args
710−inferFunctionApplication fnTy args = throwError $ "Cannot apply function of type "
711− ++ prettyPrintType fnTy
712− ++ " to argument(s) of type(s) " ++ intercalate ", " (map prettyPrintType args)
714−checkFunctionApplication' :: Type -> [Value] -> Type -> Subst ()
715−checkFunctionApplication' (Function argTys retTy) args ret = do
716− guardWith "Incorrect number of function arguments" (length args == length argTys)
717− zipWithM (check) args argTys
718− retTy `subsumes` ret
719−checkFunctionApplication' (ForAll ident ty) args ret = do
720− replaced <- replaceVarWithUnknown ident ty
721− checkFunctionApplication replaced args ret
722−checkFunctionApplication' u@(TUnknown _) args ret = do
723− tyArgs <- mapM (\arg -> infer arg >>= replaceAllVarsWithUnknowns) args
724− u ~~ Function tyArgs ret
725−checkFunctionApplication' (SaturatedTypeSynonym name tyArgs) args ret = do
726− ty <- expandTypeSynonym name tyArgs
727− checkFunctionApplication' ty args ret
728−checkFunctionApplication' fnTy args ret = throwError $ "Applying a function of type "
729− ++ prettyPrintType fnTy
730− ++ " to argument(s) " ++ intercalate ", " (map prettyPrintValue args)
731− ++ " does not yield a value of type " ++ prettyPrintType ret ++ "."
733−subsumes :: Type -> Type -> Subst ()
734−subsumes (ForAll ident ty1) ty2 = do
735− replaced <- replaceVarWithUnknown ident ty1
736− replaced `subsumes` ty2
737−subsumes (Function args1 ret1) (Function args2 ret2) = do
738− zipWithM subsumes args2 args1
739− ret1 `subsumes` ret2
740−subsumes ty1 ty2 = ty1 ~~ ty2