1{-# OPTIONS_GHC -Wall #-}
2{-# LANGUAGE OverloadedStrings #-}
3module Nitpick.PatternMatches
12{- The algorithm used here comes from "Warnings for Pattern Matching"
13by Luc Maranget. Check it out for more information!
15http://moscova.inria.fr/~maranget/papers/warn/warn.pdf
19import qualified Data.List as List
20import qualified Data.Map as Map
21import qualified Data.Maybe as Maybe
22import qualified Data.Text as Text
24import qualified AST.Canonical as Can
25import qualified Elm.Name as N
26import qualified Reporting.Annotation as A
27import qualified Reporting.Region as R
37 | Ctor Can.CtorAlts N.Name [Pattern]
49-- CREATE SIMPLIFIED PATTERNS
52simplify :: Can.Pattern -> Pattern
53simplify (A.At _ pattern) =
65 Ctor unitAlts unitName []
67 Can.PTuple a b Nothing ->
68 Ctor pairAlts pairName [ simplify a, simplify b ]
70 Can.PTuple a b (Just c) ->
71 Ctor tripleAlts tripleName [ simplify a, simplify b, simplify c ]
73 Can.PCtor _ _ _ alts name _ args ->
75 map (\(Can.PatternCtorArg _ _ arg) -> simplify arg) args
78 foldr cons nil entries
83 Can.PAlias subPattern _ ->
96cons :: Can.Pattern -> Pattern -> Pattern
98 Ctor listAlts consName [ simplify hd, tl ]
104 Ctor listAlts nilName []
111{-# NOINLINE unitAlts #-}
112unitAlts :: Can.CtorAlts
114 Can.toAlts [ Can.CtorAlt unitName 0 ]
117{-# NOINLINE pairAlts #-}
118pairAlts :: Can.CtorAlts
120 Can.toAlts [ Can.CtorAlt pairName 2 ]
123{-# NOINLINE tripleAlts #-}
124tripleAlts :: Can.CtorAlts
126 Can.toAlts [ Can.CtorAlt tripleName 3 ]
129{-# NOINLINE listAlts #-}
130listAlts :: Can.CtorAlts
132 Can.toAlts [ Can.CtorAlt consName 2, Can.CtorAlt nilName 0 ]
135{-# NOINLINE unitName #-}
140{-# NOINLINE pairName #-}
145{-# NOINLINE tripleName #-}
150{-# NOINLINE consName #-}
155{-# NOINLINE nilName #-}
165 = Incomplete R.Region Context [Pattern]
166 | Redundant R.Region R.Region Int
179check :: Can.Module -> Either [Error] ()
180check (Can.Module _ _ _ decls _ _ _ _) =
181 case checkDecls decls [] of
193checkDecls :: Can.Decls -> [Error] -> [Error]
194checkDecls decls errors =
196 Can.Declare def subDecls ->
197 checkDef def $ checkDecls subDecls errors
199 Can.DeclareRec defs subDecls ->
200 foldr checkDef (checkDecls subDecls errors) defs
202 Can.SaveTheEnvironment ->
210checkDef :: Can.Def -> [Error] -> [Error]
213 Can.Def _ args body ->
214 foldr checkArg (checkExpr body errors) args
216 Can.TypedDef _ _ args body _ ->
217 foldr checkTypedArg (checkExpr body errors) args
220checkArg :: Can.Pattern -> [Error] -> [Error]
221checkArg pattern@(A.At region _) errors =
222 checkPatterns region BadArg [pattern] errors
225checkTypedArg :: (Can.Pattern, tipe) -> [Error] -> [Error]
226checkTypedArg (pattern@(A.At region _), _) errors =
227 checkPatterns region BadArg [pattern] errors
234checkExpr :: Can.Expr -> [Error] -> [Error]
235checkExpr (A.At region expression) errors =
240 Can.VarTopLevel _ _ ->
246 Can.VarForeign _ _ _ ->
249 Can.VarDebug _ _ _ ->
252 Can.VarOperator _ _ _ _ ->
268 foldr checkExpr errors entries
271 checkExpr expr errors
273 Can.Binop _ _ _ _ left right ->
275 checkExpr right errors
277 Can.Lambda args body ->
278 foldr checkArg (checkExpr body errors) args
280 Can.Call func args ->
281 checkExpr func $ foldr checkExpr errors args
283 Can.If branches finally ->
284 foldr checkIfBranch (checkExpr finally errors) branches
287 checkDef def $ checkExpr body errors
289 Can.LetRec defs body ->
290 foldr checkDef (checkExpr body errors) defs
292 Can.LetDestruct pattern@(A.At reg _) expr body ->
293 checkPatterns reg BadDestruct [pattern] $
294 checkExpr expr $ checkExpr body errors
296 Can.Case expr branches ->
297 checkExpr expr $ checkCases region branches errors
302 Can.Access record _ ->
303 checkExpr record errors
305 Can.Update record fields ->
306 checkExpr record $ Map.foldr checkExpr errors fields
309 Map.foldr checkExpr errors fields
314 Can.Tuple a b maybeC ->
332checkIfBranch :: (Can.Expr, Can.Expr) -> [Error] -> [Error]
333checkIfBranch (condition, branch) errs =
334 checkExpr condition $ checkExpr branch errs
338-- CHECK CASE EXPRESSION
341checkCases :: R.Region -> [Can.CaseBranch] -> [Error] -> [Error]
342checkCases region branches errors =
344 (patterns, newErrors) =
345 foldr checkCaseBranch ([], errors) branches
347 checkPatterns region BadCase patterns newErrors
350checkCaseBranch :: Can.CaseBranch -> ([Can.Pattern], [Error]) -> ([Can.Pattern], [Error])
351checkCaseBranch (Can.CaseBranch pattern expr) (patterns, errors) =
353 , checkExpr expr errors
361checkPatterns :: R.Region -> Context -> [Can.Pattern] -> [Error] -> [Error]
362checkPatterns region context patterns errors =
363 case toNonRedundantRows region patterns of
368 case isExhaustive matrix 1 of
373 Incomplete region context (map head badPatterns) : errors
377-- EXHAUSTIVE PATTERNS
382-- The initial rows "matrix" are all of length 1
383-- The initial count of items per row "n" is also 1
384-- The resulting rows are examples of missing patterns
386isExhaustive :: [[Pattern]] -> Int -> [[Pattern]]
387isExhaustive matrix n =
390 [replicate n Anything]
397 ctors = collectCtors matrix
398 numSeen = Map.size ctors
402 <$> isExhaustive (Maybe.mapMaybe specializeRowByAnything matrix) (n - 1)
405 let alts@(Can.CtorAlts numAlts altList) = snd (Map.findMin ctors) in
406 if numSeen < numAlts then
408 <$> Maybe.mapMaybe (isMissing alts ctors) altList
409 <*> isExhaustive (Maybe.mapMaybe specializeRowByAnything matrix) (n - 1)
413 isAltExhaustive (Can.CtorAlt name arity) =
414 recoverCtor alts name arity <$>
416 (Maybe.mapMaybe (specializeRowByCtor name arity) matrix)
419 concatMap isAltExhaustive altList
422isMissing :: Can.CtorAlts -> Map.Map N.Name a -> Can.CtorAlt -> Maybe Pattern
423isMissing alts ctors (Can.CtorAlt name arity) =
424 if Map.member name ctors then
427 Just (Ctor alts name (replicate arity Anything))
430recoverCtor :: Can.CtorAlts -> N.Name -> Int -> [Pattern] -> [Pattern]
431recoverCtor alts name arity patterns =
434 splitAt arity patterns
436 Ctor alts name args : rest
443-- INVARIANT: Produces a list of rows where (forall row. length row == 1)
444toNonRedundantRows :: R.Region -> [Can.Pattern] -> Either Error [[Pattern]]
445toNonRedundantRows region patterns =
446 toSimplifiedUsefulRows region [] patterns
449-- INVARIANT: Produces a list of rows where (forall row. length row == 1)
450toSimplifiedUsefulRows :: R.Region -> [[Pattern]] -> [Can.Pattern] -> Either Error [[Pattern]]
451toSimplifiedUsefulRows overallRegion checkedRows uncheckedPatterns =
452 case uncheckedPatterns of
456 pattern@(A.At region _) : rest ->
457 let nextRow = [simplify pattern] in
458 if isUseful checkedRows nextRow then
459 toSimplifiedUsefulRows overallRegion (nextRow : checkedRows) rest
461 Left (Redundant overallRegion region (length checkedRows + 1))
464-- Check if a new row "vector" is useful given previous rows "matrix"
465isUseful :: [[Pattern]] -> [Pattern] -> Bool
466isUseful matrix vector =
469 -- No rows are the same as the new vector! The vector is useful!
475 -- There is nothing left in the new vector, but we still have
476 -- rows that match the same things. This is not a useful vector!
479 firstPattern : patterns ->
482 -- keep checking rows that start with this Ctor or Anything
484 (Maybe.mapMaybe (specializeRowByCtor name (length args)) matrix)
488 -- check if all alts appear in matrix
489 case isComplete matrix of
491 -- This Anything is useful because some Ctors are missing.
492 -- But what if a previous row has an Anything?
493 -- If so, this one is not useful.
494 isUseful (Maybe.mapMaybe specializeRowByAnything matrix) patterns
497 -- All Ctors are covered, so this Anything is not needed for any
498 -- of those. But what if some of those Ctors have subpatterns
499 -- that make them less general? If so, this actually is useful!
501 isUsefulAlt (Can.CtorAlt ctor arity) =
503 (Maybe.mapMaybe (specializeRowByCtor ctor arity) matrix)
504 (replicate arity Anything ++ patterns)
509 -- keep checking rows that start with this Literal or Anything
511 (Maybe.mapMaybe (specializeRowByLiteral literal) matrix)
515-- INVARIANT: (length row == N) ==> (length result == arity + N - 1)
516specializeRowByCtor :: N.Name -> Int -> [Pattern] -> Maybe [Pattern]
517specializeRowByCtor ctorName arity row =
519 Ctor _ name args : patterns ->
520 if name == ctorName then
521 Just (args ++ patterns)
525 Anything : patterns ->
526 Just (replicate arity Anything ++ patterns)
530 "Compiler bug! After type checking, constructors and literals\
531 \ should never align in pattern match exhaustiveness checks."
534 error "Compiler error! Empty matrices should not get specialized."
537-- INVARIANT: (length row == N) ==> (length result == N-1)
538specializeRowByLiteral :: Literal -> [Pattern] -> Maybe [Pattern]
539specializeRowByLiteral literal row =
541 Literal lit : patterns ->
542 if lit == literal then
547 Anything : patterns ->
552 "Compiler bug! After type checking, constructors and literals\
553 \ should never align in pattern match exhaustiveness checks."
556 error "Compiler error! Empty matrices should not get specialized."
559-- INVARIANT: (length row == N) ==> (length result == N-1)
560specializeRowByAnything :: [Pattern] -> Maybe [Pattern]
561specializeRowByAnything row =
569 Anything : patterns ->
577-- ALL CONSTRUCTORS ARE PRESENT?
585isComplete :: [[Pattern]] -> Complete
588 ctors = collectCtors matrix
589 numSeen = Map.size ctors
594 let (Can.CtorAlts numAlts alts) = snd (Map.findMin ctors) in
595 if numSeen == numAlts then Yes alts else No
602collectCtors :: [[Pattern]] -> Map.Map N.Name Can.CtorAlts
604 List.foldl' collectCtorsHelp Map.empty matrix
607collectCtorsHelp :: Map.Map N.Name Can.CtorAlts -> [Pattern] -> Map.Map N.Name Can.CtorAlts
608collectCtorsHelp ctors row =
610 Ctor alts name _ : _ ->
611 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