on master help sign in
Improve type error messages for case-expressions
commit0769e5888a8550b3c88e8b0c6ac8297ea3d6a13e authorEvan Czaplicki <info@elm-lang.org> dateWed 6 May 2015, 14:47 (11 years ago) parentca5f9da
2 files changed+27−12
src/Reporting/Error/Type.hs+8−1 src/Type/Constrain/Expression.hs+19−11
src/Reporting/Error/Type.hs+8−1
@@ -26,6 +26,7 @@ data Hint
2626 = None
2727 | Custom String
2828 | CaseBranch Int Region.Region
29+ | Case
2930 | IfBranches
3031 | MultiIfBranch Int Region.Region
3132 | If
@@ -93,6 +94,12 @@ hintToString hint =
9394 ++ "branch returns the same type of value."
9495 )
9596
97+ Case ->
98+ ( Nothing
99+ , "All the branches of this case-expression are consistent, but the overall\n"
100+ ++ "type does not match how it is used elsewhere."
101+ )
102+
96103 IfBranches ->
97104 ( Nothing
98105 , "The branches of this if-expression return different types of values.\n"
@@ -108,6 +115,6 @@ hintToString hint =
108115
109116 If ->
110117 ( Nothing
111− , "All the branches of this if-expression are consistent, but the overall return\n"
118+ , "All the branches of this if-expression are consistent, but the overall\n"
112119 ++ "type does not match how it is used elsewhere."
113120 )
src/Type/Constrain/Expression.hs+19−11
@@ -254,28 +254,36 @@ constrainCase env region expr branches tipe =
254254
255255 exprCon <- constrain env expr (varN exprVar)
256256
257− (branchVars, regions, branchExprCons) <-
258− unzip3 <$> mapM (branch (varN exprVar)) branches
259−
260− let branchCons =
261− zipWith3 branchEqual [1..] branchVars regions
257+ (branchInfo, branchExprCons) <-
258+ unzip <$> mapM (branch (varN exprVar)) branches
262259
263260 return $
264− ex (exprVar:branchVars)
265− (CAnd (exprCon : branchExprCons ++ branchCons))
261+ ex (exprVar : map fst branchInfo)
262+ (CAnd (exprCon : branchExprCons ++ branchCons 2 branchInfo))
266263 where
267264 branch patternType (pattern, branchExpr@(A.A branchRegion _)) =
268265 do branchVar <- variable Flexible
269266 fragment <- Pattern.constrain env pattern patternType
270267 branchCon <- constrain env branchExpr (varN branchVar)
271268 return
272− ( branchVar
273− , branchRegion
269+ ( (branchVar, branchRegion)
274270 , CLet [Fragment.toScheme fragment] branchCon
275271 )
276272
277− branchEqual n var branchRegion =
278− CEqual (Error.CaseBranch n branchRegion) region tipe (varN var)
273+ branchCons n branchInfo =
274+ case branchInfo of
275+ [] ->
276+ []
277+
278+ (var,_) : [] ->
279+ [ CEqual Error.Case region tipe (varN var) ]
280+
281+ (var,_) : (var',region') : rest ->
282+ let
283+ hint = Error.CaseBranch n region'
284+ con = CEqual hint region (varN var) (varN var')
285+ in
286+ con : branchCons (n+1) ((var', region') : rest)
279287
280288
281289-- EXPAND PATTERNS