@@ -9,6 +9,7 @@
9-- Portability :
9-- Portability :
12+-- This module implements the type checker
13-----------------------------------------------------------------------------
14-----------------------------------------------------------------------------
@@ -67,6 +68,9 @@ instance Unifiable Type where
67 unknowns (RCons _ ty r) = unknowns ty ++ unknowns r
68 unknowns (RCons _ ty r) = unknowns ty ++ unknowns r
68 unknowns _ = []
69 unknowns _ = []
72+-- Unify two types, updating the current substitution
70unifyTypes :: Type -> Type -> Subst ()
74unifyTypes :: Type -> Type -> Subst ()
71unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $ do
75unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $ do
72 unifyTypes' t1 t2
76 unifyTypes' t1 t2
@@ -110,6 +114,13 @@ unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 +
110 unifyTypes' r1 r2@REmpty = unifyRows r1 r2
114 unifyTypes' r1 r2@REmpty = unifyRows r1 r2
111 unifyTypes' t3 t4 = throwError $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
115 unifyTypes' t3 t4 = throwError $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
118+-- Unify two rows, updating the current substitution
120+-- Common labels are first identified, and unified. Remaining labels and types are unified with a
121+-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
113unifyRows :: Type -> Type -> Subst ()
124unifyRows :: Type -> Type -> Subst ()
114unifyRows r1 r2 =
125unifyRows r1 r2 =
@@ -136,9 +147,16 @@ unifyRows r1 r2 =
136 unifyRows' [] (Skolem s1) [] (Skolem s2) | s1 == s2 = return ()
147 unifyRows' [] (Skolem s1) [] (Skolem s2) | s1 == s2 = return ()
137 unifyRows' sd3 r3 sd4 r4 = throwError $ "Cannot unify " ++ prettyPrintRow (rowFromList (sd3, r3)) ++ " with " ++ prettyPrintRow (rowFromList (sd4, r4)) ++ "."
148 unifyRows' sd3 r3 sd4 r4 = throwError $ "Cannot unify " ++ prettyPrintRow (rowFromList (sd3, r3)) ++ " with " ++ prettyPrintRow (rowFromList (sd4, r4)) ++ "."
151+-- Ensure type constructors are equal after canonicalization
139typeConstructorsAreEqual :: Environment -> ModuleName -> Qualified ProperName -> Qualified ProperName -> Bool
153typeConstructorsAreEqual :: Environment -> ModuleName -> Qualified ProperName -> Qualified ProperName -> Bool
140typeConstructorsAreEqual env moduleName = (==) `on` canonicalizeType moduleName env
154typeConstructorsAreEqual env moduleName = (==) `on` canonicalizeType moduleName env
157+-- Infer the types of multiple mutually-recursive values, and return elaborated values including
158+-- type class dictionaries and type annotations.
142typesOf :: ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
160typesOf :: ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
143typesOf moduleName vals = do
161typesOf moduleName vals = do
144 tys <- fmap (\(tys, s) -> map (\(ident, (val, ty)) -> (ident, (overTypes (apply s) val, apply s ty))) tys)
162 tys <- fmap (\(tys, s) -> map (\(ident, (val, ty)) -> (ident, (overTypes (apply s) val, apply s ty))) tys)
@@ -173,19 +191,32 @@ typesOf moduleName vals = do
173 return (ident, (overTypes (desaturateAllTypeSynonyms . setifyAll) $ val'
191 return (ident, (overTypes (desaturateAllTypeSynonyms . setifyAll) $ val'
174 , varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty))
192 , varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty))
195+-- Check if a value contains a type annotation
176isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
197isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
177isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
198isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
178isTyped (name, value) = (name, (value, Nothing))
199isTyped (name, value) = (name, (value, Nothing))
202+-- Map a function over type annotations appearing inside a value
180overTypes :: (Type -> Type) -> Value -> Value
204overTypes :: (Type -> Type) -> Value -> Value
181overTypes f = everywhere (mkT f)
205overTypes f = everywhere (mkT f)
208+-- Replace type class dictionary placeholders with inferred type class dictionaries
183replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
210replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
184replaceTypeClassDictionaries mn = everywhereM (mkM go)
211replaceTypeClassDictionaries mn = everywhereM (mkM go)
186 go (TypeClassDictionary constraint dicts) = entails mn dicts constraint
213 go (TypeClassDictionary constraint dicts) = entails mn dicts constraint
187 go other = return other
214 go other = return other
217+-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
218+-- return a type class dictionary reference.
189entails :: ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, Type) -> Check Value
220entails :: ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, Type) -> Check Value
190entails moduleName context goal@(className, ty) = do
221entails moduleName context goal@(className, ty) = do
191 env <- getEnv
222 env <- getEnv
@@ -211,6 +242,10 @@ entails moduleName context goal@(className, ty) = do
211 canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDRegular, tcdName = nm }) = nm
242 canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDRegular, tcdName = nm }) = nm
212 canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDAlias nm }) = nm
243 canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDAlias nm }) = nm
246+-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
247+-- and return a substitution from type variables to types which makes the type heads unify.
214typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
249typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
215typeHeadsAreEqual _ _ String String = Just []
250typeHeadsAreEqual _ _ String String = Just []
216typeHeadsAreEqual _ _ Number Number = Just []
251typeHeadsAreEqual _ _ Number Number = Just []
@@ -222,6 +257,9 @@ typeHeadsAreEqual m e (TypeApp h1 (TypeVar v)) (TypeApp h2 arg) = (:) (v, arg) <
222typeHeadsAreEqual m e t1@(TypeApp _ _) t2@(TypeApp _ (TypeVar _)) = typeHeadsAreEqual m e t2 t1
257typeHeadsAreEqual m e t1@(TypeApp _ _) t2@(TypeApp _ (TypeVar _)) = typeHeadsAreEqual m e t2 t1
223typeHeadsAreEqual _ _ _ _ = Nothing
258typeHeadsAreEqual _ _ _ _ = Nothing
261+-- Ensure unsolved unification variables do not escape
225escapeCheck :: Value -> Type -> Subst ()
263escapeCheck :: Value -> Type -> Subst ()
226escapeCheck value ty = do
264escapeCheck value ty = do
227 subst <- substSubst <$> getSubstState
265 subst <- substSubst <$> getSubstState
@@ -231,12 +269,18 @@ escapeCheck value ty = do
231 let unsolvedUnknowns = nub . unknowns $ apply subst t
269 let unsolvedUnknowns = nub . unknowns $ apply subst t
232 guardWith "Escape check fails" $ null $ unsolvedUnknowns \\ visibleUnknowns
270 guardWith "Escape check fails" $ null $ unsolvedUnknowns \\ visibleUnknowns
273+-- Find all type annotations occuring inside a value
234findAllTypes :: Value -> [Type]
275findAllTypes :: Value -> [Type]
235findAllTypes = everything (++) (mkQ [] go)
276findAllTypes = everything (++) (mkQ [] go)
237 go (TypedValue _ _ ty) = [ty]
278 go (TypedValue _ _ ty) = [ty]
238 go _ = []
279 go _ = []
282+-- Ensure skolem variables do not escape their scope
240skolemEscapeCheck :: Type -> Check ()
284skolemEscapeCheck :: Type -> Check ()
241skolemEscapeCheck ty =
285skolemEscapeCheck ty =
242 case something (mkQ Nothing findSkolems) ty of
286 case something (mkQ Nothing findSkolems) ty of
@@ -246,12 +290,21 @@ skolemEscapeCheck ty =
246 findSkolems (Skolem _) = return ()
290 findSkolems (Skolem _) = return ()
247 findSkolems _ = mzero
291 findSkolems _ = mzero
294+-- Ensure a row contains no duplicate labels
249setify :: Type -> Type
296setify :: Type -> Type
250setify = rowFromList . first (M.toList . M.fromList) . rowToList
297setify = rowFromList . first (M.toList . M.fromList) . rowToList
300+-- \"Setify\" all rows occuring inside a value
252setifyAll :: (D.Data d) => d -> d
302setifyAll :: (D.Data d) => d -> d
253setifyAll = everywhere (mkT setify)
303setifyAll = everywhere (mkT setify)
306+-- Replace outermost unsolved unification variables with named type variables
255varIfUnknown :: Type -> Type
308varIfUnknown :: Type -> Type
256varIfUnknown ty =
309varIfUnknown ty =
257 let unks = nub $ unknowns ty
310 let unks = nub $ unknowns ty
@@ -262,18 +315,31 @@ varIfUnknown ty =
262 typeToVar t = t
315 typeToVar t = t
263 in mkForAll (sort . map toName $ unks) ty'
316 in mkForAll (sort . map toName $ unks) ty'
319+-- Replace named type variables with types
265replaceAllTypeVars :: (D.Data d) => [(String, Type)] -> d -> d
321replaceAllTypeVars :: (D.Data d) => [(String, Type)] -> d -> d
266replaceAllTypeVars = foldl' (\f (name, ty) -> replaceTypeVars name ty . f) id
322replaceAllTypeVars = foldl' (\f (name, ty) -> replaceTypeVars name ty . f) id
325+-- Replace named type variables with new unification variables
268replaceAllVarsWithUnknowns :: Type -> Subst Type
327replaceAllVarsWithUnknowns :: Type -> Subst Type
269replaceAllVarsWithUnknowns (ForAll ident ty) = replaceVarWithUnknown ident ty >>= replaceAllVarsWithUnknowns
328replaceAllVarsWithUnknowns (ForAll ident ty) = replaceVarWithUnknown ident ty >>= replaceAllVarsWithUnknowns
270replaceAllVarsWithUnknowns ty = return ty
329replaceAllVarsWithUnknowns ty = return ty
332+-- Replace a single type variable with a new unification variable
272replaceVarWithUnknown :: String -> Type -> Subst Type
334replaceVarWithUnknown :: String -> Type -> Subst Type
273replaceVarWithUnknown ident ty = do
335replaceVarWithUnknown ident ty = do
274 tu <- fresh
336 tu <- fresh
275 return $ replaceTypeVars ident tu $ ty
337 return $ replaceTypeVars ident tu $ ty
340+-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
341+-- better error messages during unification.
277replaceAllTypeSynonyms :: (Functor m, MonadState CheckState m, MonadReader SubstContext m, MonadError String m) => (D.Data d) => d -> m d
343replaceAllTypeSynonyms :: (Functor m, MonadState CheckState m, MonadReader SubstContext m, MonadError String m) => (D.Data d) => d -> m d
278replaceAllTypeSynonyms d = do
344replaceAllTypeSynonyms d = do
279 env <- getEnv
345 env <- getEnv
@@ -281,12 +347,18 @@ replaceAllTypeSynonyms d = do
281 let syns = map (\((path, name), (args, _)) -> ((path, name), length args)) . M.toList $ typeSynonyms env
347 let syns = map (\((path, name), (args, _)) -> ((path, name), length args)) . M.toList $ typeSynonyms env
282 either throwError return $ saturateAllTypeSynonyms env moduleName syns d
348 either throwError return $ saturateAllTypeSynonyms env moduleName syns d
351+-- \"Desaturate\" @SaturatedTypeSynonym@s
284desaturateAllTypeSynonyms :: (D.Data d) => d -> d
353desaturateAllTypeSynonyms :: (D.Data d) => d -> d
285desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
354desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
287 replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
356 replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
288 replaceSaturatedTypeSynonym t = t
357 replaceSaturatedTypeSynonym t = t
360+-- Replace a type synonym and its arguments with the aliased type
290expandTypeSynonym :: Qualified ProperName -> [Type] -> Subst Type
362expandTypeSynonym :: Qualified ProperName -> [Type] -> Subst Type
291expandTypeSynonym name args = do
363expandTypeSynonym name args = do
292 env <- getEnv
364 env <- getEnv
@@ -295,12 +367,21 @@ expandTypeSynonym name args = do
295 Just (synArgs, body) -> return $ replaceAllTypeVars (zip synArgs args) body
367 Just (synArgs, body) -> return $ replaceAllTypeVars (zip synArgs args) body
296 Nothing -> error "Type synonym was not defined"
368 Nothing -> error "Type synonym was not defined"
371+-- Ensure a set of property names and value does not contain duplicate labels
298ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
373ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
299ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
374ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
377+-- Infer a type for a value, rethrowing any error to provide a more useful error message
301infer :: Value -> Subst Value
379infer :: Value -> Subst Value
302infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
380infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
383+-- Infer a type for a value
304infer' :: Value -> Subst Value
385infer' :: Value -> Subst Value
305infer' v@(NumericLiteral _) = return $ TypedValue True v Number
386infer' v@(NumericLiteral _) = return $ TypedValue True v Number
306infer' v@(StringLiteral _) = return $ TypedValue True v String
387infer' v@(StringLiteral _) = return $ TypedValue True v String
@@ -399,6 +480,9 @@ infer' (TypedValue checkType val ty) = do
399 return $ TypedValue True val' ty
480 return $ TypedValue True val' ty
400infer' _ = error "Invalid argument to infer"
481infer' _ = error "Invalid argument to infer"
484+-- Infer the type of a property inside a record with a given type
402inferProperty :: Type -> String -> Subst (Maybe Type)
486inferProperty :: Type -> String -> Subst (Maybe Type)
403inferProperty (Object row) prop = do
487inferProperty (Object row) prop = do
404 let (props, _) = rowToList row
488 let (props, _) = rowToList row
@@ -411,6 +495,9 @@ inferProperty (ForAll ident ty) prop = do
411 inferProperty replaced prop
495 inferProperty replaced prop
412inferProperty _ _ = return Nothing
496inferProperty _ _ = return Nothing
499+-- Infer the type of a unary operator application
414inferUnary :: UnaryOperator -> Value -> Subst Value
501inferUnary :: UnaryOperator -> Value -> Subst Value
415inferUnary op (TypedValue _ val valTy) =
502inferUnary op (TypedValue _ val valTy) =
416 case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
503 case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
@@ -419,6 +506,9 @@ inferUnary op (TypedValue _ val valTy) =
419 return $ TypedValue True (Unary op val) resTy
506 return $ TypedValue True (Unary op val) resTy
420inferUnary _ _ = error "Invalid arguments to inferUnary"
507inferUnary _ _ = error "Invalid arguments to inferUnary"
510+-- Check the type of a unary operator application
422checkUnary :: UnaryOperator -> Value -> Type -> Subst Value
512checkUnary :: UnaryOperator -> Value -> Type -> Subst Value
423checkUnary op val res =
513checkUnary op val res =
424 case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
514 case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
@@ -427,12 +517,18 @@ checkUnary op val res =
427 val' <- check val valTy
517 val' <- check val valTy
428 return $ Unary op val'
518 return $ Unary op val'
521+-- Built-in unary operators
430unaryOps :: [(UnaryOperator, (Type, Type))]
523unaryOps :: [(UnaryOperator, (Type, Type))]
431unaryOps = [ (Negate, (Number, Number))
524unaryOps = [ (Negate, (Number, Number))
432 , (Not, (Boolean, Boolean))
525 , (Not, (Boolean, Boolean))
433 , (BitwiseNot, (Number, Number))
526 , (BitwiseNot, (Number, Number))
530+-- Infer the type of a binary operator application
436inferBinary :: BinaryOperator -> Value -> Value -> Subst Value
532inferBinary :: BinaryOperator -> Value -> Value -> Subst Value
437inferBinary op left@(TypedValue _ _ leftTy) right@(TypedValue _ _ rightTy) | isEqualityTest op = do
533inferBinary op left@(TypedValue _ _ leftTy) right@(TypedValue _ _ rightTy) | isEqualityTest op = do
438 leftTy ~~ rightTy
534 leftTy ~~ rightTy
@@ -445,6 +541,9 @@ inferBinary op left@(TypedValue _ _ leftTy) right@(TypedValue _ _ rightTy) =
445 return $ TypedValue True (Binary op left right) resTy
541 return $ TypedValue True (Binary op left right) resTy
446inferBinary _ _ _ = error "Invalid arguments to inferBinary"
542inferBinary _ _ _ = error "Invalid arguments to inferBinary"
545+-- Check the type of a binary operator application
448checkBinary :: BinaryOperator -> Value -> Value -> Type -> Subst Value
547checkBinary :: BinaryOperator -> Value -> Value -> Type -> Subst Value
449checkBinary op left right res | isEqualityTest op = do
548checkBinary op left right res | isEqualityTest op = do
450 res ~~ Boolean
549 res ~~ Boolean
@@ -460,11 +559,17 @@ checkBinary op left right res =
460 right' <- check right valTy
559 right' <- check right valTy
461 return $ Binary op left' right'
560 return $ Binary op left' right'
563+-- Check if a @BinaryOperator@ is an equality test
463isEqualityTest :: BinaryOperator -> Bool
565isEqualityTest :: BinaryOperator -> Bool
464isEqualityTest EqualTo = True
566isEqualityTest EqualTo = True
465isEqualityTest NotEqualTo = True
567isEqualityTest NotEqualTo = True
466isEqualityTest _ = False
568isEqualityTest _ = False
571+-- Built-in binary operators
468binaryOps :: [(BinaryOperator, (Type, Type))]
573binaryOps :: [(BinaryOperator, (Type, Type))]
469binaryOps = [ (Add, (Number, Number))
574binaryOps = [ (Add, (Number, Number))
470 , (Subtract, (Number, Number))
575 , (Subtract, (Number, Number))
@@ -486,6 +591,9 @@ binaryOps = [ (Add, (Number, Number))
486 , (GreaterThanOrEqualTo, (Number, Boolean))
591 , (GreaterThanOrEqualTo, (Number, Boolean))
595+-- Infer the types of variables brought into scope by a binder
489inferBinder :: Type -> Binder -> Subst (M.Map Ident Type)
597inferBinder :: Type -> Binder -> Subst (M.Map Ident Type)
490inferBinder _ NullBinder = return M.empty
598inferBinder _ NullBinder = return M.empty
491inferBinder val (StringBinder _) = val ~~ String >> return M.empty
599inferBinder val (StringBinder _) = val ~~ String >> return M.empty
@@ -541,6 +649,9 @@ inferBinder val (NamedBinder name binder) = do
541 m <- inferBinder val binder
649 m <- inferBinder val binder
542 return $ M.insert name val m
650 return $ M.insert name val m
653+-- Check the types of the return values in a set of binders in a case statement
544checkBinders :: [Type] -> Type -> [([Binder], Maybe Guard, Value)] -> Subst [([Binder], Maybe Guard, Value)]
655checkBinders :: [Type] -> Type -> [([Binder], Maybe Guard, Value)] -> Subst [([Binder], Maybe Guard, Value)]
545checkBinders _ _ [] = return []
656checkBinders _ _ [] = return []
546checkBinders nvals ret ((binders, grd, val):bs) = do
657checkBinders nvals ret ((binders, grd, val):bs) = do
@@ -556,6 +667,9 @@ checkBinders nvals ret ((binders, grd, val):bs) = do
556 rs <- checkBinders nvals ret bs
667 rs <- checkBinders nvals ret bs
557 return $ r : rs
668 return $ r : rs
671+-- Check that a local variable name is not already used
559assignVariable :: Ident -> Subst ()
673assignVariable :: Ident -> Subst ()
560assignVariable name = do
674assignVariable name = do
561 env <- checkEnv <$> get
675 env <- checkEnv <$> get
@@ -564,6 +678,10 @@ assignVariable name = do
564 Just (_, LocalVariable) -> throwError $ "Variable with name " ++ show name ++ " already exists."
678 Just (_, LocalVariable) -> throwError $ "Variable with name " ++ show name ++ " already exists."
565 _ -> return ()
679 _ -> return ()
682+-- Check the type of the return values of a statement, returning whether or not the statement returns on
567checkStatement :: M.Map Ident Type -> Type -> Statement -> Subst (Bool, M.Map Ident Type, Statement)
685checkStatement :: M.Map Ident Type -> Type -> Statement -> Subst (Bool, M.Map Ident Type, Statement)
568checkStatement mass _ (VariableIntroduction name val) = do
686checkStatement mass _ (VariableIntroduction name val) = do
569 assignVariable name
687 assignVariable name
@@ -593,6 +711,9 @@ checkStatement mass ret (Return val) = do
593 val' <- check val ret
711 val' <- check val ret
594 return (True, mass, Return val')
712 return (True, mass, Return val')
715+-- Check the type of an if-then-else statement
596checkIfStatement :: M.Map Ident Type -> Type -> IfStatement -> Subst (Bool, IfStatement)
717checkIfStatement :: M.Map Ident Type -> Type -> IfStatement -> Subst (Bool, IfStatement)
597checkIfStatement mass ret (IfStatement val thens Nothing) = do
718checkIfStatement mass ret (IfStatement val thens Nothing) = do
598 val' <- check val Boolean
719 val' <- check val Boolean
@@ -604,12 +725,18 @@ checkIfStatement mass ret (IfStatement val thens (Just elses)) = do
604 (allCodePathsReturn2, elses') <- checkElseStatement mass ret elses
725 (allCodePathsReturn2, elses') <- checkElseStatement mass ret elses
605 return (allCodePathsReturn1 && allCodePathsReturn2, IfStatement val' thens' (Just elses'))
726 return (allCodePathsReturn1 && allCodePathsReturn2, IfStatement val' thens' (Just elses'))
729+-- Check the type of an else statement
607checkElseStatement :: M.Map Ident Type -> Type -> ElseStatement -> Subst (Bool, ElseStatement)
731checkElseStatement :: M.Map Ident Type -> Type -> ElseStatement -> Subst (Bool, ElseStatement)
608checkElseStatement mass ret (Else elses) = do
732checkElseStatement mass ret (Else elses) = do
609 (allCodePathsReturn, _, elses') <- checkBlock mass ret elses
733 (allCodePathsReturn, _, elses') <- checkBlock mass ret elses
610 return (allCodePathsReturn, Else elses')
734 return (allCodePathsReturn, Else elses')
611checkElseStatement mass ret (ElseIf ifst) = (id *** ElseIf) <$> checkIfStatement mass ret ifst
735checkElseStatement mass ret (ElseIf ifst) = (id *** ElseIf) <$> checkIfStatement mass ret ifst
738+-- Check the type of the return value of a block of statements
613checkBlock :: M.Map Ident Type -> Type -> [Statement] -> Subst (Bool, M.Map Ident Type, [Statement])
740checkBlock :: M.Map Ident Type -> Type -> [Statement] -> Subst (Bool, M.Map Ident Type, [Statement])
614checkBlock mass _ [] = return (False, mass, [])
741checkBlock mass _ [] = return (False, mass, [])
615checkBlock mass ret (s:ss) = do
742checkBlock mass ret (s:ss) = do
@@ -622,11 +749,17 @@ checkBlock mass ret (s:ss) = do
622 (b, m, ss'') <- checkBlock mass1 ret ss'
749 (b, m, ss'') <- checkBlock mass1 ret ss'
623 return (b, m, s':ss'')
750 return (b, m, s':ss'')
753+-- Skolemize a type variable by replacing its instances with fresh skolem constants
625skolemize :: String -> Type -> Subst Type
755skolemize :: String -> Type -> Subst Type
626skolemize ident ty = do
756skolemize ident ty = do
627 tsk <- Skolem <$> fresh'
757 tsk <- Skolem <$> fresh'
628 return $ replaceTypeVars ident tsk ty
758 return $ replaceTypeVars ident tsk ty
761+-- Check the type of a value, rethrowing errors to provide a better error message
630check :: Value -> Type -> Subst Value
763check :: Value -> Type -> Subst Value
631check val ty = rethrow errorMessage $ check' val ty
764check val ty = rethrow errorMessage $ check' val ty
@@ -638,6 +771,9 @@ check val ty = rethrow errorMessage $ check' val ty
775+-- Check the type of a value
641check' :: Value -> Type -> Subst Value
777check' :: Value -> Type -> Subst Value
642check' val (ForAll idents ty) = do
778check' val (ForAll idents ty) = do
643 sk <- skolemize idents ty
779 sk <- skolemize idents ty
@@ -736,6 +872,11 @@ check' val (SaturatedTypeSynonym name args) = do
736 check val ty
872 check val ty
737check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
873check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
876+-- Check the type of a collection of named record fields
878+-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
739checkProperties :: [(String, Value)] -> Type -> Bool -> Subst [(String, Value)]
880checkProperties :: [(String, Value)] -> Type -> Bool -> Subst [(String, Value)]
740checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
881checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
741 go [] [] REmpty = return []
882 go [] [] REmpty = return []
@@ -765,6 +906,9 @@ checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
765 return $ (p, v') : ps''
906 return $ (p, v') : ps''
766 go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
907 go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
910+-- Check the type of a function application, rethrowing errors to provide a better error message
768checkFunctionApplication :: Value -> Type -> [Value] -> Type -> Subst Value
912checkFunctionApplication :: Value -> Type -> [Value] -> Type -> Subst Value
769checkFunctionApplication fn fnTy args ret = rethrow errorMessage $ checkFunctionApplication' fn fnTy args ret
913checkFunctionApplication fn fnTy args ret = rethrow errorMessage $ checkFunctionApplication' fn fnTy args ret
@@ -773,6 +917,9 @@ checkFunctionApplication fn fnTy args ret = rethrow errorMessage $ checkFunction
773 ++ " to arguments " ++ intercalate ", " (map prettyPrintValue args)
917 ++ " to arguments " ++ intercalate ", " (map prettyPrintValue args)
774 ++ ":\n" ++ msg
918 ++ ":\n" ++ msg
921+-- Check the type of a function application
776checkFunctionApplication' :: Value -> Type -> [Value] -> Type -> Subst Value
923checkFunctionApplication' :: Value -> Type -> [Value] -> Type -> Subst Value
777checkFunctionApplication' fn (Function argTys retTy) args ret = do
924checkFunctionApplication' fn (Function argTys retTy) args ret = do
778 guardWith "Incorrect number of function arguments" (length args == length argTys)
925 guardWith "Incorrect number of function arguments" (length args == length argTys)
@@ -800,12 +947,27 @@ checkFunctionApplication' _ fnTy args ret = throwError $ "Applying a function of
800 ++ " to argument(s) " ++ intercalate ", " (map prettyPrintValue args)
947 ++ " to argument(s) " ++ intercalate ", " (map prettyPrintValue args)
801 ++ " does not yield a value of type " ++ prettyPrintType ret ++ "."
948 ++ " does not yield a value of type " ++ prettyPrintType ret ++ "."
951+-- Check whether one type subsumes another, rethrowing errors to provide a better error message
803subsumes :: Type -> Type -> Subst ()
953subsumes :: Type -> Type -> Subst ()
954+subsumes ty1 ty2 = rethrow errorMessage $ subsumes' ty1 ty2
956+ errorMessage msg = "Error checking that type "
957+ ++ prettyPrintType ty1
958+ ++ " subsumes type "
959+ ++ prettyPrintType ty2
963+-- Check whether one type subsumes another
965+subsumes' :: Type -> Type -> Subst ()
804−subsumes (ForAll ident ty1) ty2 = do
966+subsumes' (ForAll ident ty1) ty2 = do
805 replaced <- replaceVarWithUnknown ident ty1
967 replaced <- replaceVarWithUnknown ident ty1
806 replaced `subsumes` ty2
968 replaced `subsumes` ty2
807−subsumes (Function args1 ret1) (Function args2 ret2) = do
969+subsumes' (Function args1 ret1) (Function args2 ret2) = do
808 zipWithM_ subsumes args2 args1
970 zipWithM_ subsumes args2 args1
809 ret1 `subsumes` ret2
971 ret1 `subsumes` ret2
810−subsumes ty1 ty2 = ty1 ~~ ty2
972+subsumes' ty1 ty2 = ty1 ~~ ty2