@@ -0,0 +1,753 @@
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 val binders) = do
337+ checkBinders t1 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+ Function [obj] ret <- replaceAllVarsWithUnknowns ty
456+ inferBinder obj binder
457+ _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
458+inferBinder val (ObjectBinder props) = do
461+ m1 <- inferRowProperties row rest props
465+ inferRowProperties :: Row -> Row -> [(String, Binder)] -> Subst (M.Map Ident Type)
466+ inferRowProperties nrow row [] = nrow ~~ row >> return M.empty
467+ inferRowProperties nrow row ((name, binder):binders) = do
469+ m1 <- inferBinder propTy binder
470+ m2 <- inferRowProperties nrow (RCons name propTy row) binders
471+ return $ m1 `M.union` m2
472+inferBinder val (ArrayBinder binders) = do
474+ m1 <- M.unions <$> mapM (inferBinder el) binders
477+inferBinder val (ConsBinder headBinder tailBinder) = do
479+ m1 <- inferBinder el headBinder
480+ m2 <- inferBinder val tailBinder
482+ return $ m1 `M.union` m2
483+inferBinder val (NamedBinder name binder) = do
484+ m <- inferBinder val binder
485+ return $ M.insert name val m
486+inferBinder _ _ = error "Invalid argument to inferBinder"
488+inferGuardedBinder :: Type -> Binder -> Subst (M.Map Ident Type)
489+inferGuardedBinder val (GuardedBinder cond binder) = do
490+ m1 <- inferBinder val binder
491+ bindLocalVariables (M.toList m1) $ check cond Boolean
493+inferGuardedBinder val b = inferBinder val b
495+checkBinders :: Type -> Type -> [(Binder, Value)] -> Subst ()
496+checkBinders _ _ [] = return ()
497+checkBinders nval ret ((binder, val):bs) = do
498+ m1 <- inferGuardedBinder nval binder
499+ bindLocalVariables (M.toList m1) $ check val ret
500+ checkBinders nval ret bs
502+assignVariable :: Ident -> Subst ()
503+assignVariable name = do
504+ env <- checkEnv <$> get
505+ modulePath <- checkModulePath <$> get
506+ case M.lookup (modulePath, name) (names env) of
507+ Just (_, LocalVariable) -> throwError $ "Variable with name " ++ show name ++ " already exists."
510+checkStatement :: M.Map Ident Type -> Type -> Statement -> Subst (Bool, M.Map Ident Type)
511+checkStatement mass _ (VariableIntroduction name val) = do
514+ return (False, M.insert name t mass)
515+checkStatement mass _ (Assignment ident val) = do
517+ case M.lookup ident mass of
518+ Nothing -> throwError $ "No local variable with name " ++ show ident
519+ Just ty -> do t ~~ ty
520+ return (False, mass)
521+checkStatement mass ret (While val inner) = do
523+ (allCodePathsReturn, _) <- checkBlock mass ret inner
524+ return (allCodePathsReturn, mass)
525+checkStatement mass ret (If ifst) = do
526+ allCodePathsReturn <- checkIfStatement mass ret ifst
527+ return (allCodePathsReturn, mass)
528+checkStatement mass ret (For ident start end inner) = do
529+ assignVariable ident
532+ (allCodePathsReturn, _) <- bindLocalVariables [(ident, Number)] $ checkBlock mass ret inner
533+ return (allCodePathsReturn, mass)
534+checkStatement mass ret (ForEach ident vals inner) = do
535+ assignVariable ident
537+ check vals (Array val)
538+ (allCodePathsReturn, _) <- bindLocalVariables [(ident, val)] $ checkBlock mass ret inner
539+ guardWith "Cannot return from within a foreach block" $ not allCodePathsReturn
540+ return (False, mass)
541+checkStatement mass _ (ValueStatement val) = do
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' (Var var) 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