@@ -0,0 +1,757 @@
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+{-# LANGUAGE DeriveDataTypeable, FlexibleContexts #-}
16+
17+module Language.PureScript.TypeChecker.Types (
18+ typesOf
19+) where
20+
21+import Data.List
22+import Data.Maybe (fromMaybe)
23+import Data.Either (lefts, rights)
24+import qualified Data.Data as D
25+import Data.Generics
26+ (mkT, something, everywhere, everywhereBut, mkQ, extQ)
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+
41+import Control.Applicative
42+import Control.Arrow (Arrow(..))
43+
44+import qualified Data.Map as M
45+
46+instance Unifiable Type where
47+ unknown = TUnknown
48+ isUnknown (TUnknown u) = Just u
49+ isUnknown _ = Nothing
50+ (~~) = unifyTypes
51+ apply s (TUnknown u) = runSubstitution s u
52+ apply s (SaturatedTypeSynonym name tys) = SaturatedTypeSynonym name $ map (apply s) tys
53+ apply s (ForAll idents ty) = ForAll idents $ apply s ty
54+ apply s (Array t) = Array (apply s t)
55+ apply s (Object r) = Object (apply s r)
56+ apply s (Function args ret) = Function (map (apply s) args) (apply s ret)
57+ apply s (TypeApp t1 t2) = TypeApp (apply s t1) (apply s t2)
58+ apply _ t = t
59+ unknowns (TUnknown (Unknown u)) = [u]
60+ unknowns (SaturatedTypeSynonym _ tys) = concatMap unknowns tys
61+ unknowns (ForAll _ ty) = unknowns ty
62+ unknowns (Array t) = unknowns t
63+ unknowns (Object r) = unknowns r
64+ unknowns (Function args ret) = concatMap unknowns args ++ unknowns ret
65+ unknowns (TypeApp t1 t2) = unknowns t1 ++ unknowns t2
66+ unknowns _ = []
67+
68+instance Unifiable Row where
69+ unknown = RUnknown
70+ isUnknown (RUnknown u) = Just u
71+ isUnknown _ = Nothing
72+ r1 ~~ r2 =
73+ let
74+ (s1, r1') = rowToList r1
75+ (s2, r2') = rowToList r2
76+ int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
77+ sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
78+ sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
79+ in do
80+ forM_ int (uncurry (~~))
81+ unifyRows sd1 r1' sd2 r2'
82+ where
83+ unifyRows :: [(String, Type)] -> Row -> [(String, Type)] -> Row -> Subst ()
84+ unifyRows [] (RUnknown u) sd r = replace u (rowFromList (sd, r))
85+ unifyRows sd r [] (RUnknown u) = replace u (rowFromList (sd, r))
86+ unifyRows ((name, ty):row) r others u@(RUnknown un) = do
87+ occursCheck un ty
88+ forM row $ \(_, t) -> occursCheck un t
89+ u' <- fresh
90+ u ~~ RCons name ty u'
91+ unifyRows row r others u'
92+ unifyRows [] REmpty [] REmpty = return ()
93+ unifyRows [] (RowVar v1) [] (RowVar v2) | v1 == v2 = return ()
94+ unifyRows [] (RSkolem s1) [] (RSkolem s2) | s1 == s2 = return ()
95+ unifyRows sd3 r3 sd4 r4 = throwError $ "Cannot unify " ++ prettyPrintRow (rowFromList (sd3, r3)) ++ " with " ++ prettyPrintRow (rowFromList (sd4, r4)) ++ "."
96+ apply s (RUnknown u) = runSubstitution s u
97+ apply s (RCons name ty r) = RCons name (apply s ty) (apply s r)
98+ apply _ r = r
99+ unknowns (RUnknown (Unknown u)) = [u]
100+ unknowns (RCons _ ty r) = unknowns ty ++ unknowns r
101+ unknowns _ = []
102+
103+unifyTypes :: Type -> Type -> Subst ()
104+unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $ do
105+ unifyTypes' t1 t2
106+ where
107+ unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
108+ unifyTypes' (TUnknown u) t = replace u t
109+ unifyTypes' t (TUnknown u) = replace u t
110+ unifyTypes' (SaturatedTypeSynonym name1 args1) (SaturatedTypeSynonym name2 args2)
111+ | name1 == name2 = zipWithM_ unifyTypes args1 args2
112+ unifyTypes' (SaturatedTypeSynonym name args) ty = do
113+ ty1 <- expandTypeSynonym name args
114+ ty1 `unifyTypes` ty
115+ unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
116+ unifyTypes' (ForAll ident1 ty1) (ForAll ident2 ty2) = do
117+ sk <- skolemize ident1 ty1
118+ replaced <- replaceVarWithUnknown ident2 ty2
119+ sk `unifyTypes` replaced
120+ unifyTypes' (ForAll ident ty1) ty2 = do
121+ sk <- skolemize ident ty1
122+ sk `unifyTypes` ty2
123+ unifyTypes' ty f@(ForAll _ _) = f `unifyTypes` ty
124+ unifyTypes' Number Number = return ()
125+ unifyTypes' String String = return ()
126+ unifyTypes' Boolean Boolean = return ()
127+ unifyTypes' (Array s) (Array t) = s `unifyTypes` t
128+ unifyTypes' (Object row1) (Object row2) = row1 ~~ row2
129+ unifyTypes' (Function args1 ret1) (Function args2 ret2) = do
130+ guardWith "Function applied to incorrect number of args" $ length args1 == length args2
131+ zipWithM_ unifyTypes args1 args2
132+ ret1 `unifyTypes` ret2
133+ unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
134+ unifyTypes' (TypeConstructor c1) (TypeConstructor c2) = do
135+ modulePath <- checkModulePath `fmap` get
136+ guardWith ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".") (qualify modulePath c1 == qualify modulePath c2)
137+ unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
138+ t3 `unifyTypes` t5
139+ t4 `unifyTypes` t6
140+ unifyTypes' (Skolem s1) (Skolem s2) | s1 == s2 = return ()
141+ unifyTypes' t3 t4 = throwError $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
142+
143+typesOf :: [(Ident, Value)] -> Check [Type]
144+typesOf vals = do
145+ (tys, sub, checks) <- runSubst $ do
146+ modulePath <- checkModulePath <$> get
147+ let es = map isTyped vals
148+ typed = lefts es
149+ untyped = rights es
150+ typedDict = map (\(ident, 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) -> ((modulePath, ident), (ty, LocalVariable))) $ typedDict ++ untypedDict)
154+ tys <- forM es $ \e -> case e of
155+ Left (_, ty, val) -> do
156+ kind <- liftCheck $ kindOf ty
157+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
158+ ty' <- replaceAllTypeSynonyms ty
159+ bindNames dict $ check val ty'
160+ return ty'
161+ Right (ident, val) -> do
162+ ty <- bindNames dict $ infer val
163+ ty ~~ fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
164+ return ty
165+ return tys
166+ forM tys $ flip (escapeCheck checks) sub
167+ forM tys $ skolemEscapeCheck
168+ return $ map (varIfUnknown . desaturateAllTypeSynonyms . setifyAll) tys
169+
170+isTyped :: (Ident, Value) -> Either (Ident, Type, Value) (Ident, Value)
171+isTyped (name, TypedValue value ty) = Left (name, ty, value)
172+isTyped (name, value) = Right (name, value)
173+
174+escapeCheck :: [AnyUnifiable] -> Type -> Substitution -> Check ()
175+escapeCheck checks ty sub =
176+ let
177+ visibleUnknowns = nub $ unknowns ty
178+ in
179+ forM_ checks $ \c -> case c of
180+ AnyUnifiable t -> do
181+ let unsolvedUnknowns = nub . unknowns $ apply sub t
182+ guardWith "Escape check fails" $ null $ unsolvedUnknowns \\ visibleUnknowns
183+
184+skolemEscapeCheck :: Type -> Check ()
185+skolemEscapeCheck ty =
186+ case something (extQ (mkQ Nothing findSkolems) findRSkolems) ty of
187+ Nothing -> return ()
188+ Just _ -> throwError "Skolem variables cannot escape. Consider adding a type signature."
189+ where
190+ findSkolems (Skolem _) = return ()
191+ findSkolems _ = mzero
192+ findRSkolems (RSkolem _) = return ()
193+ findRSkolems _ = mzero
194+
195+setify :: Row -> Row
196+setify = rowFromList . first (M.toList . M.fromList) . rowToList
197+
198+setifyAll :: (D.Data d) => d -> d
199+setifyAll = everywhere (mkT setify)
200+
201+varIfUnknown :: Type -> Type
202+varIfUnknown ty =
203+ let unks = nub $ unknowns ty
204+ toName = (:) 't' . show
205+ ty' = everywhere (mkT rowToVar) . everywhere (mkT typeToVar) $ ty
206+ typeToVar :: Type -> Type
207+ typeToVar (TUnknown (Unknown u)) = TypeVar (toName u)
208+ typeToVar t = t
209+ rowToVar :: Row -> Row
210+ rowToVar (RUnknown (Unknown u)) = RowVar (toName u)
211+ rowToVar 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+replaceRowVars :: (D.Data d) => String -> Row -> d -> d
226+replaceRowVars name r = everywhere (mkT replaceRowVar)
227+ where
228+ replaceRowVar (RowVar v) | v == name = r
229+ replaceRowVar other = other
230+
231+replaceAllVarsWithUnknowns :: Type -> Subst Type
232+replaceAllVarsWithUnknowns (ForAll ident ty) = replaceVarWithUnknown ident ty >>= replaceAllVarsWithUnknowns
233+replaceAllVarsWithUnknowns ty = return ty
234+
235+replaceVarWithUnknown :: String -> Type -> Subst Type
236+replaceVarWithUnknown ident ty = do
237+ tu <- fresh
238+ ru <- fresh
239+ return $ replaceRowVars ident ru . replaceTypeVars ident tu $ ty
240+
241+replaceAllTypeSynonyms :: (Functor m, MonadState CheckState m, MonadError String m) => (D.Data d) => d -> m d
242+replaceAllTypeSynonyms d = do
243+ env <- getEnv
244+ let syns = map (\((path, name), (args, _)) -> (Qualified path name, length args)) . M.toList $ typeSynonyms env
245+ either throwError return $ saturateAllTypeSynonyms syns d
246+
247+desaturateAllTypeSynonyms :: (D.Data d) => d -> d
248+desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
249+ where
250+ replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
251+ replaceSaturatedTypeSynonym t = t
252+
253+expandTypeSynonym :: Qualified ProperName -> [Type] -> Subst Type
254+expandTypeSynonym name args = do
255+ env <- getEnv
256+ modulePath <- checkModulePath `fmap` get
257+ case M.lookup (qualify modulePath name) (typeSynonyms env) of
258+ Just (synArgs, body) -> return $ replaceAllTypeVars (zip synArgs args) body
259+ Nothing -> error "Type synonym was not defined"
260+
261+ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
262+ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
263+
264+infer :: Value -> Subst Type
265+infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ do
266+ ty <- infer' val
267+ escapeCheckLater ty
268+ return ty
269+
270+infer' :: Value -> Subst Type
271+infer' (NumericLiteral _) = return Number
272+infer' (StringLiteral _) = return String
273+infer' (BooleanLiteral _) = return Boolean
274+infer' (ArrayLiteral vals) = do
275+ ts <- mapM (infer) vals
276+ els <- fresh
277+ forM_ ts $ \t -> els ~~ Array t
278+ return els
279+infer' (Unary op val) = do
280+ t <- infer val
281+ inferUnary op t
282+infer' (Binary op left right) = do
283+ t1 <- infer left
284+ t2 <- infer right
285+ inferBinary op t1 t2
286+infer' (ObjectLiteral ps) = do
287+ ensureNoDuplicateProperties ps
288+ ts <- mapM (infer . snd) ps
289+ let fields = zipWith (\(name, _) t -> (name, t)) ps ts
290+ return $ Object $ rowFromList (fields, REmpty)
291+infer' (ObjectUpdate o ps) = do
292+ ensureNoDuplicateProperties ps
293+ row <- fresh
294+ newTys <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
295+ oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
296+ check o $ Object $ rowFromList (oldTys, row)
297+ return $ Object $ rowFromList (newTys, row)
298+infer' (Indexer index val) = do
299+ el <- fresh
300+ check index Number
301+ check val (Array el)
302+ return el
303+infer' (Accessor prop val) = do
304+ obj <- infer val
305+ propTy <- inferProperty obj prop
306+ case propTy of
307+ Nothing -> do
308+ field <- fresh
309+ rest <- fresh
310+ obj `subsumes` Object (RCons prop field rest)
311+ return field
312+ Just ty -> return ty
313+infer' (Abs args ret) = do
314+ ts <- replicateM (length args) fresh
315+ bindLocalVariables (zip args ts) $ do
316+ body <- infer' ret
317+ return $ Function ts body
318+infer' app@(App _ _) = do
319+ let (f, argss) = unfoldApplication app
320+ ft <- infer f
321+ ret <- fresh
322+ checkFunctionApplications ft argss ret
323+ return ret
324+infer' (Var var) = do
325+ ty <- lookupVariable var
326+ replaceAllTypeSynonyms ty
327+infer' (Block ss) = do
328+ ret <- fresh
329+ (allCodePathsReturn, _) <- checkBlock M.empty ret ss
330+ guardWith "Block is missing a return statement" allCodePathsReturn
331+ return ret
332+infer' (Constructor c) = do
333+ env <- getEnv
334+ modulePath <- checkModulePath `fmap` get
335+ case M.lookup (qualify modulePath c) (dataConstructors env) of
336+ Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
337+ Just ty -> replaceAllTypeSynonyms ty
338+infer' (Case vals binders) = do
339+ ts <- mapM infer vals
340+ ret <- fresh
341+ checkBinders ts ret binders
342+ return ret
343+infer' (IfThenElse cond th el) = do
344+ check cond Boolean
345+ t2 <- infer th
346+ t3 <- infer el
347+ t2 ~~ t3
348+ return t2
349+infer' (TypedValue val ty) = do
350+ kind <- liftCheck $ kindOf ty
351+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
352+ ty' <- replaceAllTypeSynonyms ty
353+ check val ty'
354+ return ty'
355+infer' _ = error "Invalid argument to infer"
356+
357+inferProperty :: Type -> String -> Subst (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 _ _ = return Nothing
368+
369+inferUnary :: UnaryOperator -> Type -> Subst Type
370+inferUnary op val =
371+ case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
372+ (valTy, resTy) -> do
373+ val ~~ valTy
374+ return resTy
375+
376+checkUnary :: UnaryOperator -> Value -> Type -> Subst ()
377+checkUnary op val res =
378+ case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
379+ (valTy, resTy) -> do
380+ res ~~ resTy
381+ check val valTy
382+
383+unaryOps :: [(UnaryOperator, (Type, Type))]
384+unaryOps = [ (Negate, (Number, Number))
385+ , (Not, (Boolean, Boolean))
386+ , (BitwiseNot, (Number, Number))
387+ ]
388+
389+inferBinary :: BinaryOperator -> Type -> Type -> Subst Type
390+inferBinary op left right | isEqualityTest op = do
391+ left ~~ right
392+ return Boolean
393+inferBinary op left right =
394+ case fromMaybe (error "Invalid operator") $ lookup op binaryOps of
395+ (valTy, resTy) -> do
396+ left ~~ valTy
397+ right ~~ valTy
398+ return resTy
399+
400+checkBinary :: BinaryOperator -> Value -> Value -> Type -> Subst ()
401+checkBinary op left right res | isEqualityTest op = do
402+ res ~~ Boolean
403+ t1 <- infer left
404+ t2 <- infer right
405+ t1 ~~ t2
406+checkBinary op left right res =
407+ case fromMaybe (error "Invalid operator") $ lookup op binaryOps of
408+ (valTy, resTy) -> do
409+ res ~~ resTy
410+ check left valTy
411+ check right valTy
412+
413+isEqualityTest :: BinaryOperator -> Bool
414+isEqualityTest EqualTo = True
415+isEqualityTest NotEqualTo = True
416+isEqualityTest _ = False
417+
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))
437+ ]
438+
439+inferBinder :: Type -> Binder -> Subst (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
446+ env <- getEnv
447+ modulePath <- checkModulePath <$> get
448+ case M.lookup (qualify modulePath ctor) (dataConstructors env) of
449+ Just ty -> do
450+ ty `subsumes` val
451+ return M.empty
452+ _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
453+inferBinder val (UnaryBinder ctor binder) = do
454+ env <- getEnv
455+ modulePath <- checkModulePath <$> get
456+ case M.lookup (qualify modulePath ctor) (dataConstructors env) of
457+ Just ty -> do
458+ fn <- replaceAllVarsWithUnknowns ty
459+ case fn of
460+ Function [obj] ret -> do
461+ val `subsumes` ret
462+ inferBinder obj binder
463+ _ -> throwError $ "Constructor " ++ show ctor ++ " is not a unary constructor"
464+ _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
465+inferBinder val (ObjectBinder props) = do
466+ row <- fresh
467+ rest <- fresh
468+ m1 <- inferRowProperties row rest props
469+ val ~~ Object row
470+ return m1
471+ where
472+ inferRowProperties :: Row -> Row -> [(String, Binder)] -> Subst (M.Map Ident Type)
473+ inferRowProperties nrow row [] = nrow ~~ row >> return M.empty
474+ inferRowProperties nrow row ((name, binder):binders) = do
475+ propTy <- fresh
476+ m1 <- inferBinder propTy binder
477+ m2 <- inferRowProperties nrow (RCons name propTy row) binders
478+ return $ m1 `M.union` m2
479+inferBinder val (ArrayBinder binders) = do
480+ el <- fresh
481+ m1 <- M.unions <$> mapM (inferBinder el) binders
482+ val ~~ Array el
483+ return m1
484+inferBinder val (ConsBinder headBinder tailBinder) = do
485+ el <- fresh
486+ m1 <- inferBinder el headBinder
487+ m2 <- inferBinder val tailBinder
488+ val ~~ Array el
489+ return $ m1 `M.union` m2
490+inferBinder val (NamedBinder name binder) = do
491+ m <- inferBinder val binder
492+ return $ M.insert name val m
493+
494+checkBinders :: [Type] -> Type -> [([Binder], Maybe Guard, Value)] -> Subst ()
495+checkBinders _ _ [] = return ()
496+checkBinders nvals ret ((binders, grd, val):bs) = do
497+ m1 <- M.unions <$> zipWithM inferBinder nvals binders
498+ bindLocalVariables (M.toList m1) $ do
499+ check val ret
500+ case grd of
501+ Nothing -> return ()
502+ Just g -> check g Boolean
503+ checkBinders nvals ret bs
504+
505+assignVariable :: Ident -> Subst ()
506+assignVariable name = do
507+ env <- checkEnv <$> get
508+ modulePath <- checkModulePath <$> get
509+ case M.lookup (modulePath, name) (names env) of
510+ Just (_, LocalVariable) -> throwError $ "Variable with name " ++ show name ++ " already exists."
511+ _ -> return ()
512+
513+checkStatement :: M.Map Ident Type -> Type -> Statement -> Subst (Bool, M.Map Ident Type)
514+checkStatement mass _ (VariableIntroduction name val) = do
515+ assignVariable name
516+ t <- infer val
517+ return (False, M.insert name t mass)
518+checkStatement mass _ (Assignment ident val) = do
519+ t <- infer val
520+ case M.lookup ident mass of
521+ Nothing -> throwError $ "No local variable with name " ++ show ident
522+ Just ty -> do t ~~ ty
523+ return (False, mass)
524+checkStatement mass ret (While val inner) = do
525+ check val Boolean
526+ (allCodePathsReturn, _) <- checkBlock mass ret inner
527+ return (allCodePathsReturn, mass)
528+checkStatement mass ret (If ifst) = do
529+ allCodePathsReturn <- checkIfStatement mass ret ifst
530+ return (allCodePathsReturn, mass)
531+checkStatement mass ret (For ident start end inner) = do
532+ assignVariable ident
533+ check start Number
534+ check end Number
535+ (allCodePathsReturn, _) <- bindLocalVariables [(ident, Number)] $ checkBlock mass ret inner
536+ return (allCodePathsReturn, mass)
537+checkStatement mass ret (ForEach ident vals inner) = do
538+ assignVariable ident
539+ val <- fresh
540+ check vals (Array val)
541+ (allCodePathsReturn, _) <- bindLocalVariables [(ident, val)] $ checkBlock mass ret inner
542+ guardWith "Cannot return from within a foreach block" $ not allCodePathsReturn
543+ return (False, mass)
544+checkStatement mass _ (ValueStatement val) = do
545+ check val unit
546+ return (False, mass)
547+checkStatement mass ret (Return val) = do
548+ check val ret
549+ return (True, mass)
550+
551+checkIfStatement :: M.Map Ident Type -> Type -> IfStatement -> Subst Bool
552+checkIfStatement mass ret (IfStatement val thens Nothing) = do
553+ check val Boolean
554+ _ <- checkBlock mass ret thens
555+ return False
556+checkIfStatement mass ret (IfStatement val thens (Just elses)) = do
557+ check val Boolean
558+ (allCodePathsReturn1, _) <- checkBlock mass ret thens
559+ allCodePathsReturn2 <- checkElseStatement mass ret elses
560+ return $ allCodePathsReturn1 && allCodePathsReturn2
561+
562+checkElseStatement :: M.Map Ident Type -> Type -> ElseStatement -> Subst Bool
563+checkElseStatement mass ret (Else elses) = fst <$> checkBlock mass ret elses
564+checkElseStatement mass ret (ElseIf ifst) = checkIfStatement mass ret ifst
565+
566+checkBlock :: M.Map Ident Type -> Type -> [Statement] -> Subst (Bool, M.Map Ident Type)
567+checkBlock mass _ [] = return (False, mass)
568+checkBlock mass ret (s:ss) = do
569+ (b1, mass1) <- checkStatement mass ret s
570+ bindLocalVariables (M.toList mass1) $ case (b1, ss) of
571+ (True, []) -> return (True, mass1)
572+ (True, _) -> throwError "Unreachable code"
573+ (False, ss') -> checkBlock mass1 ret ss'
574+
575+skolemize :: String -> Type -> Subst Type
576+skolemize ident ty = do
577+ tsk <- Skolem <$> fresh'
578+ rsk <- RSkolem <$> fresh'
579+ return $ replaceRowVars ident rsk $ replaceTypeVars ident tsk ty
580+
581+check :: Value -> Type -> Subst ()
582+check val ty = rethrow errorMessage $ check' val ty
583+ where
584+ errorMessage msg =
585+ "Error checking type of term " ++
586+ prettyPrintValue val ++
587+ " against type " ++
588+ prettyPrintType ty ++
589+ ":\n" ++
590+ msg
591+
592+check' :: Value -> Type -> Subst ()
593+check' val (ForAll idents ty) = do
594+ sk <- skolemize idents ty
595+ check val sk
596+check' val u@(TUnknown _) = do
597+ ty <- infer val
598+ -- Don't unify an unknown with an inferred polytype
599+ ty' <- replaceAllVarsWithUnknowns ty
600+ ty' ~~ u
601+check' (NumericLiteral _) Number = return ()
602+check' (StringLiteral _) String = return ()
603+check' (BooleanLiteral _) Boolean = return ()
604+check' (Unary op val) ty = checkUnary op val ty
605+check' (Binary op left right) ty = checkBinary op left right ty
606+check' (ArrayLiteral vals) (Array ty) = forM_ vals (\val -> check val ty)
607+check' (Indexer index vals) ty = check index Number >> check vals (Array ty)
608+check' (Abs args ret) (Function argTys retTy) = do
609+ guardWith "Incorrect number of function arguments" (length args == length argTys)
610+ bindLocalVariables (zip args argTys) $ check ret retTy
611+check' app@(App _ _) ret = do
612+ let (f, argss) = unfoldApplication app
613+ ft <- infer f
614+ checkFunctionApplications ft argss ret
615+check' (Var var) ty = do
616+ ty1 <- lookupVariable var
617+ repl <- replaceAllTypeSynonyms ty1
618+ repl `subsumes` ty
619+check' (TypedValue val ty1) ty2 = do
620+ kind <- liftCheck $ kindOf ty1
621+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
622+ ty1 `subsumes` ty2
623+ check val ty1
624+check' (Case vals binders) ret = do
625+ ts <- mapM infer vals
626+ checkBinders ts ret binders
627+check' (IfThenElse cond th el) ty = do
628+ check cond Boolean
629+ check th ty
630+ check el ty
631+check' (ObjectLiteral ps) (Object row) = do
632+ ensureNoDuplicateProperties ps
633+ checkProperties ps row False
634+check' (ObjectUpdate obj ps) (Object row) = do
635+ ensureNoDuplicateProperties ps
636+ us <- zip (map fst ps) <$> replicateM (length ps) fresh
637+ let (propsToCheck, rest) = rowToList row
638+ propsToRemove = map fst ps
639+ remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
640+ check obj (Object (rowFromList (us ++ remainingProps, rest)))
641+ checkProperties ps row True
642+check' (Accessor prop val) ty = do
643+ rest <- fresh
644+ check val (Object (RCons prop ty rest))
645+check' (Block ss) ret = do
646+ (allCodePathsReturn, _) <- checkBlock M.empty ret ss
647+ guardWith "Block is missing a return statement" allCodePathsReturn
648+check' (Constructor c) ty = do
649+ env <- getEnv
650+ modulePath <- checkModulePath <$> get
651+ case M.lookup (qualify modulePath c) (dataConstructors env) of
652+ Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
653+ Just ty1 -> do
654+ repl <- replaceAllTypeSynonyms ty1
655+ repl `subsumes` ty
656+check' val (SaturatedTypeSynonym name args) = do
657+ ty <- expandTypeSynonym name args
658+ check val ty
659+check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
660+
661+checkProperties :: [(String, Value)] -> Row -> Bool -> Subst ()
662+checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
663+ go [] [] REmpty = return ()
664+ go [] [] u@(RUnknown _) = u ~~ REmpty
665+ go [] [] (RSkolem _) | lax = return ()
666+ go [] ((p, _): _) _ | lax = return ()
667+ | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
668+ go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
669+ go ((p,v):ps') [] u@(RUnknown _) = do
670+ ty <- infer v
671+ rest <- fresh
672+ u ~~ RCons p ty rest
673+ go ps' [] rest
674+ go ((p,v):ps') ts r =
675+ case lookup p ts of
676+ Nothing -> do
677+ ty <- infer v
678+ rest <- fresh
679+ r ~~ RCons p ty rest
680+ go ps' ts rest
681+ Just ty -> do
682+ check v ty
683+ go ps' (delete (p, ty) ts) r
684+ go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
685+
686+unfoldApplication :: Value -> (Value, [[Value]])
687+unfoldApplication = go []
688+ where
689+ go argss (App f args) = go (args:argss) f
690+ go argss f = (f, argss)
691+
692+checkFunctionApplications :: Type -> [[Value]] -> Type -> Subst ()
693+checkFunctionApplications _ [] _ = error "Nullary function application"
694+checkFunctionApplications fnTy [args] ret = checkFunctionApplication fnTy args ret
695+checkFunctionApplications fnTy (args:argss) ret = do
696+ argTys <- mapM (infer) args
697+ f <- inferFunctionApplication fnTy argTys
698+ checkFunctionApplications f argss ret
699+
700+checkFunctionApplication :: Type -> [Value] -> Type -> Subst ()
701+checkFunctionApplication fnTy args ret = rethrow errorMessage $ checkFunctionApplication' fnTy args ret
702+ where
703+ errorMessage msg = "Error applying function of type "
704+ ++ prettyPrintType fnTy
705+ ++ " to arguments " ++ intercalate ", " (map prettyPrintValue args)
706+ ++ ", expecting value of type "
707+ ++ prettyPrintType ret ++ ":\n" ++ msg
708+
709+inferFunctionApplication :: Type -> [Type] -> Subst Type
710+inferFunctionApplication (Function argTys retTy) args = do
711+ guardWith "Incorrect number of function arguments" (length args == length argTys)
712+ zipWithM subsumes args argTys
713+ return retTy
714+inferFunctionApplication (ForAll ident ty) args = do
715+ replaced <- replaceVarWithUnknown ident ty
716+ inferFunctionApplication replaced args
717+inferFunctionApplication u@(TUnknown _) args = do
718+
719+ ret <- fresh
720+ args' <- mapM replaceAllVarsWithUnknowns args
721+ u ~~ Function args' ret
722+ return ret
723+inferFunctionApplication (SaturatedTypeSynonym name tyArgs) args = do
724+ ty <- expandTypeSynonym name tyArgs
725+ inferFunctionApplication ty args
726+inferFunctionApplication fnTy args = throwError $ "Cannot apply function of type "
727+ ++ prettyPrintType fnTy
728+ ++ " to argument(s) of type(s) " ++ intercalate ", " (map prettyPrintType args)
729+
730+checkFunctionApplication' :: Type -> [Value] -> Type -> Subst ()
731+checkFunctionApplication' (Function argTys retTy) args ret = do
732+ guardWith "Incorrect number of function arguments" (length args == length argTys)
733+ zipWithM (check) args argTys
734+ retTy `subsumes` ret
735+checkFunctionApplication' (ForAll ident ty) args ret = do
736+ replaced <- replaceVarWithUnknown ident ty
737+ checkFunctionApplication replaced args ret
738+checkFunctionApplication' u@(TUnknown _) args ret = do
739+ tyArgs <- mapM (\arg -> infer arg >>= replaceAllVarsWithUnknowns) args
740+ u ~~ Function tyArgs ret
741+checkFunctionApplication' (SaturatedTypeSynonym name tyArgs) args ret = do
742+ ty <- expandTypeSynonym name tyArgs
743+ checkFunctionApplication' ty args ret
744+checkFunctionApplication' fnTy args ret = throwError $ "Applying a function of type "
745+ ++ prettyPrintType fnTy
746+ ++ " to argument(s) " ++ intercalate ", " (map prettyPrintValue args)
747+ ++ " does not yield a value of type " ++ prettyPrintType ret ++ "."
748+
749+subsumes :: Type -> Type -> Subst ()
750+subsumes (ForAll ident ty1) ty2 = do
751+ replaced <- replaceVarWithUnknown ident ty1
752+ replaced `subsumes` ty2
753+subsumes (Function args1 ret1) (Function args2 ret2) = do
754+ zipWithM subsumes args2 args1
755+ ret1 `subsumes` ret2
756+subsumes ty1 ty2 = ty1 ~~ ty2
757+