@@ -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−{-# 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) <- 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− TypedValue _ 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
190−skolemEscapeCheck :: Type -> Check ()
191−skolemEscapeCheck ty =
192− case something (mkQ Nothing findSkolems) ty of
193− Nothing -> return ()
194− Just _ -> throwError "Skolem variables cannot escape. Consider adding a type signature."
196− findSkolems (Skolem _) = return ()
197− findSkolems _ = mzero
199−setify :: Type -> Type
200−setify = rowFromList . first (M.toList . M.fromList) . rowToList
202−setifyAll :: (D.Data d) => d -> d
203−setifyAll = everywhere (mkT setify)
205−varIfUnknown :: Type -> Type
207− let unks = nub $ unknowns ty
208− toName = (:) 't' . show
209− ty' = everywhere (mkT typeToVar) $ ty
210− typeToVar :: Type -> Type
211− typeToVar (TUnknown (Unknown u)) = TypeVar (toName u)
213− in mkForAll (sort . map toName $ unks) ty'
215−replaceAllTypeVars :: (D.Data d) => [(String, Type)] -> d -> d
216−replaceAllTypeVars = foldl' (\f (name, ty) -> replaceTypeVars name ty . f) id
218−replaceAllVarsWithUnknowns :: Type -> Subst Type
219−replaceAllVarsWithUnknowns (ForAll ident ty) = replaceVarWithUnknown ident ty >>= replaceAllVarsWithUnknowns
220−replaceAllVarsWithUnknowns ty = return ty
222−replaceVarWithUnknown :: String -> Type -> Subst Type
223−replaceVarWithUnknown ident ty = do
225− return $ replaceTypeVars ident tu $ ty
227−replaceAllTypeSynonyms :: (Functor m, MonadState CheckState m, MonadReader SubstContext m, MonadError String m) => (D.Data d) => d -> m d
228−replaceAllTypeSynonyms d = do
230− moduleName <- substCurrentModule <$> ask
231− let syns = map (\((path, name), (args, _)) -> ((path, name), length args)) . M.toList $ typeSynonyms env
232− either throwError return $ saturateAllTypeSynonyms env moduleName syns d
234−desaturateAllTypeSynonyms :: (D.Data d) => d -> d
235−desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
237− replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
238− replaceSaturatedTypeSynonym t = t
240−expandTypeSynonym :: Qualified ProperName -> [Type] -> Subst Type
241−expandTypeSynonym name args = do
243− moduleName <- substCurrentModule `fmap` ask
244− case M.lookup (canonicalizeType moduleName env name) (typeSynonyms env) of
245− Just (synArgs, body) -> return $ replaceAllTypeVars (zip synArgs args) body
246− Nothing -> error "Type synonym was not defined"
248−ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
249−ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
251−infer :: Value -> Subst Value
252−infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
254−infer' :: Value -> Subst Value
255−infer' v@(NumericLiteral _) = return $ TypedValue v Number
256−infer' v@(StringLiteral _) = return $ TypedValue v String
257−infer' v@(BooleanLiteral _) = return $ TypedValue v Boolean
258−infer' (ArrayLiteral vals) = do
259− ts <- mapM infer vals
261− forM_ ts $ \(TypedValue _ t) -> els ~~ Array t
262− return $ TypedValue (ArrayLiteral ts) els
263−infer' (Unary op val) = do
266−infer' (Binary op left right) = do
269− inferBinary op v1 v2
270−infer' (ObjectLiteral ps) = do
271− ensureNoDuplicateProperties ps
272− ts <- mapM (infer . snd) ps
273− let fields = zipWith (\name (TypedValue _ t) -> (name, t)) (map fst ps) ts
274− ty = Object $ rowFromList (fields, REmpty)
275− return $ TypedValue (ObjectLiteral (zip (map fst ps) ts)) ty
276−infer' (ObjectUpdate o ps) = do
277− ensureNoDuplicateProperties ps
279− newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
280− let newTys = map (\(name, TypedValue _ ty) -> (name, ty)) newVals
281− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
282− o' <- check o $ Object $ rowFromList (oldTys, row)
283− return $ TypedValue (ObjectUpdate o' newVals) $ Object $ rowFromList (newTys, row)
284−infer' (Indexer index val) = do
287− check val (Array el)
288− return $ TypedValue (Indexer (TypedValue index Number) (TypedValue val (Array el))) el
289−infer' (Accessor prop val) = do
290− typed@(TypedValue _ objTy) <- infer val
291− propTy <- inferProperty objTy prop
296− objTy `subsumes` Object (RCons prop field rest)
297− return $ TypedValue (Accessor prop typed) field
298− Just ty -> return $ TypedValue (Accessor prop typed) ty
299−infer' (Abs args ret) = do
300− ts <- replicateM (length args) fresh
301− moduleName <- substCurrentModule <$> ask
302− bindLocalVariables moduleName (zip args ts) $ do
303− (TypedValue body bodyTy) <- infer' ret
304− return $ TypedValue (Abs args body) $ Function ts bodyTy
305−infer' (App f args) = do
306− (TypedValue f' ft) <- infer f
308− args' <- checkFunctionApplication ft args ret
309− return $ TypedValue (App f' args') ret
310−infer' (Var var) = do
311− moduleName <- substCurrentModule <$> ask
312− ty <- lookupVariable moduleName var
313− ty' <- replaceAllTypeSynonyms ty
314− return $ TypedValue (Var var) ty'
315−infer' (Block ss) = do
317− (allCodePathsReturn, _, ss') <- checkBlock M.empty ret ss
318− guardWith "Block is missing a return statement" allCodePathsReturn
319− return $ TypedValue (Block ss') ret
320−infer' v@(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, _) -> do ty' <- replaceAllTypeSynonyms ty
326− return $ TypedValue v ty'
327−infer' (Case vals binders) = do
328− ts <- mapM infer vals
330− binders' <- checkBinders (map (\(TypedValue _ t) -> t) ts) ret binders
331− return $ TypedValue (Case ts binders') ret
332−infer' (IfThenElse cond th el) = do
334− TypedValue v2 t2 <- infer th
335− TypedValue v3 t3 <- infer el
337− return $ TypedValue (IfThenElse cond v2 v3) t2
338−infer' (TypedValue val ty) = do
339− moduleName <- substCurrentModule <$> ask
340− kind <- liftCheck $ kindOf moduleName ty
341− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
342− 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 -> Value -> Subst Value
359−inferUnary op (TypedValue val valTy) =
360− case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
361− (valTy', resTy) -> do
363− return $ TypedValue (Unary op val) resTy
364−inferUnary _ _ = error "Invalid arguments to inferUnary"
366−checkUnary :: UnaryOperator -> Value -> Type -> Subst Value
367−checkUnary op val res =
368− case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
369− (valTy, resTy) -> do
373−unaryOps :: [(UnaryOperator, (Type, Type))]
374−unaryOps = [ (Negate, (Number, Number))
375− , (Not, (Boolean, Boolean))
376− , (BitwiseNot, (Number, Number))
379−inferBinary :: BinaryOperator -> Value -> Value -> Subst Value
380−inferBinary op left@(TypedValue _ leftTy) right@(TypedValue _ rightTy) | isEqualityTest op = do
382− return $ TypedValue (Binary op left right) Boolean
383−inferBinary op left@(TypedValue _ leftTy) right@(TypedValue _ rightTy) =
384− case fromMaybe (error "Invalid operator") $ lookup op binaryOps of
385− (valTy, resTy) -> do
388− return $ TypedValue (Binary op left right) resTy
389−inferBinary _ _ _ = error "Invalid arguments to inferBinary"
391−checkBinary :: BinaryOperator -> Value -> Value -> Type -> Subst Value
392−checkBinary op left right res | isEqualityTest op = do
394− TypedValue v1 t1 <- infer left
395− TypedValue v2 t2 <- infer right
397− return $ TypedValue (Binary op v1 v2) $ res
398−checkBinary op left right res =
399− case fromMaybe (error "Invalid operator") $ lookup op binaryOps of
400− (valTy, resTy) -> do
402− v1 <- check left valTy
403− v2 <- check right valTy
404− return $ TypedValue (Binary op v1 v2) $ res
406−isEqualityTest :: BinaryOperator -> Bool
407−isEqualityTest EqualTo = True
408−isEqualityTest NotEqualTo = True
409−isEqualityTest _ = False
411−binaryOps :: [(BinaryOperator, (Type, Type))]
412−binaryOps = [ (Add, (Number, Number))
413− , (Subtract, (Number, Number))
414− , (Multiply, (Number, Number))
415− , (Divide, (Number, Number))
416− , (Modulus, (Number, Number))
417− , (BitwiseAnd, (Number, Number))
418− , (BitwiseOr, (Number, Number))
419− , (BitwiseXor, (Number, Number))
420− , (ShiftRight, (Number, Number))
421− , (ZeroFillShiftRight, (Number, Number))
422− , (And, (Boolean, Boolean))
423− , (Or, (Boolean, Boolean))
424− , (Concat, (String, String))
425− , (Modulus, (Number, Number))
426− , (LessThan, (Number, Boolean))
427− , (LessThanOrEqualTo, (Number, Boolean))
428− , (GreaterThan, (Number, Boolean))
429− , (GreaterThanOrEqualTo, (Number, Boolean))
432−inferBinder :: Type -> Binder -> Subst (M.Map Ident Type)
433−inferBinder _ NullBinder = return M.empty
434−inferBinder val (StringBinder _) = val ~~ String >> return M.empty
435−inferBinder val (NumberBinder _) = val ~~ Number >> return M.empty
436−inferBinder val (BooleanBinder _) = val ~~ Boolean >> return M.empty
437−inferBinder val (VarBinder name) = return $ M.singleton name val
438−inferBinder val (NullaryBinder ctor) = do
440− moduleName <- substCurrentModule <$> ask
441− case M.lookup (qualify moduleName ctor) (dataConstructors env) of
445− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
446−inferBinder val (UnaryBinder ctor binder) = do
448− moduleName <- substCurrentModule <$> ask
449− case M.lookup (qualify moduleName ctor) (dataConstructors env) of
451− fn <- replaceAllVarsWithUnknowns ty
453− Function [obj] ret -> do
455− inferBinder obj binder
456− _ -> throwError $ "Constructor " ++ show ctor ++ " is not a unary constructor"
457− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
458−inferBinder val (ObjectBinder props) = do
461− m1 <- inferRowProperties row rest props
465− inferRowProperties :: Type -> Type -> [(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
487−checkBinders :: [Type] -> Type -> [([Binder], Maybe Guard, Value)] -> Subst [([Binder], Maybe Guard, Value)]
488−checkBinders _ _ [] = return []
489−checkBinders nvals ret ((binders, grd, val):bs) = do
490− moduleName <- substCurrentModule <$> ask
491− m1 <- M.unions <$> zipWithM inferBinder nvals binders
492− r <- bindLocalVariables moduleName (M.toList m1) $ do
493− val' <- check val ret
495− Nothing -> return (binders, Nothing, val')
497− g' <- check g Boolean
498− return (binders, Just g', val')
499− rs <- checkBinders nvals ret bs
502−assignVariable :: Ident -> Subst ()
503−assignVariable name = do
504− env <- checkEnv <$> get
505− moduleName <- substCurrentModule <$> ask
506− case M.lookup (moduleName, 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, Statement)
511−checkStatement mass _ (VariableIntroduction name val) = do
513− val'@(TypedValue _ t) <- infer val
514− return (False, M.insert name t mass, VariableIntroduction name val')
515−checkStatement mass _ (Assignment ident val) = do
516− val'@(TypedValue _ t) <- infer val
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, Assignment ident val')
521−checkStatement mass ret (While val inner) = do
522− val' <- check val Boolean
523− (allCodePathsReturn, _, inner') <- checkBlock mass ret inner
524− return (allCodePathsReturn, mass, While val' inner')
525−checkStatement mass ret (If ifst) = do
526− (allCodePathsReturn, ifst') <- checkIfStatement mass ret ifst
527− return (allCodePathsReturn, mass, If ifst')
528−checkStatement mass ret (For ident start end inner) = do
529− moduleName <- substCurrentModule <$> ask
530− assignVariable ident
531− start' <- check start Number
532− end' <- check end Number
533− (allCodePathsReturn, _, inner') <- bindLocalVariables moduleName [(ident, Number)] $ checkBlock mass ret inner
534− return (allCodePathsReturn, mass, For ident start' end' inner')
535−checkStatement mass ret (Return val) = do
536− val' <- check val ret
537− return (True, mass, Return val')
539−checkIfStatement :: M.Map Ident Type -> Type -> IfStatement -> Subst (Bool, IfStatement)
540−checkIfStatement mass ret (IfStatement val thens Nothing) = do
541− val' <- check val Boolean
542− (_, _, thens') <- checkBlock mass ret thens
543− return (False, IfStatement val' thens' Nothing)
544−checkIfStatement mass ret (IfStatement val thens (Just elses)) = do
545− val' <- check val Boolean
546− (allCodePathsReturn1, _, thens') <- checkBlock mass ret thens
547− (allCodePathsReturn2, elses') <- checkElseStatement mass ret elses
548− return (allCodePathsReturn1 && allCodePathsReturn2, IfStatement val' thens' (Just elses'))
550−checkElseStatement :: M.Map Ident Type -> Type -> ElseStatement -> Subst (Bool, ElseStatement)
551−checkElseStatement mass ret (Else elses) = do
552− (allCodePathsReturn, _, elses') <- checkBlock mass ret elses
553− return (allCodePathsReturn, Else elses')
554−checkElseStatement mass ret (ElseIf ifst) = (id *** ElseIf) <$> checkIfStatement mass ret ifst
556−checkBlock :: M.Map Ident Type -> Type -> [Statement] -> Subst (Bool, M.Map Ident Type, [Statement])
557−checkBlock mass _ [] = return (False, mass, [])
558−checkBlock mass ret (s:ss) = do
559− moduleName <- substCurrentModule <$> ask
560− (b1, mass1, s') <- checkStatement mass ret s
561− bindLocalVariables moduleName (M.toList mass1) $ case (b1, ss) of
562− (True, []) -> return (True, mass1, [s'])
563− (True, _) -> throwError "Unreachable code"
565− (b, m, ss'') <- checkBlock mass1 ret ss'
566− return (b, m, s':ss'')
568−skolemize :: String -> Type -> Subst Type
569−skolemize ident ty = do
570− tsk <- Skolem <$> fresh'
571− return $ replaceTypeVars ident tsk ty
573−check :: Value -> Type -> Subst Value
574−check val ty = rethrow errorMessage $ check' val ty
577− "Error checking type of term " ++
578− prettyPrintValue val ++
580− prettyPrintType ty ++
584−check' :: Value -> Type -> Subst Value
585−check' val (ForAll idents ty) = do
586− sk <- skolemize idents ty
588−check' val u@(TUnknown _) = do
589− val'@(TypedValue _ ty) <- infer val
590− -- Don't unify an unknown with an inferred polytype
591− ty' <- replaceAllVarsWithUnknowns ty
594−check' v@(NumericLiteral _) Number = return $ TypedValue v Number
595−check' v@(StringLiteral _) String = return $ TypedValue v String
596−check' v@(BooleanLiteral _) Boolean = return $ TypedValue v Boolean
597−check' (Unary op val) ty = checkUnary op val ty
598−check' (Binary op left right) ty = checkBinary op left right ty
599−check' (ArrayLiteral vals) (Array ty) = TypedValue <$> (ArrayLiteral <$> forM vals (\val -> check val ty)) <*> pure (Array ty)
600−check' (Indexer index vals) ty = check index Number >> check vals (Array ty)
601−check' (Abs args ret) (Function argTys retTy) = do
602− moduleName <- substCurrentModule <$> ask
603− guardWith "Incorrect number of function arguments" (length args == length argTys)
604− bindLocalVariables moduleName (zip args argTys) $ check ret retTy
605−check' (App f args) ret = do
606− f'@(TypedValue _ ft) <- infer f
607− args' <- checkFunctionApplication ft args ret
608− return $ TypedValue (App f' args') ret
609−check' (Var var) ty = do
610− moduleName <- substCurrentModule <$> ask
611− ty1 <- lookupVariable moduleName var
612− repl <- replaceAllTypeSynonyms ty1
614− return $ TypedValue (Var var) ty
615−check' v@(TypedValue val ty1) ty2 = do
616− moduleName <- substCurrentModule <$> ask
617− kind <- liftCheck $ kindOf moduleName ty1
618− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
622−check' (Case vals binders) ret = do
623− vals' <- mapM infer vals
624− let ts = map (\(TypedValue _ t) -> t) vals'
625− binders' <- checkBinders ts ret binders
626− return $ TypedValue (Case vals' binders') ret
627−check' (IfThenElse cond th el) ty = do
631−check' (ObjectLiteral ps) t@(Object row) = do
632− ensureNoDuplicateProperties ps
633− ps' <- checkProperties ps row False
634− return $ TypedValue (ObjectLiteral ps') t
635−check' (ObjectUpdate obj ps) t@(Object row) = do
636− ensureNoDuplicateProperties ps
637− us <- zip (map fst ps) <$> replicateM (length ps) fresh
638− let (propsToCheck, rest) = rowToList row
639− propsToRemove = map fst ps
640− remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
641− obj' <- check obj (Object (rowFromList (us ++ remainingProps, rest)))
642− ps' <- checkProperties ps row True
643− return $ TypedValue (ObjectUpdate obj' ps') t
644−check' (Accessor prop val) ty = do
646− check val (Object (RCons prop ty rest))
647−check' (Block ss) ret = do
648− (allCodePathsReturn, _, ss') <- checkBlock M.empty ret ss
649− guardWith "Block is missing a return statement" allCodePathsReturn
650− return $ TypedValue (Block ss') ret
651−check' (Constructor c) ty = do
653− moduleName <- substCurrentModule <$> ask
654− case M.lookup (qualify moduleName c) (dataConstructors env) of
655− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
657− repl <- replaceAllTypeSynonyms ty1
659− return $ TypedValue (Constructor c) ty
660−check' val (SaturatedTypeSynonym name args) = do
661− ty <- expandTypeSynonym name args
663−check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
665−checkProperties :: [(String, Value)] -> Type -> Bool -> Subst [(String, Value)]
666−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
667− go [] [] REmpty = return []
668− go [] [] u@(TUnknown _) = do u ~~ REmpty
670− go [] [] (Skolem _) | lax = return []
671− go [] ((p, _): _) _ | lax = return []
672− | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
673− go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
674− go ((p,v):ps') [] u@(TUnknown _) = do
675− v'@(TypedValue _ ty) <- infer v
677− u ~~ RCons p ty rest
678− ps'' <- go ps' [] rest
679− return $ (p, v') : ps''
680− go ((p,v):ps') ts r =
683− v'@(TypedValue _ ty) <- infer v
685− r ~~ RCons p ty rest
686− ps'' <- go ps' ts rest
687− return $ (p, v') : ps''
690− ps'' <- go ps' (delete (p, ty) ts) r
691− return $ (p, v') : ps''
692− go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
694−checkFunctionApplication :: Type -> [Value] -> Type -> Subst [Value]
695−checkFunctionApplication fnTy args ret = rethrow errorMessage $ checkFunctionApplication' fnTy args ret
697− errorMessage msg = "Error applying function of type "
698− ++ prettyPrintType fnTy
699− ++ " to arguments " ++ intercalate ", " (map prettyPrintValue args)
700− ++ ", expecting value of type "
701− ++ prettyPrintType ret ++ ":\n" ++ msg
703−inferFunctionApplication :: Type -> [Type] -> Subst Type
704−inferFunctionApplication (Function argTys retTy) args = do
705− guardWith "Incorrect number of function arguments" (length args == length argTys)
706− zipWithM subsumes args argTys
708−inferFunctionApplication (ForAll ident ty) args = do
709− replaced <- replaceVarWithUnknown ident ty
710− inferFunctionApplication replaced args
711−inferFunctionApplication u@(TUnknown _) args = do
713− args' <- mapM replaceAllVarsWithUnknowns args
714− u ~~ Function args' ret
716−inferFunctionApplication (SaturatedTypeSynonym name tyArgs) args = do
717− ty <- expandTypeSynonym name tyArgs
718− inferFunctionApplication ty args
719−inferFunctionApplication fnTy args = throwError $ "Cannot apply function of type "
720− ++ prettyPrintType fnTy
721− ++ " to argument(s) of type(s) " ++ intercalate ", " (map prettyPrintType args)
723−checkFunctionApplication' :: Type -> [Value] -> Type -> Subst [Value]
724−checkFunctionApplication' (Function argTys retTy) args ret = do
725− guardWith "Incorrect number of function arguments" (length args == length argTys)
726− args' <- zipWithM check args argTys
727− retTy `subsumes` ret
729−checkFunctionApplication' (ForAll ident ty) args ret = do
730− replaced <- replaceVarWithUnknown ident ty
731− checkFunctionApplication replaced args ret
732−checkFunctionApplication' u@(TUnknown _) args ret = do
733− args' <- mapM (\arg -> infer arg >>= \(TypedValue v t) -> TypedValue v <$> replaceAllVarsWithUnknowns t) args
734− let tys = map (\(TypedValue _ t) -> t) args'
735− u ~~ Function tys 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