@@ -1,748 +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 #-}
17−module Language.PureScript.TypeChecker.Types (
22−import Data.Maybe (isJust, fromMaybe)
24−import qualified Data.Data as D
26− (something, everywhere, everywhereM, everything, everywhereBut,
27− 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 Check ()
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 Check ()
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` lift 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 <- lift $ kindOf ty
157− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
158− ty' <- lift $ replaceAllTypeSynonyms ty
159− check (M.singleton ident ty) val ty'
163− ty <- infer (M.singleton ident me) val
166− _ -> infer M.empty val
167− escapeCheck checks ty sub
168− skolemEscapeCheck ty
169− return $ varIfUnknown $ desaturateAllTypeSynonyms $ setifyAll ty
171−escapeCheck :: [AnyUnifiable] -> Type -> Substitution -> Check ()
172−escapeCheck checks ty sub =
174− visibleUnknowns = nub $ unknowns ty
176− forM_ checks $ \check -> case check of
177− AnyUnifiable t -> do
178− let unsolvedUnknowns = nub . unknowns $ apply sub t
179− guardWith "Escape check fails" $ null $ unsolvedUnknowns \\ visibleUnknowns
181−skolemEscapeCheck :: Type -> Check ()
182−skolemEscapeCheck ty =
183− case something (extQ (mkQ Nothing findSkolems) findRSkolems) ty of
184− Nothing -> return ()
185− Just _ -> throwError "Skolem variables cannot escape. Consider adding a type signature."
187− findSkolems (Skolem _) = return ()
188− findSkolems _ = mzero
189− findRSkolems (RSkolem _) = return ()
190− findRSkolems _ = mzero
193−setify = rowFromList . first (M.toList . M.fromList) . rowToList
195−setifyAll :: (D.Data d) => d -> d
196−setifyAll = everywhere (mkT setify)
198−varIfUnknown :: Type -> Type
199−varIfUnknown ty = mkForAll (sort . map ((:) 'u' . show) . nub $ unknowns ty) ty
201−replaceAllTypeVars :: (D.Data d) => [(String, Type)] -> d -> d
202−replaceAllTypeVars = foldl' (\f (name, ty) -> replaceTypeVars name ty . f) id
204−replaceTypeVars :: (D.Data d) => String -> Type -> d -> d
205−replaceTypeVars name t = everywhereBut (mkQ False isShadowed) (mkT replace)
207− replace (TypeVar v) | v == name = t
209− isShadowed (ForAll v _) | v == name = True
210− isShadowed _ = False
212−replaceRowVars :: (D.Data d) => String -> Row -> d -> d
213−replaceRowVars name r = everywhere (mkT replace)
215− replace (RowVar v) | v == name = r
218−replaceAllVarsWithUnknowns :: Type -> Subst Check Type
219−replaceAllVarsWithUnknowns (ForAll ident ty) = replaceVarWithUnknown ident ty >>= replaceAllVarsWithUnknowns
220−replaceAllVarsWithUnknowns ty = return ty
222−replaceVarWithUnknown :: String -> Type -> Subst Check Type
223−replaceVarWithUnknown ident ty = do
226− return $ replaceRowVars ident ru . replaceTypeVars ident tu $ ty
228−replaceAllTypeSynonyms :: (D.Data d) => d -> Check d
229−replaceAllTypeSynonyms d = do
231− let syns = map (\((path, name), (args, _)) -> (Qualified path name, length args)) . M.toList $ typeSynonyms env
232− either throwError return $ saturateAllTypeSynonyms syns d
234−desaturateAllTypeSynonyms :: (D.Data d) => d -> d
235−desaturateAllTypeSynonyms = everywhere (mkT replace)
237− replace (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
240−expandAllTypeSynonyms :: Type -> Subst Check Type
241−expandAllTypeSynonyms (SaturatedTypeSynonym name args) = expandTypeSynonym name args >>= expandAllTypeSynonyms
242−expandAllTypeSynonyms ty = return ty
244−expandTypeSynonym :: Qualified ProperName -> [Type] -> Subst Check Type
245−expandTypeSynonym name args = do
247− modulePath <- checkModulePath `fmap` lift get
248− case M.lookup (qualify modulePath name) (typeSynonyms env) of
249− Just (synArgs, body) -> return $ replaceAllTypeVars (zip synArgs args) body
250− Nothing -> error "Type synonym was not defined"
252−ensureNoDuplicateProperties :: [(String, Value)] -> Check ()
253−ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
255−infer :: M.Map Ident Type -> Value -> Subst Check Type
256−infer m val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ do
261−infer' _ (NumericLiteral _) = return Number
262−infer' _ (StringLiteral _) = return String
263−infer' _ (BooleanLiteral _) = return Boolean
264−infer' m (ArrayLiteral vals) = do
265− ts <- mapM (infer m) vals
267− forM_ ts $ \t -> arr ~~ Array t
269−infer' m (Unary op val) = do
272−infer' m (Binary op left right) = do
275− inferBinary op t1 t2
276−infer' m (ObjectLiteral ps) = do
277− lift $ ensureNoDuplicateProperties ps
278− ts <- mapM (infer m . snd) ps
279− let fields = zipWith (\(name, _) t -> (name, t)) ps ts
280− return $ Object $ rowFromList (fields, REmpty)
281−infer' m (ObjectUpdate o ps) = do
282− lift $ ensureNoDuplicateProperties ps
284− newTys <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer m . snd) ps
285− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
286− check m o $ Object $ rowFromList (oldTys, row)
287− return $ Object $ rowFromList (newTys, row)
288−infer' m (Indexer index val) = do
290− check m index Number
291− check m val (Array el)
293−infer' m (Accessor prop val) = do
295− propTy <- inferProperty obj prop
300− obj `subsumes` Object (RCons prop field rest)
302− Just ty -> return ty
303−infer' m (Abs args ret) = do
304− ts <- replicateM (length args) fresh
305− let m' = m `M.union` M.fromList (zip args ts)
306− body <- infer m' ret
307− return $ Function ts body
308−infer' m app@(App _ _) = do
309− let (f, argss) = unfoldApplication app
312− checkFunctionApplications m ft argss ret
314−infer' m (Var var@(Qualified mp name)) = do
317− case M.lookup name m of
318− Just ty -> lift $ replaceAllTypeSynonyms ty
319− Nothing -> lookupGlobal
324− modulePath <- checkModulePath `fmap` lift get
325− case M.lookup (qualify modulePath var) (names env) of
326− Nothing -> throwError $ show var ++ " is undefined"
327− Just (ty, _) -> lift $ replaceAllTypeSynonyms ty
328−infer' m (Block ss) = do
330− (allCodePathsReturn, _) <- checkBlock m M.empty ret ss
331− guardWith "Block is missing a return statement" allCodePathsReturn
333−infer' m (Constructor c) = do
335− modulePath <- checkModulePath `fmap` lift get
336− case M.lookup (qualify modulePath c) (dataConstructors env) of
337− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
338− Just ty -> lift $ replaceAllTypeSynonyms ty
339−infer' m (Case val binders) = do
342− checkBinders m t1 ret binders
344−infer' m (IfThenElse cond th el) = do
345− check m cond Boolean
350−infer' m (TypedValue val ty) = do
351− kind <- lift $ kindOf ty
352− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
353− ty' <- lift $ replaceAllTypeSynonyms ty
357−inferProperty :: Type -> String -> Subst Check (Maybe Type)
358−inferProperty (Object row) prop = do
359− let (props, _) = rowToList row
360− return $ lookup prop props
361−inferProperty (SaturatedTypeSynonym name args) prop = do
362− replaced <- expandTypeSynonym name args
363− inferProperty replaced prop
364−inferProperty (ForAll ident ty) prop = do
365− replaced <- replaceVarWithUnknown ident ty
366− inferProperty replaced prop
367−inferProperty _ prop = return Nothing
369−inferUnary :: UnaryOperator -> Type -> Subst Check Type
371− case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
372− (valTy, resTy) -> do
376−checkUnary :: M.Map Ident Type -> UnaryOperator -> Value -> Type -> Subst Check ()
377−checkUnary m op val res =
378− case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
379− (valTy, resTy) -> do
383−unaryOps :: [(UnaryOperator, (Type, Type))]
384−unaryOps = [ (Negate, (Number, Number))
385− , (Not, (Boolean, Boolean))
386− , (BitwiseNot, (Number, Number))
389−inferBinary :: BinaryOperator -> Type -> Type -> Subst Check Type
390−inferBinary op left right | isEqualityTest op = do
393−inferBinary op left right =
394− case fromMaybe (error "Invalid operator") $ lookup op binaryOps of
395− (valTy, resTy) -> do
400−checkBinary :: M.Map Ident Type -> BinaryOperator -> Value -> Value -> Type -> Subst Check ()
401−checkBinary m op left right res | isEqualityTest op = do
406−checkBinary m op left right res =
407− case fromMaybe (error "Invalid operator") $ lookup op binaryOps of
408− (valTy, resTy) -> do
413−isEqualityTest :: BinaryOperator -> Bool
414−isEqualityTest EqualTo = True
415−isEqualityTest NotEqualTo = True
416−isEqualityTest _ = False
418−binaryOps :: [(BinaryOperator, (Type, Type))]
419−binaryOps = [ (Add, (Number, Number))
420− , (Subtract, (Number, Number))
421− , (Multiply, (Number, Number))
422− , (Divide, (Number, Number))
423− , (Modulus, (Number, Number))
424− , (BitwiseAnd, (Number, Number))
425− , (BitwiseOr, (Number, Number))
426− , (BitwiseXor, (Number, Number))
427− , (ShiftRight, (Number, Number))
428− , (ZeroFillShiftRight, (Number, Number))
429− , (And, (Boolean, Boolean))
430− , (Or, (Boolean, Boolean))
431− , (Concat, (String, String))
432− , (Modulus, (Number, Number))
433− , (LessThan, (Number, Boolean))
434− , (LessThanOrEqualTo, (Number, Boolean))
435− , (GreaterThan, (Number, Boolean))
436− , (GreaterThanOrEqualTo, (Number, Boolean))
439−inferBinder :: Type -> Binder -> Subst Check (M.Map Ident Type)
440−inferBinder _ NullBinder = return M.empty
441−inferBinder val (StringBinder _) = val ~~ String >> return M.empty
442−inferBinder val (NumberBinder _) = val ~~ Number >> return M.empty
443−inferBinder val (BooleanBinder _) = val ~~ Boolean >> return M.empty
444−inferBinder val (VarBinder name) = return $ M.singleton name val
445−inferBinder val (NullaryBinder ctor) = do
447− modulePath <- checkModulePath `fmap` lift get
448− case M.lookup (qualify modulePath ctor) (dataConstructors env) of
452− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
453−inferBinder val (UnaryBinder ctor binder) = do
455− modulePath <- checkModulePath `fmap` lift get
456− case M.lookup (qualify modulePath ctor) (dataConstructors env) of
458− Function [obj] ret <- replaceAllVarsWithUnknowns ty
460− inferBinder obj binder
461− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
462−inferBinder val (ObjectBinder props) = do
465− m1 <- inferRowProperties row rest props
469− inferRowProperties :: Row -> Row -> [(String, Binder)] -> Subst Check (M.Map Ident Type)
470− inferRowProperties nrow row [] = nrow ~~ row >> return M.empty
471− inferRowProperties nrow row ((name, binder):binders) = do
473− m1 <- inferBinder propTy binder
474− m2 <- inferRowProperties nrow (RCons name propTy row) binders
475− return $ m1 `M.union` m2
476−inferBinder val (ArrayBinder binders rest) = do
478− m1 <- M.unions <$> mapM (inferBinder el) binders
481− Nothing -> return m1
483− m2 <- inferBinder val binder
484− return $ m1 `M.union` m2
485−inferBinder val (NamedBinder name binder) = do
486− m <- inferBinder val binder
487− return $ M.insert name val m
489−inferGuardedBinder :: M.Map Ident Type -> Type -> Binder -> Subst Check (M.Map Ident Type)
490−inferGuardedBinder m val (GuardedBinder cond binder) = do
491− m1 <- inferBinder val binder
492− check (m1 `M.union` m) cond Boolean
494−inferGuardedBinder m val b = inferBinder val b
496−checkBinders :: M.Map Ident Type -> Type -> Type -> [(Binder, Value)] -> Subst Check ()
497−checkBinders _ _ _ [] = return ()
498−checkBinders m nval ret ((binder, val):bs) = do
499− m1 <- inferGuardedBinder m nval binder
500− check (m1 `M.union` m) val ret
501− checkBinders m nval ret bs
503−assignVariable :: Ident -> M.Map Ident Type -> Subst Check ()
504−assignVariable name m =
505− case M.lookup name m of
506− Nothing -> return ()
507− Just _ -> throwError $ "Variable with name " ++ show name ++ " already exists."
509−checkStatement :: M.Map Ident Type -> M.Map Ident Type -> Type -> Statement -> Subst Check (Bool, M.Map Ident Type)
510−checkStatement m mass ret (VariableIntroduction name val) = do
511− assignVariable name (m `M.union` mass)
513− return (False, M.insert name t mass)
514−checkStatement m mass ret (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 m mass ret (While val inner) = do
522− (allCodePathsReturn, _) <- checkBlock m mass ret inner
523− return (allCodePathsReturn, mass)
524−checkStatement m mass ret (If ifst) = do
525− allCodePathsReturn <- checkIfStatement m mass ret ifst
526− return (allCodePathsReturn, mass)
527−checkStatement m mass ret (For ident start end inner) = do
528− assignVariable ident (m `M.union` mass)
529− check (m `M.union` mass) start Number
530− check (m `M.union` mass) end Number
531− let mass1 = M.insert ident Number mass
532− (allCodePathsReturn, _) <- checkBlock (m `M.union` mass1) mass1 ret inner
533− return (allCodePathsReturn, mass)
534−checkStatement m mass ret (ForEach ident vals inner) = do
535− assignVariable ident (m `M.union` mass)
537− check (m `M.union` mass) vals (Array val)
538− let mass1 = M.insert ident val mass
539− (allCodePathsReturn, _) <- checkBlock (m `M.union` mass1) mass1 ret inner
540− guardWith "Cannot return from within a foreach block" $ not allCodePathsReturn
541− return (False, mass)
542−checkStatement m mass ret (Return val) = do
543− check (m `M.union` mass) val ret
546−checkIfStatement :: M.Map Ident Type -> M.Map Ident Type -> Type -> IfStatement -> Subst Check Bool
547−checkIfStatement m mass ret (IfStatement val thens Nothing) = do
549− _ <- checkBlock m mass ret thens
551−checkIfStatement m mass ret (IfStatement val thens (Just elses)) = do
553− (allCodePathsReturn1, _) <- checkBlock m mass ret thens
554− allCodePathsReturn2 <- checkElseStatement m mass ret elses
555− return $ allCodePathsReturn1 && allCodePathsReturn2
557−checkElseStatement :: M.Map Ident Type -> M.Map Ident Type -> Type -> ElseStatement -> Subst Check Bool
558−checkElseStatement m mass ret (Else elses) = fst <$> checkBlock m mass ret elses
559−checkElseStatement m mass ret (ElseIf ifst) = checkIfStatement m mass ret ifst
561−checkBlock :: M.Map Ident Type -> M.Map Ident Type -> Type -> [Statement] -> Subst Check (Bool, M.Map Ident Type)
562−checkBlock _ mass _ [] = return (False, mass)
563−checkBlock m mass ret (s:ss) = do
564− (b1, mass1) <- checkStatement (m `M.union` mass) mass ret s
566− (True, []) -> return (True, mass1)
567− (True, _) -> throwError "Unreachable code"
569− (b2, mass2) <- checkBlock m mass1 ret ss
572−skolemize :: String -> Type -> Subst Check 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 :: M.Map Ident Type -> Value -> Type -> Subst Check ()
579−check m val ty = rethrow errorMessage $ check' m val ty
582− "Error checking type of term " ++
583− prettyPrintValue val ++
585− prettyPrintType ty ++
589−check' :: M.Map Ident Type -> Value -> Type -> Subst Check ()
590−check' m val (ForAll idents ty) = do
591− sk <- skolemize idents ty
593−check' m val u@(TUnknown _) = do
595− -- Don't unify an unknown with an inferred polytype
596− ty' <- replaceAllVarsWithUnknowns ty
598−check' m (NumericLiteral _) Number = return ()
599−check' m (StringLiteral _) String = return ()
600−check' m (BooleanLiteral _) Boolean = return ()
601−check' m (Unary op val) ty = checkUnary m op val ty
602−check' m (Binary op left right) ty = checkBinary m op left right ty
603−check' m (ArrayLiteral vals) (Array ty) = forM_ vals (\val -> check m val ty)
604−check' m (Indexer index vals) ty = check m index Number >> check m vals (Array ty)
605−check' m (Abs args ret) (Function argTys retTy) = do
606− guardWith "Incorrect number of function arguments" (length args == length argTys)
607− let bindings = M.fromList (zip args argTys)
608− check (bindings `M.union` m) ret retTy
609−check' m app@(App _ _) ret = do
610− let (f, argss) = unfoldApplication app
612− checkFunctionApplications m ft argss ret
613−check' m v@(Var var@(Qualified mp name)) ty = do
616− case M.lookup name m of
618− repl <- lift $ replaceAllTypeSynonyms ty1
620− Nothing -> lookupGlobal
625− modulePath <- checkModulePath `fmap` lift get
626− case M.lookup (qualify modulePath var) (names env) of
627− Nothing -> throwError $ show var ++ " is undefined"
629− repl <- lift $ replaceAllTypeSynonyms ty1
631−check' m (TypedValue val ty1) ty2 = do
632− kind <- lift $ kindOf ty1
633− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
636−check' m (Case val binders) ret = do
638− checkBinders m t1 ret binders
639−check' m (IfThenElse cond th el) ty = do
640− check m cond Boolean
643−check' m (ObjectLiteral ps) (Object row) = do
644− lift $ ensureNoDuplicateProperties ps
645− checkProperties m ps row False
646−check' m (ObjectUpdate obj ps) (Object row) = do
647− lift $ ensureNoDuplicateProperties ps
648− us <- zip (map fst ps) <$> replicateM (length ps) fresh
649− let (propsToCheck, rest) = rowToList row
650− propsToRemove = map fst ps
651− remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
652− check m obj (Object (rowFromList (us ++ remainingProps, rest)))
653− checkProperties m ps row True
654−check' m (Accessor prop val) ty = do
656− check m val (Object (RCons prop ty rest))
657−check' m (Block ss) ret = do
658− (allCodePathsReturn, _) <- checkBlock m M.empty ret ss
659− guardWith "Block is missing a return statement" allCodePathsReturn
660−check' m (Constructor c) ty = do
662− modulePath <- checkModulePath `fmap` lift get
663− case M.lookup (qualify modulePath c) (dataConstructors env) of
664− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
666− repl <- lift $ replaceAllTypeSynonyms ty1
668−check' m val (SaturatedTypeSynonym name args) = do
669− ty <- expandTypeSynonym name args
671−check' _ val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
673−checkProperties :: M.Map Ident Type -> [(String, Value)] -> Row -> Bool -> Subst Check ()
674−checkProperties m ps row lax = let (ts, r') = rowToList row in go ps ts r' where
675− go [] [] REmpty = return ()
676− go [] [] u@(RUnknown _) = u ~~ REmpty
677− go [] [] (RSkolem _) | lax = return ()
678− go [] ((p, _): _) _ | lax = return ()
679− | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
680− go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
681− go ((p,v):ps) [] u@(RUnknown _) = do
684− u ~~ RCons p ty rest
686− go ((p,v):ps) ts r =
691− r ~~ RCons p ty rest
695− go ps (delete (p, ty) ts) r
696− go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
698−unfoldApplication :: Value -> (Value, [[Value]])
699−unfoldApplication = go []
701− go argss (App f args) = go (args:argss) f
702− go argss f = (f, argss)
704−checkFunctionApplications :: M.Map Ident Type -> Type -> [[Value]] -> Type -> Subst Check ()
705−checkFunctionApplications _ _ [] _ = error "Nullary function application"
706−checkFunctionApplications m fnTy [args] ret = checkFunctionApplication m fnTy args ret
707−checkFunctionApplications m fnTy (args:argss) ret = do
709− checkFunctionApplication m fnTy args f
710− checkFunctionApplications m f argss ret
712−checkFunctionApplication :: M.Map Ident Type -> Type -> [Value] -> Type -> Subst Check ()
713−checkFunctionApplication m fnTy args ret = rethrow errorMessage $ checkFunctionApplication' m fnTy args ret
715− errorMessage msg = "Error applying function of type "
716− ++ prettyPrintType fnTy
717− ++ " to arguments " ++ intercalate ", " (map prettyPrintValue args)
718− ++ ", expecting value of type "
719− ++ prettyPrintType ret ++ ":\n" ++ msg
721−checkFunctionApplication' :: M.Map Ident Type -> Type -> [Value] -> Type -> Subst Check ()
722−checkFunctionApplication' m (Function argTys retTy) args ret = do
723− guardWith "Incorrect number of function arguments" (length args == length argTys)
724− zipWithM (check m) args argTys
725− retTy `subsumes` ret
726−checkFunctionApplication' m (ForAll ident ty) args ret = do
727− replaced <- replaceVarWithUnknown ident ty
728− checkFunctionApplication m replaced args ret
729−checkFunctionApplication' m u@(TUnknown _) args ret = do
730− tyArgs <- mapM (\arg -> infer m arg >>= replaceAllVarsWithUnknowns) args
731− u ~~ Function tyArgs ret
732−checkFunctionApplication' m (SaturatedTypeSynonym name tyArgs) args ret = do
733− ty <- expandTypeSynonym name tyArgs
734− checkFunctionApplication' m ty args ret
735−checkFunctionApplication' _ fnTy args ret = throwError $ "Cannot apply function of type "
736− ++ prettyPrintType fnTy
737− ++ " to arguments " ++ intercalate ", " (map prettyPrintValue args)
738− ++ ". Expecting value of type " ++ prettyPrintType ret ++ "."
740−subsumes :: Type -> Type -> Subst Check ()
741−subsumes (ForAll ident ty1) ty2 = do
742− replaced <- replaceVarWithUnknown ident ty1
743− replaced `subsumes` ty2
744−subsumes (Function args1 ret1) (Function args2 ret2) = do
745− zipWithM subsumes args2 args1
746− ret1 `subsumes` ret2
747−subsumes ty1 ty2 = ty1 ~~ ty2