@@ -1,749 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.TypeChecker.Types
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−--
13−-----------------------------------------------------------------------------
14−
15−{-# OPTIONS_GHC -fno-warn-orphans #-}
16−{-# LANGUAGE DeriveDataTypeable, FlexibleContexts #-}
17−
18−module Language.PureScript.TypeChecker.Types (
19− typesOf
20−) where
21−
22−import Data.List
23−import Data.Maybe (isNothing, isJust, fromMaybe)
24−import qualified Data.Data as D
25−import Data.Generics
26− (mkT, something, everywhere, everywhereBut, mkQ)
27−
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
37−
38−import Control.Monad.State
39−import Control.Monad.Error
40−import Control.Monad.Reader
41−
42−import Control.Applicative
43−import Control.Arrow (Arrow(..))
44−
45−import qualified Data.Map as M
46−import Data.Function (on)
47−
48−instance Unifiable Type where
49− unknown = TUnknown
50− isUnknown (TUnknown u) = Just u
51− isUnknown _ = Nothing
52− (~~) = unifyTypes
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)
61− apply _ t = t
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
70− unknowns _ = []
71−
72−unifyTypes :: Type -> Type -> Subst ()
73−unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $ do
74− unifyTypes' t1 t2
75− where
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
81− ty1 `unifyTypes` ty
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
89− sk `unifyTypes` ty2
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
102− env <- getEnv
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
106− t3 `unifyTypes` t5
107− t4 `unifyTypes` t6
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 ++ "."
114−
115−unifyRows :: Type -> Type -> Subst ()
116−unifyRows r1 r2 =
117− let
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 ]
123− in do
124− forM_ int (uncurry (~~))
125− unifyRows' sd1 r1' sd2 r2'
126− where
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
131− occursCheck un ty
132− forM row $ \(_, t) -> occursCheck un t
133− u' <- fresh
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)) ++ "."
140−
141−typeConstructorsAreEqual :: Environment -> ModuleName -> Qualified ProperName -> Qualified ProperName -> Bool
142−typeConstructorsAreEqual env moduleName = (==) `on` canonicalizeType moduleName env
143−
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
155− ty <- case e of
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'
161− return ty'
162− (ident, (val, Nothing)) -> do
163− ty <- bindNames dict $ infer val
164− ty ~~ fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
165− return ty
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
169− return ty
170− return tys
171− forM tys $ flip (escapeCheck checks) sub
172− forM tys $ skolemEscapeCheck
173− return $ map (varIfUnknown . desaturateAllTypeSynonyms . setifyAll) tys
174−
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))
178−
179−escapeCheck :: [AnyUnifiable] -> Type -> Substitution -> Check ()
180−escapeCheck checks ty sub =
181− let
182− visibleUnknowns = nub $ unknowns ty
183− in
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
188−
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."
194− where
195− findSkolems (Skolem _) = return ()
196− findSkolems _ = mzero
197−
198−setify :: Type -> Type
199−setify = rowFromList . first (M.toList . M.fromList) . rowToList
200−
201−setifyAll :: (D.Data d) => d -> d
202−setifyAll = everywhere (mkT setify)
203−
204−varIfUnknown :: Type -> Type
205−varIfUnknown ty =
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)
211− typeToVar t = t
212− in mkForAll (sort . map toName $ unks) ty'
213−
214−replaceAllTypeVars :: (D.Data d) => [(String, Type)] -> d -> d
215−replaceAllTypeVars = foldl' (\f (name, ty) -> replaceTypeVars name ty . f) id
216−
217−replaceTypeVars :: (D.Data d) => String -> Type -> d -> d
218−replaceTypeVars name t = everywhereBut (mkQ False isShadowed) (mkT replaceTypeVar)
219− where
220− replaceTypeVar (TypeVar v) | v == name = t
221− replaceTypeVar other = other
222− isShadowed (ForAll v _) | v == name = True
223− isShadowed _ = False
224−
225−replaceAllVarsWithUnknowns :: Type -> Subst Type
226−replaceAllVarsWithUnknowns (ForAll ident ty) = replaceVarWithUnknown ident ty >>= replaceAllVarsWithUnknowns
227−replaceAllVarsWithUnknowns ty = return ty
228−
229−replaceVarWithUnknown :: String -> Type -> Subst Type
230−replaceVarWithUnknown ident ty = do
231− tu <- fresh
232− return $ replaceTypeVars ident tu $ ty
233−
234−replaceAllTypeSynonyms :: (Functor m, MonadState CheckState m, MonadReader SubstContext m, MonadError String m) => (D.Data d) => d -> m d
235−replaceAllTypeSynonyms d = do
236− env <- getEnv
237− moduleName <- substCurrentModule <$> ask
238− let syns = map (\((path, name), (args, _)) -> ((path, name), length args)) . M.toList $ typeSynonyms env
239− either throwError return $ saturateAllTypeSynonyms env moduleName syns d
240−
241−desaturateAllTypeSynonyms :: (D.Data d) => d -> d
242−desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
243− where
244− replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
245− replaceSaturatedTypeSynonym t = t
246−
247−expandTypeSynonym :: Qualified ProperName -> [Type] -> Subst Type
248−expandTypeSynonym name args = do
249− env <- getEnv
250− moduleName <- substCurrentModule `fmap` ask
251− case M.lookup (canonicalizeType moduleName env name) (typeSynonyms env) of
252− Just (synArgs, body) -> return $ replaceAllTypeVars (zip synArgs args) body
253− Nothing -> error "Type synonym was not defined"
254−
255−ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
256−ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
257−
258−infer :: Value -> Subst Type
259−infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ do
260− ty <- infer' val
261− escapeCheckLater ty
262− return ty
263−
264−infer' :: Value -> Subst Type
265−infer' (NumericLiteral _) = return Number
266−infer' (StringLiteral _) = return String
267−infer' (BooleanLiteral _) = return Boolean
268−infer' (ArrayLiteral vals) = do
269− ts <- mapM (infer) vals
270− els <- fresh
271− forM_ ts $ \t -> els ~~ Array t
272− return els
273−infer' (Unary op val) = do
274− t <- infer val
275− inferUnary op t
276−infer' (Binary op left right) = do
277− t1 <- infer left
278− t2 <- infer right
279− inferBinary op t1 t2
280−infer' (ObjectLiteral ps) = do
281− ensureNoDuplicateProperties ps
282− ts <- mapM (infer . snd) ps
283− let fields = zipWith (\(name, _) t -> (name, t)) ps ts
284− return $ Object $ rowFromList (fields, REmpty)
285−infer' (ObjectUpdate o ps) = do
286− ensureNoDuplicateProperties ps
287− row <- fresh
288− newTys <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
289− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
290− check o $ Object $ rowFromList (oldTys, row)
291− return $ Object $ rowFromList (newTys, row)
292−infer' (Indexer index val) = do
293− el <- fresh
294− check index Number
295− check val (Array el)
296− return el
297−infer' (Accessor prop val) = do
298− obj <- infer val
299− propTy <- inferProperty obj prop
300− case propTy of
301− Nothing -> do
302− field <- fresh
303− rest <- fresh
304− obj `subsumes` Object (RCons prop field rest)
305− return field
306− Just ty -> return ty
307−infer' (Abs args ret) = do
308− ts <- replicateM (length args) fresh
309− moduleName <- substCurrentModule <$> ask
310− bindLocalVariables moduleName (zip args ts) $ do
311− body <- infer' ret
312− return $ Function ts body
313−infer' app@(App _ _) = do
314− let (f, argss) = unfoldApplication app
315− ft <- infer f
316− ret <- fresh
317− checkFunctionApplications ft argss ret
318− return ret
319−infer' (Var var) = do
320− moduleName <- substCurrentModule <$> ask
321− ty <- lookupVariable moduleName var
322− replaceAllTypeSynonyms ty
323−infer' (Block ss) = do
324− ret <- fresh
325− (allCodePathsReturn, _) <- checkBlock M.empty ret ss
326− guardWith "Block is missing a return statement" allCodePathsReturn
327− return ret
328−infer' (Constructor c) = do
329− env <- getEnv
330− moduleName <- substCurrentModule `fmap` ask
331− case M.lookup (qualify moduleName c) (dataConstructors env) of
332− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
333− Just (ty, _) -> replaceAllTypeSynonyms ty
334−infer' (Case vals binders) = do
335− ts <- mapM infer vals
336− ret <- fresh
337− checkBinders ts ret binders
338− return ret
339−infer' (IfThenElse cond th el) = do
340− check cond Boolean
341− t2 <- infer th
342− t3 <- infer el
343− t2 ~~ t3
344− return t2
345−infer' (TypedValue val ty) = do
346− moduleName <- substCurrentModule <$> ask
347− kind <- liftCheck $ kindOf moduleName ty
348− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
349− ty' <- replaceAllTypeSynonyms ty
350− check val ty'
351− return ty'
352−infer' _ = error "Invalid argument to infer"
353−
354−inferProperty :: Type -> String -> Subst (Maybe Type)
355−inferProperty (Object row) prop = do
356− let (props, _) = rowToList row
357− return $ lookup prop props
358−inferProperty (SaturatedTypeSynonym name args) prop = do
359− replaced <- expandTypeSynonym name args
360− inferProperty replaced prop
361−inferProperty (ForAll ident ty) prop = do
362− replaced <- replaceVarWithUnknown ident ty
363− inferProperty replaced prop
364−inferProperty _ _ = return Nothing
365−
366−inferUnary :: UnaryOperator -> Type -> Subst Type
367−inferUnary op val =
368− case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
369− (valTy, resTy) -> do
370− val ~~ valTy
371− return resTy
372−
373−checkUnary :: UnaryOperator -> Value -> Type -> Subst ()
374−checkUnary op val res =
375− case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
376− (valTy, resTy) -> do
377− res ~~ resTy
378− check val valTy
379−
380−unaryOps :: [(UnaryOperator, (Type, Type))]
381−unaryOps = [ (Negate, (Number, Number))
382− , (Not, (Boolean, Boolean))
383− , (BitwiseNot, (Number, Number))
384− ]
385−
386−inferBinary :: BinaryOperator -> Type -> Type -> Subst Type
387−inferBinary op left right | isEqualityTest op = do
388− left ~~ right
389− return Boolean
390−inferBinary op left right =
391− case fromMaybe (error "Invalid operator") $ lookup op binaryOps of
392− (valTy, resTy) -> do
393− left ~~ valTy
394− right ~~ valTy
395− return resTy
396−
397−checkBinary :: BinaryOperator -> Value -> Value -> Type -> Subst ()
398−checkBinary op left right res | isEqualityTest op = do
399− res ~~ Boolean
400− t1 <- infer left
401− t2 <- infer right
402− t1 ~~ t2
403−checkBinary op left right res =
404− case fromMaybe (error "Invalid operator") $ lookup op binaryOps of
405− (valTy, resTy) -> do
406− res ~~ resTy
407− check left valTy
408− check right valTy
409−
410−isEqualityTest :: BinaryOperator -> Bool
411−isEqualityTest EqualTo = True
412−isEqualityTest NotEqualTo = True
413−isEqualityTest _ = False
414−
415−binaryOps :: [(BinaryOperator, (Type, Type))]
416−binaryOps = [ (Add, (Number, Number))
417− , (Subtract, (Number, Number))
418− , (Multiply, (Number, Number))
419− , (Divide, (Number, Number))
420− , (Modulus, (Number, Number))
421− , (BitwiseAnd, (Number, Number))
422− , (BitwiseOr, (Number, Number))
423− , (BitwiseXor, (Number, Number))
424− , (ShiftRight, (Number, Number))
425− , (ZeroFillShiftRight, (Number, Number))
426− , (And, (Boolean, Boolean))
427− , (Or, (Boolean, Boolean))
428− , (Concat, (String, String))
429− , (Modulus, (Number, Number))
430− , (LessThan, (Number, Boolean))
431− , (LessThanOrEqualTo, (Number, Boolean))
432− , (GreaterThan, (Number, Boolean))
433− , (GreaterThanOrEqualTo, (Number, Boolean))
434− ]
435−
436−inferBinder :: Type -> Binder -> Subst (M.Map Ident Type)
437−inferBinder _ NullBinder = return M.empty
438−inferBinder val (StringBinder _) = val ~~ String >> return M.empty
439−inferBinder val (NumberBinder _) = val ~~ Number >> return M.empty
440−inferBinder val (BooleanBinder _) = val ~~ Boolean >> return M.empty
441−inferBinder val (VarBinder name) = return $ M.singleton name val
442−inferBinder val (NullaryBinder ctor) = do
443− env <- getEnv
444− moduleName <- substCurrentModule <$> ask
445− case M.lookup (qualify moduleName ctor) (dataConstructors env) of
446− Just (ty, _) -> do
447− ty `subsumes` val
448− return M.empty
449− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
450−inferBinder val (UnaryBinder ctor binder) = do
451− env <- getEnv
452− moduleName <- substCurrentModule <$> ask
453− case M.lookup (qualify moduleName ctor) (dataConstructors env) of
454− Just (ty, _) -> do
455− fn <- replaceAllVarsWithUnknowns ty
456− case fn of
457− Function [obj] ret -> do
458− val `subsumes` ret
459− inferBinder obj binder
460− _ -> throwError $ "Constructor " ++ show ctor ++ " is not a unary constructor"
461− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
462−inferBinder val (ObjectBinder props) = do
463− row <- fresh
464− rest <- fresh
465− m1 <- inferRowProperties row rest props
466− val ~~ Object row
467− return m1
468− where
469− inferRowProperties :: Type -> Type -> [(String, Binder)] -> Subst (M.Map Ident Type)
470− inferRowProperties nrow row [] = nrow ~~ row >> return M.empty
471− inferRowProperties nrow row ((name, binder):binders) = do
472− propTy <- fresh
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) = do
477− el <- fresh
478− m1 <- M.unions <$> mapM (inferBinder el) binders
479− val ~~ Array el
480− return m1
481−inferBinder val (ConsBinder headBinder tailBinder) = do
482− el <- fresh
483− m1 <- inferBinder el headBinder
484− m2 <- inferBinder val tailBinder
485− val ~~ Array el
486− return $ m1 `M.union` m2
487−inferBinder val (NamedBinder name binder) = do
488− m <- inferBinder val binder
489− return $ M.insert name val m
490−
491−checkBinders :: [Type] -> Type -> [([Binder], Maybe Guard, Value)] -> Subst ()
492−checkBinders _ _ [] = return ()
493−checkBinders nvals ret ((binders, grd, val):bs) = do
494− moduleName <- substCurrentModule <$> ask
495− m1 <- M.unions <$> zipWithM inferBinder nvals binders
496− bindLocalVariables moduleName (M.toList m1) $ do
497− check val ret
498− case grd of
499− Nothing -> return ()
500− Just g -> check g Boolean
501− checkBinders nvals ret bs
502−
503−assignVariable :: Ident -> Subst ()
504−assignVariable name = do
505− env <- checkEnv <$> get
506− moduleName <- substCurrentModule <$> ask
507− case M.lookup (moduleName, name) (names env) of
508− Just (_, LocalVariable) -> throwError $ "Variable with name " ++ show name ++ " already exists."
509− _ -> return ()
510−
511−checkStatement :: M.Map Ident Type -> Type -> Statement -> Subst (Bool, M.Map Ident Type)
512−checkStatement mass _ (VariableIntroduction name val) = do
513− assignVariable name
514− t <- infer val
515− return (False, M.insert name t mass)
516−checkStatement mass _ (Assignment ident val) = do
517− t <- infer val
518− case M.lookup ident mass of
519− Nothing -> throwError $ "No local variable with name " ++ show ident
520− Just ty -> do t ~~ ty
521− return (False, mass)
522−checkStatement mass ret (While val inner) = do
523− check val Boolean
524− (allCodePathsReturn, _) <- checkBlock mass ret inner
525− return (allCodePathsReturn, mass)
526−checkStatement mass ret (If ifst) = do
527− allCodePathsReturn <- checkIfStatement mass ret ifst
528− return (allCodePathsReturn, mass)
529−checkStatement mass ret (For ident start end inner) = do
530− moduleName <- substCurrentModule <$> ask
531− assignVariable ident
532− check start Number
533− check end Number
534− (allCodePathsReturn, _) <- bindLocalVariables moduleName [(ident, Number)] $ checkBlock mass ret inner
535− return (allCodePathsReturn, mass)
536−checkStatement mass ret (Return val) = do
537− check val ret
538− return (True, mass)
539−
540−checkIfStatement :: M.Map Ident Type -> Type -> IfStatement -> Subst Bool
541−checkIfStatement mass ret (IfStatement val thens Nothing) = do
542− check val Boolean
543− _ <- checkBlock mass ret thens
544− return False
545−checkIfStatement mass ret (IfStatement val thens (Just elses)) = do
546− check val Boolean
547− (allCodePathsReturn1, _) <- checkBlock mass ret thens
548− allCodePathsReturn2 <- checkElseStatement mass ret elses
549− return $ allCodePathsReturn1 && allCodePathsReturn2
550−
551−checkElseStatement :: M.Map Ident Type -> Type -> ElseStatement -> Subst Bool
552−checkElseStatement mass ret (Else elses) = fst <$> checkBlock mass ret elses
553−checkElseStatement mass ret (ElseIf ifst) = checkIfStatement mass ret ifst
554−
555−checkBlock :: M.Map Ident Type -> Type -> [Statement] -> Subst (Bool, M.Map Ident Type)
556−checkBlock mass _ [] = return (False, mass)
557−checkBlock mass ret (s:ss) = do
558− moduleName <- substCurrentModule <$> ask
559− (b1, mass1) <- checkStatement mass ret s
560− bindLocalVariables moduleName (M.toList mass1) $ case (b1, ss) of
561− (True, []) -> return (True, mass1)
562− (True, _) -> throwError "Unreachable code"
563− (False, ss') -> checkBlock mass1 ret ss'
564−
565−skolemize :: String -> Type -> Subst Type
566−skolemize ident ty = do
567− tsk <- Skolem <$> fresh'
568− return $ replaceTypeVars ident tsk ty
569−
570−check :: Value -> Type -> Subst ()
571−check val ty = rethrow errorMessage $ check' val ty
572− where
573− errorMessage msg =
574− "Error checking type of term " ++
575− prettyPrintValue val ++
576− " against type " ++
577− prettyPrintType ty ++
578− ":\n" ++
579− msg
580−
581−check' :: Value -> Type -> Subst ()
582−check' val (ForAll idents ty) = do
583− sk <- skolemize idents ty
584− check val sk
585−check' val u@(TUnknown _) = do
586− ty <- infer val
587− -- Don't unify an unknown with an inferred polytype
588− ty' <- replaceAllVarsWithUnknowns ty
589− ty' ~~ u
590−check' (NumericLiteral _) Number = return ()
591−check' (StringLiteral _) String = return ()
592−check' (BooleanLiteral _) Boolean = return ()
593−check' (Unary op val) ty = checkUnary op val ty
594−check' (Binary op left right) ty = checkBinary op left right ty
595−check' (ArrayLiteral vals) (Array ty) = forM_ vals (\val -> check val ty)
596−check' (Indexer index vals) ty = check index Number >> check vals (Array ty)
597−check' (Abs args ret) (Function argTys retTy) = do
598− moduleName <- substCurrentModule <$> ask
599− guardWith "Incorrect number of function arguments" (length args == length argTys)
600− bindLocalVariables moduleName (zip args argTys) $ check ret retTy
601−check' app@(App _ _) ret = do
602− let (f, argss) = unfoldApplication app
603− ft <- infer f
604− checkFunctionApplications ft argss ret
605−check' (Var var) ty = do
606− moduleName <- substCurrentModule <$> ask
607− ty1 <- lookupVariable moduleName var
608− repl <- replaceAllTypeSynonyms ty1
609− repl `subsumes` ty
610−check' (TypedValue val ty1) ty2 = do
611− moduleName <- substCurrentModule <$> ask
612− kind <- liftCheck $ kindOf moduleName ty1
613− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
614− ty1 `subsumes` ty2
615− check val ty1
616−check' (Case vals binders) ret = do
617− ts <- mapM infer vals
618− checkBinders ts ret binders
619−check' (IfThenElse cond th el) ty = do
620− check cond Boolean
621− check th ty
622− check el ty
623−check' (ObjectLiteral ps) (Object row) = do
624− ensureNoDuplicateProperties ps
625− checkProperties ps row False
626−check' (ObjectUpdate obj ps) (Object row) = do
627− ensureNoDuplicateProperties ps
628− us <- zip (map fst ps) <$> replicateM (length ps) fresh
629− let (propsToCheck, rest) = rowToList row
630− propsToRemove = map fst ps
631− remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
632− check obj (Object (rowFromList (us ++ remainingProps, rest)))
633− checkProperties ps row True
634−check' (Accessor prop val) ty = do
635− rest <- fresh
636− check val (Object (RCons prop ty rest))
637−check' (Block ss) ret = do
638− (allCodePathsReturn, _) <- checkBlock M.empty ret ss
639− guardWith "Block is missing a return statement" allCodePathsReturn
640−check' (Constructor c) ty = do
641− env <- getEnv
642− moduleName <- substCurrentModule <$> ask
643− case M.lookup (qualify moduleName c) (dataConstructors env) of
644− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
645− Just (ty1, _) -> do
646− repl <- replaceAllTypeSynonyms ty1
647− repl `subsumes` ty
648−check' val (SaturatedTypeSynonym name args) = do
649− ty <- expandTypeSynonym name args
650− check val ty
651−check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
652−
653−checkProperties :: [(String, Value)] -> Type -> Bool -> Subst ()
654−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
655− go [] [] REmpty = return ()
656− go [] [] u@(TUnknown _) = u ~~ REmpty
657− go [] [] (Skolem _) | lax = return ()
658− go [] ((p, _): _) _ | lax = return ()
659− | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
660− go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
661− go ((p,v):ps') [] u@(TUnknown _) = do
662− ty <- infer v
663− rest <- fresh
664− u ~~ RCons p ty rest
665− go ps' [] rest
666− go ((p,v):ps') ts r =
667− case lookup p ts of
668− Nothing -> do
669− ty <- infer v
670− rest <- fresh
671− r ~~ RCons p ty rest
672− go ps' ts rest
673− Just ty -> do
674− check v ty
675− go ps' (delete (p, ty) ts) r
676− go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
677−
678−unfoldApplication :: Value -> (Value, [[Value]])
679−unfoldApplication = go []
680− where
681− go argss (App f args) = go (args:argss) f
682− go argss f = (f, argss)
683−
684−checkFunctionApplications :: Type -> [[Value]] -> Type -> Subst ()
685−checkFunctionApplications _ [] _ = error "Nullary function application"
686−checkFunctionApplications fnTy [args] ret = checkFunctionApplication fnTy args ret
687−checkFunctionApplications fnTy (args:argss) ret = do
688− argTys <- mapM (infer) args
689− f <- inferFunctionApplication fnTy argTys
690− checkFunctionApplications f argss ret
691−
692−checkFunctionApplication :: Type -> [Value] -> Type -> Subst ()
693−checkFunctionApplication fnTy args ret = rethrow errorMessage $ checkFunctionApplication' fnTy args ret
694− where
695− errorMessage msg = "Error applying function of type "
696− ++ prettyPrintType fnTy
697− ++ " to arguments " ++ intercalate ", " (map prettyPrintValue args)
698− ++ ", expecting value of type "
699− ++ prettyPrintType ret ++ ":\n" ++ msg
700−
701−inferFunctionApplication :: Type -> [Type] -> Subst Type
702−inferFunctionApplication (Function argTys retTy) args = do
703− guardWith "Incorrect number of function arguments" (length args == length argTys)
704− zipWithM subsumes args argTys
705− return retTy
706−inferFunctionApplication (ForAll ident ty) args = do
707− replaced <- replaceVarWithUnknown ident ty
708− inferFunctionApplication replaced args
709−inferFunctionApplication u@(TUnknown _) args = do
710−
711− ret <- fresh
712− args' <- mapM replaceAllVarsWithUnknowns args
713− u ~~ Function args' ret
714− return ret
715−inferFunctionApplication (SaturatedTypeSynonym name tyArgs) args = do
716− ty <- expandTypeSynonym name tyArgs
717− inferFunctionApplication ty args
718−inferFunctionApplication fnTy args = throwError $ "Cannot apply function of type "
719− ++ prettyPrintType fnTy
720− ++ " to argument(s) of type(s) " ++ intercalate ", " (map prettyPrintType args)
721−
722−checkFunctionApplication' :: Type -> [Value] -> Type -> Subst ()
723−checkFunctionApplication' (Function argTys retTy) args ret = do
724− guardWith "Incorrect number of function arguments" (length args == length argTys)
725− zipWithM (check) args argTys
726− retTy `subsumes` ret
727−checkFunctionApplication' (ForAll ident ty) args ret = do
728− replaced <- replaceVarWithUnknown ident ty
729− checkFunctionApplication replaced args ret
730−checkFunctionApplication' u@(TUnknown _) args ret = do
731− tyArgs <- mapM (\arg -> infer arg >>= replaceAllVarsWithUnknowns) args
732− u ~~ Function tyArgs ret
733−checkFunctionApplication' (SaturatedTypeSynonym name tyArgs) args ret = do
734− ty <- expandTypeSynonym name tyArgs
735− checkFunctionApplication' ty args ret
736−checkFunctionApplication' fnTy args ret = throwError $ "Applying a function of type "
737− ++ prettyPrintType fnTy
738− ++ " to argument(s) " ++ intercalate ", " (map prettyPrintValue args)
739− ++ " does not yield a value of type " ++ prettyPrintType ret ++ "."
740−
741−subsumes :: Type -> Type -> Subst ()
742−subsumes (ForAll ident ty1) ty2 = do
743− replaced <- replaceVarWithUnknown ident ty1
744− replaced `subsumes` ty2
745−subsumes (Function args1 ret1) (Function args2 ret2) = do
746− zipWithM subsumes args2 args1
747− ret1 `subsumes` ret2
748−subsumes ty1 ty2 = ty1 ~~ ty2
749−