1{-# OPTIONS_GHC -Wall #-}
2{-# LANGUAGE OverloadedStrings #-}
3module Nitpick.PatternMatches
13{- The algorithm used here comes from "Warnings for Pattern Matching"
14by Luc Maranget. Check it out for more information!
16http://moscova.inria.fr/~maranget/papers/warn/warn.pdf
20import qualified Data.List as List
21import qualified Data.Map as Map
22import qualified Data.Maybe as Maybe
23import qualified Data.Text as Text
25import qualified AST.Canonical as Can
26import qualified Elm.Name as N
27import qualified Reporting.Annotation as A
28import qualified Reporting.Region as R
38 | Ctor Can.CtorAlts N.Name [Pattern]
50-- CREATE SIMPLIFIED PATTERNS
53simplify :: Can.Pattern -> Pattern
54simplify (A.At _ pattern) =
66 Ctor unitAlts unitName []
68 Can.PTuple a b Nothing ->
69 Ctor pairAlts pairName [ simplify a, simplify b ]
71 Can.PTuple a b (Just c) ->
72 Ctor tripleAlts tripleName [ simplify a, simplify b, simplify c ]
74 Can.PCtor _ _ _ alts name _ args ->
76 map (\(Can.PatternCtorArg _ _ arg) -> simplify arg) args
79 foldr cons nil entries
84 Can.PAlias subPattern _ ->
97cons :: Can.Pattern -> Pattern -> Pattern
99 Ctor listAlts consName [ simplify hd, tl ]
105 Ctor listAlts nilName []
112{-# NOINLINE unitAlts #-}
113unitAlts :: Can.CtorAlts
115 Can.toAlts [ Can.CtorAlt unitName 0 ]
118{-# NOINLINE pairAlts #-}
119pairAlts :: Can.CtorAlts
121 Can.toAlts [ Can.CtorAlt pairName 2 ]
124{-# NOINLINE tripleAlts #-}
125tripleAlts :: Can.CtorAlts
127 Can.toAlts [ Can.CtorAlt tripleName 3 ]
130{-# NOINLINE listAlts #-}
131listAlts :: Can.CtorAlts
133 Can.toAlts [ Can.CtorAlt consName 2, Can.CtorAlt nilName 0 ]
136{-# NOINLINE unitName #-}
141{-# NOINLINE pairName #-}
146{-# NOINLINE tripleName #-}
151{-# NOINLINE consName #-}
156{-# NOINLINE nilName #-}
166 = Incomplete R.Region Context [Pattern]
167 | Redundant R.Region R.Region Int
180check :: Can.Module -> Either [Error] ()
181check (Can.Module _ _ _ decls _ _ _ _) =
182 case checkDecls decls [] of
194checkDecls :: Can.Decls -> [Error] -> [Error]
195checkDecls decls errors =
197 Can.Declare def subDecls ->
198 checkDef def $ checkDecls subDecls errors
200 Can.DeclareRec defs subDecls ->
201 foldr checkDef (checkDecls subDecls errors) defs
203 Can.SaveTheEnvironment ->
211checkDef :: Can.Def -> [Error] -> [Error]
214 Can.Def _ args body ->
215 foldr checkArg (checkExpr body errors) args
217 Can.TypedDef _ _ args body _ ->
218 foldr checkTypedArg (checkExpr body errors) args
221checkArg :: Can.Pattern -> [Error] -> [Error]
222checkArg pattern@(A.At region _) errors =
223 checkPatterns region BadArg [pattern] errors
226checkTypedArg :: (Can.Pattern, tipe) -> [Error] -> [Error]
227checkTypedArg (pattern@(A.At region _), _) errors =
228 checkPatterns region BadArg [pattern] errors
235checkExpr :: Can.Expr -> [Error] -> [Error]
236checkExpr (A.At region expression) errors =
241 Can.VarTopLevel _ _ ->
247 Can.VarForeign _ _ _ ->
250 Can.VarDebug _ _ _ ->
253 Can.VarOperator _ _ _ _ ->
269 foldr checkExpr errors entries
272 checkExpr expr errors
274 Can.Binop _ _ _ _ left right ->
276 checkExpr right errors
278 Can.Lambda args body ->
279 foldr checkArg (checkExpr body errors) args
281 Can.Call func args ->
282 checkExpr func $ foldr checkExpr errors args
284 Can.If branches finally ->
285 foldr checkIfBranch (checkExpr finally errors) branches
288 checkDef def $ checkExpr body errors
290 Can.LetRec defs body ->
291 foldr checkDef (checkExpr body errors) defs
293 Can.LetDestruct pattern@(A.At reg _) expr body ->
294 checkPatterns reg BadDestruct [pattern] $
295 checkExpr expr $ checkExpr body errors
297 Can.Case expr branches ->
298 checkExpr expr $ checkCases region branches errors
303 Can.Access record _ ->
304 checkExpr record errors
306 Can.Update record fields ->
307 checkExpr record $ Map.foldr checkExpr errors fields
310 Map.foldr checkExpr errors fields
315 Can.Tuple a b maybeC ->
333checkIfBranch :: (Can.Expr, Can.Expr) -> [Error] -> [Error]
334checkIfBranch (condition, branch) errs =
335 checkExpr condition $ checkExpr branch errs
339-- CHECK CASE EXPRESSION
342checkCases :: R.Region -> [Can.CaseBranch] -> [Error] -> [Error]
343checkCases region branches errors =
345 (patterns, newErrors) =
346 foldr checkCaseBranch ([], errors) branches
348 checkPatterns region BadCase patterns newErrors
351checkCaseBranch :: Can.CaseBranch -> ([Can.Pattern], [Error]) -> ([Can.Pattern], [Error])
352checkCaseBranch (Can.CaseBranch pattern expr) (patterns, errors) =
354 , checkExpr expr errors
362checkPatterns :: R.Region -> Context -> [Can.Pattern] -> [Error] -> [Error]
363checkPatterns region context patterns errors =
364 case toNonRedundantRows region patterns of
369 case isExhaustive matrix 1 of
374 Incomplete region context (map head badPatterns) : errors
378-- EXHAUSTIVE PATTERNS
383-- The initial rows "matrix" are all of length 1
384-- The initial count of items per row "n" is also 1
385-- The resulting rows are examples of missing patterns
387isExhaustive :: [[Pattern]] -> Int -> [[Pattern]]
388isExhaustive matrix n =
391 [replicate n Anything]
398 ctors = collectCtors matrix
399 numSeen = Map.size ctors
403 <$> isExhaustive (Maybe.mapMaybe specializeRowByAnything matrix) (n - 1)
406 let alts@(Can.CtorAlts numAlts altList) = snd (Map.findMin ctors) in
407 if numSeen < numAlts then
409 <$> Maybe.mapMaybe (isMissing alts ctors) altList
410 <*> isExhaustive (Maybe.mapMaybe specializeRowByAnything matrix) (n - 1)
414 isAltExhaustive (Can.CtorAlt name arity) =
415 recoverCtor alts name arity <$>
417 (Maybe.mapMaybe (specializeRowByCtor name arity) matrix)
420 concatMap isAltExhaustive altList
423isMissing :: Can.CtorAlts -> Map.Map N.Name a -> Can.CtorAlt -> Maybe Pattern
424isMissing alts ctors (Can.CtorAlt name arity) =
425 if Map.member name ctors then
428 Just (Ctor alts name (replicate arity Anything))
431recoverCtor :: Can.CtorAlts -> N.Name -> Int -> [Pattern] -> [Pattern]
432recoverCtor alts name arity patterns =
435 splitAt arity patterns
437 Ctor alts name args : rest
444-- INVARIANT: Produces a list of rows where (forall row. length row == 1)
445toNonRedundantRows :: R.Region -> [Can.Pattern] -> Either Error [[Pattern]]
446toNonRedundantRows region patterns =
447 toSimplifiedUsefulRows region [] patterns
450-- INVARIANT: Produces a list of rows where (forall row. length row == 1)
451toSimplifiedUsefulRows :: R.Region -> [[Pattern]] -> [Can.Pattern] -> Either Error [[Pattern]]
452toSimplifiedUsefulRows overallRegion checkedRows uncheckedPatterns =
453 case uncheckedPatterns of
457 pattern@(A.At region _) : rest ->
458 let nextRow = [simplify pattern] in
459 if isUseful checkedRows nextRow then
460 toSimplifiedUsefulRows overallRegion (nextRow : checkedRows) rest
462 Left (Redundant overallRegion region (length checkedRows + 1))
465-- Check if a new row "vector" is useful given previous rows "matrix"
466isUseful :: [[Pattern]] -> [Pattern] -> Bool
467isUseful matrix vector =
470 -- No rows are the same as the new vector! The vector is useful!
476 -- There is nothing left in the new vector, but we still have
477 -- rows that match the same things. This is not a useful vector!
480 firstPattern : patterns ->
483 -- keep checking rows that start with this Ctor or Anything
485 (Maybe.mapMaybe (specializeRowByCtor name (length args)) matrix)
489 -- check if all alts appear in matrix
490 case isComplete matrix of
492 -- This Anything is useful because some Ctors are missing.
493 -- But what if a previous row has an Anything?
494 -- If so, this one is not useful.
495 isUseful (Maybe.mapMaybe specializeRowByAnything matrix) patterns
498 -- All Ctors are covered, so this Anything is not needed for any
499 -- of those. But what if some of those Ctors have subpatterns
500 -- that make them less general? If so, this actually is useful!
502 isUsefulAlt (Can.CtorAlt ctor arity) =
504 (Maybe.mapMaybe (specializeRowByCtor ctor arity) matrix)
505 (replicate arity Anything ++ patterns)
510 -- keep checking rows that start with this Literal or Anything
512 (Maybe.mapMaybe (specializeRowByLiteral literal) matrix)
516-- INVARIANT: (length row == N) ==> (length result == arity + N - 1)
517specializeRowByCtor :: N.Name -> Int -> [Pattern] -> Maybe [Pattern]
518specializeRowByCtor ctorName arity row =
520 Ctor _ name args : patterns ->
521 if name == ctorName then
522 Just (args ++ patterns)
526 Anything : patterns ->
527 Just (replicate arity Anything ++ patterns)
531 "Compiler bug! After type checking, constructors and literals\
532 \ should never align in pattern match exhaustiveness checks."
535 error "Compiler error! Empty matrices should not get specialized."
538-- INVARIANT: (length row == N) ==> (length result == N-1)
539specializeRowByLiteral :: Literal -> [Pattern] -> Maybe [Pattern]
540specializeRowByLiteral literal row =
542 Literal lit : patterns ->
543 if lit == literal then
548 Anything : patterns ->
553 "Compiler bug! After type checking, constructors and literals\
554 \ should never align in pattern match exhaustiveness checks."
557 error "Compiler error! Empty matrices should not get specialized."
560-- INVARIANT: (length row == N) ==> (length result == N-1)
561specializeRowByAnything :: [Pattern] -> Maybe [Pattern]
562specializeRowByAnything row =
570 Anything : patterns ->
578-- ALL CONSTRUCTORS ARE PRESENT?
586isComplete :: [[Pattern]] -> Complete
589 ctors = collectCtors matrix
590 numSeen = Map.size ctors
595 let (Can.CtorAlts numAlts alts) = snd (Map.findMin ctors) in
596 if numSeen == numAlts then Yes alts else No
603collectCtors :: [[Pattern]] -> Map.Map N.Name Can.CtorAlts
605 List.foldl' collectCtorsHelp Map.empty matrix
608collectCtorsHelp :: Map.Map N.Name Can.CtorAlts -> [Pattern] -> Map.Map N.Name Can.CtorAlts
609collectCtorsHelp ctors row =
611 Ctor alts name _ : _ ->
612 Map.insert name alts ctors
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list