@@ -9,6 +9,7 @@
99-- Portability :
1010--
1111-- |
12+-- This module implements the type checker
1213--
1314-----------------------------------------------------------------------------
1415
@@ -67,6 +68,9 @@ instance Unifiable Type where
6768 unknowns (RCons _ ty r) = unknowns ty ++ unknowns r
6869 unknowns _ = []
6970
71+-- |
72+-- Unify two types, updating the current substitution
73+--
7074unifyTypes :: Type -> Type -> Subst ()
7175unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $ do
7276 unifyTypes' t1 t2
@@ -110,6 +114,13 @@ unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 +
110114 unifyTypes' r1 r2@REmpty = unifyRows r1 r2
111115 unifyTypes' t3 t4 = throwError $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
112116
117+-- |
118+-- Unify two rows, updating the current substitution
119+--
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
122+-- error.
123+--
113124unifyRows :: Type -> Type -> Subst ()
114125unifyRows r1 r2 =
115126 let
@@ -136,9 +147,16 @@ unifyRows r1 r2 =
136147 unifyRows' [] (Skolem s1) [] (Skolem s2) | s1 == s2 = return ()
137148 unifyRows' sd3 r3 sd4 r4 = throwError $ "Cannot unify " ++ prettyPrintRow (rowFromList (sd3, r3)) ++ " with " ++ prettyPrintRow (rowFromList (sd4, r4)) ++ "."
138149
150+-- |
151+-- Ensure type constructors are equal after canonicalization
152+--
139153typeConstructorsAreEqual :: Environment -> ModuleName -> Qualified ProperName -> Qualified ProperName -> Bool
140154typeConstructorsAreEqual env moduleName = (==) `on` canonicalizeType moduleName env
141155
156+-- |
157+-- Infer the types of multiple mutually-recursive values, and return elaborated values including
158+-- type class dictionaries and type annotations.
159+--
142160typesOf :: ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
143161typesOf moduleName vals = do
144162 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
173191 return (ident, (overTypes (desaturateAllTypeSynonyms . setifyAll) $ val'
174192 , varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty))
175193
194+-- |
195+-- Check if a value contains a type annotation
196+--
176197isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
177198isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
178199isTyped (name, value) = (name, (value, Nothing))
179200
201+-- |
202+-- Map a function over type annotations appearing inside a value
203+--
180204overTypes :: (Type -> Type) -> Value -> Value
181205overTypes f = everywhere (mkT f)
182206
207+-- |
208+-- Replace type class dictionary placeholders with inferred type class dictionaries
209+--
183210replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
184211replaceTypeClassDictionaries mn = everywhereM (mkM go)
185212 where
186213 go (TypeClassDictionary constraint dicts) = entails mn dicts constraint
187214 go other = return other
188215
216+-- |
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.
219+--
189220entails :: ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, Type) -> Check Value
190221entails moduleName context goal@(className, ty) = do
191222 env <- getEnv
@@ -211,6 +242,10 @@ entails moduleName context goal@(className, ty) = do
211242 canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDRegular, tcdName = nm }) = nm
212243 canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDAlias nm }) = nm
213244
245+-- |
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.
248+--
214249typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
215250typeHeadsAreEqual _ _ String String = Just []
216251typeHeadsAreEqual _ _ Number Number = Just []
@@ -222,6 +257,9 @@ typeHeadsAreEqual m e (TypeApp h1 (TypeVar v)) (TypeApp h2 arg) = (:) (v, arg) <
222257typeHeadsAreEqual m e t1@(TypeApp _ _) t2@(TypeApp _ (TypeVar _)) = typeHeadsAreEqual m e t2 t1
223258typeHeadsAreEqual _ _ _ _ = Nothing
224259
260+-- |
261+-- Ensure unsolved unification variables do not escape
262+--
225263escapeCheck :: Value -> Type -> Subst ()
226264escapeCheck value ty = do
227265 subst <- substSubst <$> getSubstState
@@ -231,12 +269,18 @@ escapeCheck value ty = do
231269 let unsolvedUnknowns = nub . unknowns $ apply subst t
232270 guardWith "Escape check fails" $ null $ unsolvedUnknowns \\ visibleUnknowns
233271
272+-- |
273+-- Find all type annotations occuring inside a value
274+--
234275findAllTypes :: Value -> [Type]
235276findAllTypes = everything (++) (mkQ [] go)
236277 where
237278 go (TypedValue _ _ ty) = [ty]
238279 go _ = []
239280
281+-- |
282+-- Ensure skolem variables do not escape their scope
283+--
240284skolemEscapeCheck :: Type -> Check ()
241285skolemEscapeCheck ty =
242286 case something (mkQ Nothing findSkolems) ty of
@@ -246,12 +290,21 @@ skolemEscapeCheck ty =
246290 findSkolems (Skolem _) = return ()
247291 findSkolems _ = mzero
248292
293+-- |
294+-- Ensure a row contains no duplicate labels
295+--
249296setify :: Type -> Type
250297setify = rowFromList . first (M.toList . M.fromList) . rowToList
251298
299+-- |
300+-- \"Setify\" all rows occuring inside a value
301+--
252302setifyAll :: (D.Data d) => d -> d
253303setifyAll = everywhere (mkT setify)
254304
305+-- |
306+-- Replace outermost unsolved unification variables with named type variables
307+--
255308varIfUnknown :: Type -> Type
256309varIfUnknown ty =
257310 let unks = nub $ unknowns ty
@@ -262,18 +315,31 @@ varIfUnknown ty =
262315 typeToVar t = t
263316 in mkForAll (sort . map toName $ unks) ty'
264317
318+-- |
319+-- Replace named type variables with types
320+--
265321replaceAllTypeVars :: (D.Data d) => [(String, Type)] -> d -> d
266322replaceAllTypeVars = foldl' (\f (name, ty) -> replaceTypeVars name ty . f) id
267323
324+-- |
325+-- Replace named type variables with new unification variables
326+--
268327replaceAllVarsWithUnknowns :: Type -> Subst Type
269328replaceAllVarsWithUnknowns (ForAll ident ty) = replaceVarWithUnknown ident ty >>= replaceAllVarsWithUnknowns
270329replaceAllVarsWithUnknowns ty = return ty
271330
331+-- |
332+-- Replace a single type variable with a new unification variable
333+--
272334replaceVarWithUnknown :: String -> Type -> Subst Type
273335replaceVarWithUnknown ident ty = do
274336 tu <- fresh
275337 return $ replaceTypeVars ident tu $ ty
276338
339+-- |
340+-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
341+-- better error messages during unification.
342+--
277343replaceAllTypeSynonyms :: (Functor m, MonadState CheckState m, MonadReader SubstContext m, MonadError String m) => (D.Data d) => d -> m d
278344replaceAllTypeSynonyms d = do
279345 env <- getEnv
@@ -281,12 +347,18 @@ replaceAllTypeSynonyms d = do
281347 let syns = map (\((path, name), (args, _)) -> ((path, name), length args)) . M.toList $ typeSynonyms env
282348 either throwError return $ saturateAllTypeSynonyms env moduleName syns d
283349
350+-- |
351+-- \"Desaturate\" @SaturatedTypeSynonym@s
352+--
284353desaturateAllTypeSynonyms :: (D.Data d) => d -> d
285354desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
286355 where
287356 replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
288357 replaceSaturatedTypeSynonym t = t
289358
359+-- |
360+-- Replace a type synonym and its arguments with the aliased type
361+--
290362expandTypeSynonym :: Qualified ProperName -> [Type] -> Subst Type
291363expandTypeSynonym name args = do
292364 env <- getEnv
@@ -295,12 +367,21 @@ expandTypeSynonym name args = do
295367 Just (synArgs, body) -> return $ replaceAllTypeVars (zip synArgs args) body
296368 Nothing -> error "Type synonym was not defined"
297369
370+-- |
371+-- Ensure a set of property names and value does not contain duplicate labels
372+--
298373ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
299374ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
300375
376+-- |
377+-- Infer a type for a value, rethrowing any error to provide a more useful error message
378+--
301379infer :: Value -> Subst Value
302380infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
303381
382+-- |
383+-- Infer a type for a value
384+--
304385infer' :: Value -> Subst Value
305386infer' v@(NumericLiteral _) = return $ TypedValue True v Number
306387infer' v@(StringLiteral _) = return $ TypedValue True v String
@@ -399,6 +480,9 @@ infer' (TypedValue checkType val ty) = do
399480 return $ TypedValue True val' ty
400481infer' _ = error "Invalid argument to infer"
401482
483+-- |
484+-- Infer the type of a property inside a record with a given type
485+--
402486inferProperty :: Type -> String -> Subst (Maybe Type)
403487inferProperty (Object row) prop = do
404488 let (props, _) = rowToList row
@@ -411,6 +495,9 @@ inferProperty (ForAll ident ty) prop = do
411495 inferProperty replaced prop
412496inferProperty _ _ = return Nothing
413497
498+-- |
499+-- Infer the type of a unary operator application
500+--
414501inferUnary :: UnaryOperator -> Value -> Subst Value
415502inferUnary op (TypedValue _ val valTy) =
416503 case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
@@ -419,6 +506,9 @@ inferUnary op (TypedValue _ val valTy) =
419506 return $ TypedValue True (Unary op val) resTy
420507inferUnary _ _ = error "Invalid arguments to inferUnary"
421508
509+-- |
510+-- Check the type of a unary operator application
511+--
422512checkUnary :: UnaryOperator -> Value -> Type -> Subst Value
423513checkUnary op val res =
424514 case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
@@ -427,12 +517,18 @@ checkUnary op val res =
427517 val' <- check val valTy
428518 return $ Unary op val'
429519
520+-- |
521+-- Built-in unary operators
522+--
430523unaryOps :: [(UnaryOperator, (Type, Type))]
431524unaryOps = [ (Negate, (Number, Number))
432525 , (Not, (Boolean, Boolean))
433526 , (BitwiseNot, (Number, Number))
434527 ]
435528
529+-- |
530+-- Infer the type of a binary operator application
531+--
436532inferBinary :: BinaryOperator -> Value -> Value -> Subst Value
437533inferBinary op left@(TypedValue _ _ leftTy) right@(TypedValue _ _ rightTy) | isEqualityTest op = do
438534 leftTy ~~ rightTy
@@ -445,6 +541,9 @@ inferBinary op left@(TypedValue _ _ leftTy) right@(TypedValue _ _ rightTy) =
445541 return $ TypedValue True (Binary op left right) resTy
446542inferBinary _ _ _ = error "Invalid arguments to inferBinary"
447543
544+-- |
545+-- Check the type of a binary operator application
546+--
448547checkBinary :: BinaryOperator -> Value -> Value -> Type -> Subst Value
449548checkBinary op left right res | isEqualityTest op = do
450549 res ~~ Boolean
@@ -460,11 +559,17 @@ checkBinary op left right res =
460559 right' <- check right valTy
461560 return $ Binary op left' right'
462561
562+-- |
563+-- Check if a @BinaryOperator@ is an equality test
564+--
463565isEqualityTest :: BinaryOperator -> Bool
464566isEqualityTest EqualTo = True
465567isEqualityTest NotEqualTo = True
466568isEqualityTest _ = False
467569
570+-- |
571+-- Built-in binary operators
572+--
468573binaryOps :: [(BinaryOperator, (Type, Type))]
469574binaryOps = [ (Add, (Number, Number))
470575 , (Subtract, (Number, Number))
@@ -486,6 +591,9 @@ binaryOps = [ (Add, (Number, Number))
486591 , (GreaterThanOrEqualTo, (Number, Boolean))
487592 ]
488593
594+-- |
595+-- Infer the types of variables brought into scope by a binder
596+--
489597inferBinder :: Type -> Binder -> Subst (M.Map Ident Type)
490598inferBinder _ NullBinder = return M.empty
491599inferBinder val (StringBinder _) = val ~~ String >> return M.empty
@@ -541,6 +649,9 @@ inferBinder val (NamedBinder name binder) = do
541649 m <- inferBinder val binder
542650 return $ M.insert name val m
543651
652+-- |
653+-- Check the types of the return values in a set of binders in a case statement
654+--
544655checkBinders :: [Type] -> Type -> [([Binder], Maybe Guard, Value)] -> Subst [([Binder], Maybe Guard, Value)]
545656checkBinders _ _ [] = return []
546657checkBinders nvals ret ((binders, grd, val):bs) = do
@@ -556,6 +667,9 @@ checkBinders nvals ret ((binders, grd, val):bs) = do
556667 rs <- checkBinders nvals ret bs
557668 return $ r : rs
558669
670+-- |
671+-- Check that a local variable name is not already used
672+--
559673assignVariable :: Ident -> Subst ()
560674assignVariable name = do
561675 env <- checkEnv <$> get
@@ -564,6 +678,10 @@ assignVariable name = do
564678 Just (_, LocalVariable) -> throwError $ "Variable with name " ++ show name ++ " already exists."
565679 _ -> return ()
566680
681+-- |
682+-- Check the type of the return values of a statement, returning whether or not the statement returns on
683+-- all code paths
684+--
567685checkStatement :: M.Map Ident Type -> Type -> Statement -> Subst (Bool, M.Map Ident Type, Statement)
568686checkStatement mass _ (VariableIntroduction name val) = do
569687 assignVariable name
@@ -593,6 +711,9 @@ checkStatement mass ret (Return val) = do
593711 val' <- check val ret
594712 return (True, mass, Return val')
595713
714+-- |
715+-- Check the type of an if-then-else statement
716+--
596717checkIfStatement :: M.Map Ident Type -> Type -> IfStatement -> Subst (Bool, IfStatement)
597718checkIfStatement mass ret (IfStatement val thens Nothing) = do
598719 val' <- check val Boolean
@@ -604,12 +725,18 @@ checkIfStatement mass ret (IfStatement val thens (Just elses)) = do
604725 (allCodePathsReturn2, elses') <- checkElseStatement mass ret elses
605726 return (allCodePathsReturn1 && allCodePathsReturn2, IfStatement val' thens' (Just elses'))
606727
728+-- |
729+-- Check the type of an else statement
730+--
607731checkElseStatement :: M.Map Ident Type -> Type -> ElseStatement -> Subst (Bool, ElseStatement)
608732checkElseStatement mass ret (Else elses) = do
609733 (allCodePathsReturn, _, elses') <- checkBlock mass ret elses
610734 return (allCodePathsReturn, Else elses')
611735checkElseStatement mass ret (ElseIf ifst) = (id *** ElseIf) <$> checkIfStatement mass ret ifst
612736
737+-- |
738+-- Check the type of the return value of a block of statements
739+--
613740checkBlock :: M.Map Ident Type -> Type -> [Statement] -> Subst (Bool, M.Map Ident Type, [Statement])
614741checkBlock mass _ [] = return (False, mass, [])
615742checkBlock mass ret (s:ss) = do
@@ -622,11 +749,17 @@ checkBlock mass ret (s:ss) = do
622749 (b, m, ss'') <- checkBlock mass1 ret ss'
623750 return (b, m, s':ss'')
624751
752+-- |
753+-- Skolemize a type variable by replacing its instances with fresh skolem constants
754+--
625755skolemize :: String -> Type -> Subst Type
626756skolemize ident ty = do
627757 tsk <- Skolem <$> fresh'
628758 return $ replaceTypeVars ident tsk ty
629759
760+-- |
761+-- Check the type of a value, rethrowing errors to provide a better error message
762+--
630763check :: Value -> Type -> Subst Value
631764check val ty = rethrow errorMessage $ check' val ty
632765 where
@@ -638,6 +771,9 @@ check val ty = rethrow errorMessage $ check' val ty
638771 ":\n" ++
639772 msg
640773
774+-- |
775+-- Check the type of a value
776+--
641777check' :: Value -> Type -> Subst Value
642778check' val (ForAll idents ty) = do
643779 sk <- skolemize idents ty
@@ -736,6 +872,11 @@ check' val (SaturatedTypeSynonym name args) = do
736872 check val ty
737873check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
738874
875+-- |
876+-- Check the type of a collection of named record fields
877+--
878+-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
879+--
739880checkProperties :: [(String, Value)] -> Type -> Bool -> Subst [(String, Value)]
740881checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
741882 go [] [] REmpty = return []
@@ -765,6 +906,9 @@ checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
765906 return $ (p, v') : ps''
766907 go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
767908
909+-- |
910+-- Check the type of a function application, rethrowing errors to provide a better error message
911+--
768912checkFunctionApplication :: Value -> Type -> [Value] -> Type -> Subst Value
769913checkFunctionApplication fn fnTy args ret = rethrow errorMessage $ checkFunctionApplication' fn fnTy args ret
770914 where
@@ -773,6 +917,9 @@ checkFunctionApplication fn fnTy args ret = rethrow errorMessage $ checkFunction
773917 ++ " to arguments " ++ intercalate ", " (map prettyPrintValue args)
774918 ++ ":\n" ++ msg
775919
920+-- |
921+-- Check the type of a function application
922+--
776923checkFunctionApplication' :: Value -> Type -> [Value] -> Type -> Subst Value
777924checkFunctionApplication' fn (Function argTys retTy) args ret = do
778925 guardWith "Incorrect number of function arguments" (length args == length argTys)
@@ -800,12 +947,27 @@ checkFunctionApplication' _ fnTy args ret = throwError $ "Applying a function of
800947 ++ " to argument(s) " ++ intercalate ", " (map prettyPrintValue args)
801948 ++ " does not yield a value of type " ++ prettyPrintType ret ++ "."
802949
950+-- |
951+-- Check whether one type subsumes another, rethrowing errors to provide a better error message
952+--
803953subsumes :: Type -> Type -> Subst ()
804−subsumes (ForAll ident ty1) ty2 = do
954+subsumes ty1 ty2 = rethrow errorMessage $ subsumes' ty1 ty2
955+ where
956+ errorMessage msg = "Error checking that type "
957+ ++ prettyPrintType ty1
958+ ++ " subsumes type "
959+ ++ prettyPrintType ty2
960+ ++ ":\n" ++ msg
961+
962+-- |
963+-- Check whether one type subsumes another
964+--
965+subsumes' :: Type -> Type -> Subst ()
966+subsumes' (ForAll ident ty1) ty2 = do
805967 replaced <- replaceVarWithUnknown ident ty1
806968 replaced `subsumes` ty2
807−subsumes (Function args1 ret1) (Function args2 ret2) = do
969+subsumes' (Function args1 ret1) (Function args2 ret2) = do
808970 zipWithM_ subsumes args2 args1
809971 ret1 `subsumes` ret2
810−subsumes ty1 ty2 = ty1 ~~ ty2
972+subsumes' ty1 ty2 = ty1 ~~ ty2
811973