3bf52ceaa08a65201bf547005bd5551eca874cde
[ghc.git] / compiler / deSugar / Check.hs
1 {-
2 Author: George Karachalias <george.karachalias@cs.kuleuven.be>
3
4 Pattern Matching Coverage Checking.
5 -}
6
7 {-# LANGUAGE CPP, GADTs, DataKinds, KindSignatures #-}
8 {-# LANGUAGE TupleSections #-}
9
10 module Check (
11 -- Checking and printing
12 checkSingle, checkMatches, isAnyPmCheckEnabled,
13
14 -- See Note [Type and Term Equality Propagation]
15 genCaseTmCs1, genCaseTmCs2
16 ) where
17
18 #include "HsVersions.h"
19
20 import TmOracle
21
22 import DynFlags
23 import HsSyn
24 import TcHsSyn
25 import Id
26 import ConLike
27 import Name
28 import FamInstEnv
29 import TysWiredIn
30 import TyCon
31 import SrcLoc
32 import Util
33 import Outputable
34 import FastString
35 import DataCon
36 import HscTypes (CompleteMatch(..))
37
38 import DsMonad
39 import TcSimplify (tcCheckSatisfiability)
40 import TcType (toTcType, isStringTy, isIntTy, isWordTy)
41 import Bag
42 import ErrUtils
43 import Var (EvVar)
44 import Type
45 import UniqSupply
46 import DsGRHSs (isTrueLHsExpr)
47
48 import Data.List (find)
49 import Data.Maybe (isJust, fromMaybe)
50 import Control.Monad (forM, when, forM_)
51 import Coercion
52 import TcEvidence
53 import IOEnv
54 import Data.Monoid ( Monoid(mappend) )
55
56 import ListT (ListT(..), fold, select)
57
58 {-
59 This module checks pattern matches for:
60 \begin{enumerate}
61 \item Equations that are redundant
62 \item Equations with inaccessible right-hand-side
63 \item Exhaustiveness
64 \end{enumerate}
65
66 The algorithm is based on the paper:
67
68 "GADTs Meet Their Match:
69 Pattern-matching Warnings That Account for GADTs, Guards, and Laziness"
70
71 http://people.cs.kuleuven.be/~george.karachalias/papers/p424-karachalias.pdf
72
73 %************************************************************************
74 %* *
75 Pattern Match Check Types
76 %* *
77 %************************************************************************
78 -}
79
80 -- We use the non-determinism monad to apply the algorithm to several
81 -- possible sets of constructors. Users can specify complete sets of
82 -- constructors by using COMPLETE pragmas.
83 -- The algorithm only picks out constructor
84 -- sets deep in the bowels which makes a simpler `mapM` more difficult to
85 -- implement. The non-determinism is only used in one place, see the ConVar
86 -- case in `pmCheckHd`.
87
88 type PmM a = ListT DsM a
89
90 liftD :: DsM a -> PmM a
91 liftD m = ListT $ \sk fk -> m >>= \a -> sk a fk
92
93 -- Pick the first match complete covered match or otherwise the "best" match.
94 -- The best match is the one with the least uncovered clauses, ties broken
95 -- by the number of inaccessible clauses followed by number of redudant
96 -- clauses
97 getResult :: PmM PmResult -> DsM PmResult
98 getResult ls = do
99 res <- fold ls goM (pure Nothing)
100 case res of
101 Nothing -> panic "getResult is empty"
102 Just a -> return a
103 where
104 goM :: PmResult -> DsM (Maybe PmResult) -> DsM (Maybe PmResult)
105 goM mpm dpm = do
106 pmr <- dpm
107 return $ go pmr mpm
108 -- Careful not to force unecessary results
109 go :: Maybe PmResult -> PmResult -> Maybe PmResult
110 go Nothing rs = Just rs
111 go old@(Just (PmResult prov rs (UncoveredPatterns us) is)) new
112 | null us && null rs && null is = old
113 | otherwise =
114 let PmResult prov' rs' (UncoveredPatterns us') is' = new
115 lr = length rs
116 lr' = length rs'
117 li = length is
118 li' = length is'
119 in case compare (length us) (length us')
120 `mappend` (compare li li')
121 `mappend` (compare lr lr')
122 `mappend` (compare prov prov') of
123 GT -> Just new
124 EQ -> Just new
125 LT -> old
126 go (Just (PmResult _ _ (TypeOfUncovered _) _)) _new
127 = panic "getResult: No inhabitation candidates"
128
129 data PatTy = PAT | VA -- Used only as a kind, to index PmPat
130
131 -- The *arity* of a PatVec [p1,..,pn] is
132 -- the number of p1..pn that are not Guards
133
134 data PmPat :: PatTy -> * where
135 PmCon :: { pm_con_con :: ConLike
136 , pm_con_arg_tys :: [Type]
137 , pm_con_tvs :: [TyVar]
138 , pm_con_dicts :: [EvVar]
139 , pm_con_args :: [PmPat t] } -> PmPat t
140 -- For PmCon arguments' meaning see @ConPatOut@ in hsSyn/HsPat.hs
141 PmVar :: { pm_var_id :: Id } -> PmPat t
142 PmLit :: { pm_lit_lit :: PmLit } -> PmPat t -- See Note [Literals in PmPat]
143 PmNLit :: { pm_lit_id :: Id
144 , pm_lit_not :: [PmLit] } -> PmPat 'VA
145 PmGrd :: { pm_grd_pv :: PatVec
146 , pm_grd_expr :: PmExpr } -> PmPat 'PAT
147
148 -- data T a where
149 -- MkT :: forall p q. (Eq p, Ord q) => p -> q -> T [p]
150 -- or MkT :: forall p q r. (Eq p, Ord q, [p] ~ r) => p -> q -> T r
151
152 type Pattern = PmPat 'PAT -- ^ Patterns
153 type ValAbs = PmPat 'VA -- ^ Value Abstractions
154
155 type PatVec = [Pattern] -- ^ Pattern Vectors
156 data ValVec = ValVec [ValAbs] Delta -- ^ Value Vector Abstractions
157
158 -- | Term and type constraints to accompany each value vector abstraction.
159 -- For efficiency, we store the term oracle state instead of the term
160 -- constraints. TODO: Do the same for the type constraints?
161 data Delta = MkDelta { delta_ty_cs :: Bag EvVar
162 , delta_tm_cs :: TmState }
163
164 type ValSetAbs = [ValVec] -- ^ Value Set Abstractions
165 type Uncovered = ValSetAbs
166
167 -- Instead of keeping the whole sets in memory, we keep a boolean for both the
168 -- covered and the divergent set (we store the uncovered set though, since we
169 -- want to print it). For both the covered and the divergent we have:
170 --
171 -- True <=> The set is non-empty
172 --
173 -- hence:
174 -- C = True ==> Useful clause (no warning)
175 -- C = False, D = True ==> Clause with inaccessible RHS
176 -- C = False, D = False ==> Redundant clause
177
178 data Covered = Covered | NotCovered
179 deriving Show
180
181 instance Outputable Covered where
182 ppr (Covered) = text "Covered"
183 ppr (NotCovered) = text "NotCovered"
184
185 -- Like the or monoid for booleans
186 -- Covered = True, Uncovered = False
187 instance Monoid Covered where
188 mempty = NotCovered
189 Covered `mappend` _ = Covered
190 _ `mappend` Covered = Covered
191 NotCovered `mappend` NotCovered = NotCovered
192
193 data Diverged = Diverged | NotDiverged
194 deriving Show
195
196 instance Outputable Diverged where
197 ppr Diverged = text "Diverged"
198 ppr NotDiverged = text "NotDiverged"
199
200 instance Monoid Diverged where
201 mempty = NotDiverged
202 Diverged `mappend` _ = Diverged
203 _ `mappend` Diverged = Diverged
204 NotDiverged `mappend` NotDiverged = NotDiverged
205
206 -- | When we learned that a given match group is complete
207 data Provenance =
208 FromBuiltin -- ^ From the original definition of the type
209 -- constructor.
210 | FromComplete -- ^ From a user-provided @COMPLETE@ pragma
211 deriving (Show, Eq, Ord)
212
213 instance Outputable Provenance where
214 ppr = text . show
215
216 instance Monoid Provenance where
217 mempty = FromBuiltin
218 FromComplete `mappend` _ = FromComplete
219 _ `mappend` FromComplete = FromComplete
220 _ `mappend` _ = FromBuiltin
221
222 data PartialResult = PartialResult {
223 presultProvenence :: Provenance
224 -- keep track of provenance because we don't want
225 -- to warn about redundant matches if the result
226 -- is contaiminated with a COMPLETE pragma
227 , presultCovered :: Covered
228 , presultUncovered :: Uncovered
229 , presultDivergent :: Diverged }
230
231 instance Outputable PartialResult where
232 ppr (PartialResult prov c vsa d)
233 = text "PartialResult" <+> ppr prov <+> ppr c
234 <+> ppr d <+> ppr vsa
235
236 instance Monoid PartialResult where
237 mempty = PartialResult mempty mempty [] mempty
238 (PartialResult prov1 cs1 vsa1 ds1)
239 `mappend` (PartialResult prov2 cs2 vsa2 ds2)
240 = PartialResult (prov1 `mappend` prov2)
241 (cs1 `mappend` cs2)
242 (vsa1 `mappend` vsa2)
243 (ds1 `mappend` ds2)
244
245 -- newtype ChoiceOf a = ChoiceOf [a]
246
247 -- | Pattern check result
248 --
249 -- * Redundant clauses
250 -- * Not-covered clauses (or their type, if no pattern is available)
251 -- * Clauses with inaccessible RHS
252 --
253 -- More details about the classification of clauses into useful, redundant
254 -- and with inaccessible right hand side can be found here:
255 --
256 -- https://ghc.haskell.org/trac/ghc/wiki/PatternMatchCheck
257 --
258 data PmResult =
259 PmResult {
260 pmresultProvenance :: Provenance
261 , pmresultRedundant :: [Located [LPat Id]]
262 , pmresultUncovered :: UncoveredCandidates
263 , pmresultInaccessible :: [Located [LPat Id]] }
264
265 -- | Either a list of patterns that are not covered, or their type, in case we
266 -- have no patterns at hand. Not having patterns at hand can arise when
267 -- handling EmptyCase expressions, in two cases:
268 --
269 -- * The type of the scrutinee is a trivially inhabited type (like Int or Char)
270 -- * The type of the scrutinee cannot be reduced to WHNF.
271 --
272 -- In both these cases we have no inhabitation candidates for the type at hand,
273 -- but we don't want to issue just a wildcard as missing. Instead, we print a
274 -- type annotated wildcard, so that the user knows what kind of patterns is
275 -- expected (e.g. (_ :: Int), or (_ :: F Int), where F Int does not reduce).
276 data UncoveredCandidates = UncoveredPatterns Uncovered
277 | TypeOfUncovered Type
278
279 -- | The empty pattern check result
280 emptyPmResult :: PmResult
281 emptyPmResult = PmResult FromBuiltin [] (UncoveredPatterns []) []
282
283 -- | Non-exhaustive empty case with unknown/trivial inhabitants
284 uncoveredWithTy :: Type -> PmResult
285 uncoveredWithTy ty = PmResult FromBuiltin [] (TypeOfUncovered ty) []
286
287 {-
288 %************************************************************************
289 %* *
290 Entry points to the checker: checkSingle and checkMatches
291 %* *
292 %************************************************************************
293 -}
294
295 -- | Check a single pattern binding (let)
296 checkSingle :: DynFlags -> DsMatchContext -> Id -> Pat Id -> DsM ()
297 checkSingle dflags ctxt@(DsMatchContext _ locn) var p = do
298 tracePmD "checkSingle" (vcat [ppr ctxt, ppr var, ppr p])
299 mb_pm_res <- tryM (getResult (checkSingle' locn var p))
300 case mb_pm_res of
301 Left _ -> warnPmIters dflags ctxt
302 Right res -> dsPmWarn dflags ctxt res
303
304 -- | Check a single pattern binding (let)
305 checkSingle' :: SrcSpan -> Id -> Pat Id -> PmM PmResult
306 checkSingle' locn var p = do
307 liftD resetPmIterDs -- set the iter-no to zero
308 fam_insts <- liftD dsGetFamInstEnvs
309 clause <- liftD $ translatePat fam_insts p
310 missing <- mkInitialUncovered [var]
311 tracePm "checkSingle: missing" (vcat (map pprValVecDebug missing))
312 -- no guards
313 PartialResult prov cs us ds <- runMany (pmcheckI clause []) missing
314 let us' = UncoveredPatterns us
315 return $ case (cs,ds) of
316 (Covered, _ ) -> PmResult prov [] us' [] -- useful
317 (NotCovered, NotDiverged) -> PmResult prov m us' [] -- redundant
318 (NotCovered, Diverged ) -> PmResult prov [] us' m -- inaccessible rhs
319 where m = [L locn [L locn p]]
320
321 -- | Check a matchgroup (case, functions, etc.)
322 checkMatches :: DynFlags -> DsMatchContext
323 -> [Id] -> [LMatch Id (LHsExpr Id)] -> DsM ()
324 checkMatches dflags ctxt vars matches = do
325 tracePmD "checkMatches" (hang (vcat [ppr ctxt
326 , ppr vars
327 , text "Matches:"])
328 2
329 (vcat (map ppr matches)))
330 mb_pm_res <- tryM $ getResult $ case matches of
331 -- Check EmptyCase separately
332 -- See Note [Checking EmptyCase Expressions]
333 [] | [var] <- vars -> checkEmptyCase' var
334 _normal_match -> checkMatches' vars matches
335 case mb_pm_res of
336 Left _ -> warnPmIters dflags ctxt
337 Right res -> dsPmWarn dflags ctxt res
338
339 -- | Check a matchgroup (case, functions, etc.). To be called on a non-empty
340 -- list of matches. For empty case expressions, use checkEmptyCase' instead.
341 checkMatches' :: [Id] -> [LMatch Id (LHsExpr Id)] -> PmM PmResult
342 checkMatches' vars matches
343 | null matches = panic "checkMatches': EmptyCase"
344 | otherwise = do
345 liftD resetPmIterDs -- set the iter-no to zero
346 missing <- mkInitialUncovered vars
347 tracePm "checkMatches: missing" (vcat (map pprValVecDebug missing))
348 (prov, rs,us,ds) <- go matches missing
349 return $ PmResult {
350 pmresultProvenance = prov
351 , pmresultRedundant = map hsLMatchToLPats rs
352 , pmresultUncovered = UncoveredPatterns us
353 , pmresultInaccessible = map hsLMatchToLPats ds }
354 where
355 go :: [LMatch Id (LHsExpr Id)] -> Uncovered
356 -> PmM (Provenance
357 , [LMatch Id (LHsExpr Id)]
358 , Uncovered
359 , [LMatch Id (LHsExpr Id)])
360 go [] missing = return (mempty, [], missing, [])
361 go (m:ms) missing = do
362 tracePm "checMatches': go" (ppr m $$ ppr missing)
363 fam_insts <- liftD dsGetFamInstEnvs
364 (clause, guards) <- liftD $ translateMatch fam_insts m
365 r@(PartialResult prov cs missing' ds)
366 <- runMany (pmcheckI clause guards) missing
367 tracePm "checMatches': go: res" (ppr r)
368 (ms_prov, rs, final_u, is) <- go ms missing'
369 let final_prov = prov `mappend` ms_prov
370 return $ case (cs, ds) of
371 -- useful
372 (Covered, _ ) -> (final_prov, rs, final_u, is)
373 -- redundant
374 (NotCovered, NotDiverged) -> (final_prov, m:rs, final_u,is)
375 -- inaccessible
376 (NotCovered, Diverged ) -> (final_prov, rs, final_u, m:is)
377
378 hsLMatchToLPats :: LMatch id body -> Located [LPat id]
379 hsLMatchToLPats (L l (Match _ pats _ _)) = L l pats
380
381 -- | Check an empty case expression. Since there are no clauses to process, we
382 -- only compute the uncovered set. See Note [Checking EmptyCase Expressions]
383 -- for details.
384 checkEmptyCase' :: Id -> PmM PmResult
385 checkEmptyCase' var = do
386 tm_css <- map toComplex . bagToList <$> liftD getTmCsDs
387 case tmOracle initialTmState tm_css of
388 Just tm_state -> do
389 ty_css <- liftD getDictsDs
390 fam_insts <- liftD dsGetFamInstEnvs
391 mb_candidates <- inhabitationCandidates fam_insts (idType var)
392 case mb_candidates of
393 -- Inhabitation checking failed / the type is trivially inhabited
394 Left ty -> return (uncoveredWithTy ty)
395
396 -- A list of inhabitant candidates is available: Check for each
397 -- one for the satisfiability of the constraints it gives rise to.
398 Right candidates -> do
399 missing_m <- flip concatMapM candidates $ \(va,tm_ct,ty_cs) -> do
400 let all_ty_cs = unionBags ty_cs ty_css
401 sat_ty <- tyOracle all_ty_cs
402 return $ case (sat_ty, tmOracle tm_state (tm_ct:tm_css)) of
403 (True, Just tm_state') -> [(va, all_ty_cs, tm_state')]
404 _non_sat -> []
405 let mkValVec (va,all_ty_cs,tm_state')
406 = ValVec [va] (MkDelta all_ty_cs tm_state')
407 uncovered = UncoveredPatterns (map mkValVec missing_m)
408 return $ if null missing_m
409 then emptyPmResult
410 else PmResult FromBuiltin [] uncovered []
411 Nothing -> return emptyPmResult
412
413 -- | Generate all inhabitation candidates for a given type. The result is
414 -- either (Left ty), if the type cannot be reduced to a closed algebraic type
415 -- (or if it's one trivially inhabited, like Int), or (Right candidates), if it
416 -- can. In this case, the candidates are the singnature of the tycon, each one
417 -- accompanied by the term- and type- constraints it gives rise to.
418 -- See also Note [Checking EmptyCase Expressions]
419 inhabitationCandidates :: FamInstEnvs -> Type
420 -> PmM (Either Type [(ValAbs, ComplexEq, Bag EvVar)])
421 inhabitationCandidates fam_insts ty
422 = case pmTopNormaliseType_maybe fam_insts ty of
423 Just (src_ty, dcs, core_ty) -> alts_to_check src_ty core_ty dcs
424 Nothing -> alts_to_check ty ty []
425 where
426 -- All these types are trivially inhabited
427 trivially_inhabited = [ charTyCon, doubleTyCon, floatTyCon
428 , intTyCon, wordTyCon, word8TyCon ]
429
430 -- Note: At the moment we leave all the typing and constraint fields of
431 -- PmCon empty, since we know that they are not gonna be used. Is the
432 -- right-thing-to-do to actually create them, even if they are never used?
433 build_tm :: ValAbs -> [DataCon] -> ValAbs
434 build_tm = foldr (\dc e -> PmCon (RealDataCon dc) [] [] [] [e])
435
436 -- Inhabitation candidates, using the result of pmTopNormaliseType_maybe
437 alts_to_check :: Type -> Type -> [DataCon]
438 -> PmM (Either Type [(ValAbs, ComplexEq, Bag EvVar)])
439 alts_to_check src_ty core_ty dcs = case splitTyConApp_maybe core_ty of
440 Just (tc, _)
441 | tc `elem` trivially_inhabited -> case dcs of
442 [] -> return (Left src_ty)
443 (_:_) -> do var <- liftD $ mkPmId (toTcType core_ty)
444 let va = build_tm (PmVar var) dcs
445 return $ Right [(va, mkIdEq var, emptyBag)]
446 | isClosedAlgType core_ty -> liftD $ do
447 var <- mkPmId (toTcType core_ty) -- it would be wrong to unify x
448 alts <- mapM (mkOneConFull var . RealDataCon) (tyConDataCons tc)
449 return $ Right [(build_tm va dcs, eq, cs) | (va, eq, cs) <- alts]
450 -- For other types conservatively assume that they are inhabited.
451 _other -> return (Left src_ty)
452
453 {- Note [Checking EmptyCase Expressions]
454 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
455 Empty case expressions are strict on the scrutinee. That is, `case x of {}`
456 will force argument `x`. Hence, `checkMatches` is not sufficient for checking
457 empty cases, because it assumes that the match is not strict (which is true
458 for all other cases, apart from EmptyCase). This gave rise to #10746. Instead,
459 we do the following:
460
461 1. We normalise the outermost type family redex, data family redex or newtype,
462 using pmTopNormaliseType_maybe (in types/FamInstEnv.hs). This computes 3
463 things:
464 (a) A normalised type src_ty, which is equal to the type of the scrutinee in
465 source Haskell (does not normalise newtypes or data families)
466 (b) The actual normalised type core_ty, which coincides with the result
467 topNormaliseType_maybe. This type is not necessarily equal to the input
468 type in source Haskell. And this is precicely the reason we compute (a)
469 and (c): the reasoning happens with the underlying types, but both the
470 patterns and types we print should respect newtypes and also show the
471 family type constructors and not the representation constructors.
472
473 (c) A list of all newtype data constructors dcs, each one corresponding to a
474 newtype rewrite performed in (b).
475
476 For an example see also Note [Type normalisation for EmptyCase]
477 in types/FamInstEnv.hs.
478
479 2. Function checkEmptyCase' performs the check:
480 - If core_ty is not an algebraic type, then we cannot check for
481 inhabitation, so we emit (_ :: src_ty) as missing, conservatively assuming
482 that the type is inhabited.
483 - If core_ty is an algebraic type, then we unfold the scrutinee to all
484 possible constructor patterns, using inhabitationCandidates, and then
485 check each one for constraint satisfiability, same as we for normal
486 pattern match checking.
487
488 %************************************************************************
489 %* *
490 Transform source syntax to *our* syntax
491 %* *
492 %************************************************************************
493 -}
494
495 -- -----------------------------------------------------------------------
496 -- * Utilities
497
498 nullaryConPattern :: ConLike -> Pattern
499 -- Nullary data constructor and nullary type constructor
500 nullaryConPattern con =
501 PmCon { pm_con_con = con, pm_con_arg_tys = []
502 , pm_con_tvs = [], pm_con_dicts = [], pm_con_args = [] }
503 {-# INLINE nullaryConPattern #-}
504
505 truePattern :: Pattern
506 truePattern = nullaryConPattern (RealDataCon trueDataCon)
507 {-# INLINE truePattern #-}
508
509 -- | A fake guard pattern (True <- _) used to represent cases we cannot handle
510 fake_pat :: Pattern
511 fake_pat = PmGrd { pm_grd_pv = [truePattern]
512 , pm_grd_expr = PmExprOther EWildPat }
513 {-# INLINE fake_pat #-}
514
515 -- | Check whether a guard pattern is generated by the checker (unhandled)
516 isFakeGuard :: [Pattern] -> PmExpr -> Bool
517 isFakeGuard [PmCon { pm_con_con = RealDataCon c }] (PmExprOther EWildPat)
518 | c == trueDataCon = True
519 | otherwise = False
520 isFakeGuard _pats _e = False
521
522 -- | Generate a `canFail` pattern vector of a specific type
523 mkCanFailPmPat :: Type -> DsM PatVec
524 mkCanFailPmPat ty = do
525 var <- mkPmVar ty
526 return [var, fake_pat]
527
528 vanillaConPattern :: ConLike -> [Type] -> PatVec -> Pattern
529 -- ADT constructor pattern => no existentials, no local constraints
530 vanillaConPattern con arg_tys args =
531 PmCon { pm_con_con = con, pm_con_arg_tys = arg_tys
532 , pm_con_tvs = [], pm_con_dicts = [], pm_con_args = args }
533 {-# INLINE vanillaConPattern #-}
534
535 -- | Create an empty list pattern of a given type
536 nilPattern :: Type -> Pattern
537 nilPattern ty =
538 PmCon { pm_con_con = RealDataCon nilDataCon, pm_con_arg_tys = [ty]
539 , pm_con_tvs = [], pm_con_dicts = []
540 , pm_con_args = [] }
541 {-# INLINE nilPattern #-}
542
543 mkListPatVec :: Type -> PatVec -> PatVec -> PatVec
544 mkListPatVec ty xs ys = [PmCon { pm_con_con = RealDataCon consDataCon
545 , pm_con_arg_tys = [ty]
546 , pm_con_tvs = [], pm_con_dicts = []
547 , pm_con_args = xs++ys }]
548 {-# INLINE mkListPatVec #-}
549
550 -- | Create a (non-overloaded) literal pattern
551 mkLitPattern :: HsLit -> Pattern
552 mkLitPattern lit = PmLit { pm_lit_lit = PmSLit lit }
553 {-# INLINE mkLitPattern #-}
554
555 -- -----------------------------------------------------------------------
556 -- * Transform (Pat Id) into of (PmPat Id)
557
558 translatePat :: FamInstEnvs -> Pat Id -> DsM PatVec
559 translatePat fam_insts pat = case pat of
560 WildPat ty -> mkPmVars [ty]
561 VarPat id -> return [PmVar (unLoc id)]
562 ParPat p -> translatePat fam_insts (unLoc p)
563 LazyPat _ -> mkPmVars [hsPatType pat] -- like a variable
564
565 -- ignore strictness annotations for now
566 BangPat p -> translatePat fam_insts (unLoc p)
567
568 AsPat lid p -> do
569 -- Note [Translating As Patterns]
570 ps <- translatePat fam_insts (unLoc p)
571 let [e] = map vaToPmExpr (coercePatVec ps)
572 g = PmGrd [PmVar (unLoc lid)] e
573 return (ps ++ [g])
574
575 SigPatOut p _ty -> translatePat fam_insts (unLoc p)
576
577 -- See Note [Translate CoPats]
578 CoPat wrapper p ty
579 | isIdHsWrapper wrapper -> translatePat fam_insts p
580 | WpCast co <- wrapper, isReflexiveCo co -> translatePat fam_insts p
581 | otherwise -> do
582 ps <- translatePat fam_insts p
583 (xp,xe) <- mkPmId2Forms ty
584 let g = mkGuard ps (HsWrap wrapper (unLoc xe))
585 return [xp,g]
586
587 -- (n + k) ===> x (True <- x >= k) (n <- x-k)
588 NPlusKPat (L _ _n) _k1 _k2 _ge _minus ty -> mkCanFailPmPat ty
589
590 -- (fun -> pat) ===> x (pat <- fun x)
591 ViewPat lexpr lpat arg_ty -> do
592 ps <- translatePat fam_insts (unLoc lpat)
593 -- See Note [Guards and Approximation]
594 case all cantFailPattern ps of
595 True -> do
596 (xp,xe) <- mkPmId2Forms arg_ty
597 let g = mkGuard ps (HsApp lexpr xe)
598 return [xp,g]
599 False -> mkCanFailPmPat arg_ty
600
601 -- list
602 ListPat ps ty Nothing -> do
603 foldr (mkListPatVec ty) [nilPattern ty]
604 <$> translatePatVec fam_insts (map unLoc ps)
605
606 -- overloaded list
607 ListPat lpats elem_ty (Just (pat_ty, _to_list))
608 | Just e_ty <- splitListTyConApp_maybe pat_ty
609 , (_, norm_elem_ty) <- normaliseType fam_insts Nominal elem_ty
610 -- elem_ty is frequently something like
611 -- `Item [Int]`, but we prefer `Int`
612 , norm_elem_ty `eqType` e_ty ->
613 -- We have to ensure that the element types are exactly the same.
614 -- Otherwise, one may give an instance IsList [Int] (more specific than
615 -- the default IsList [a]) with a different implementation for `toList'
616 translatePat fam_insts (ListPat lpats e_ty Nothing)
617 -- See Note [Guards and Approximation]
618 | otherwise -> mkCanFailPmPat pat_ty
619
620 ConPatOut { pat_con = L _ con
621 , pat_arg_tys = arg_tys
622 , pat_tvs = ex_tvs
623 , pat_dicts = dicts
624 , pat_args = ps } -> do
625 groups <- allCompleteMatches con arg_tys
626 case groups of
627 [] -> mkCanFailPmPat (conLikeResTy con arg_tys)
628 _ -> do
629 args <- translateConPatVec fam_insts arg_tys ex_tvs con ps
630 return [PmCon { pm_con_con = con
631 , pm_con_arg_tys = arg_tys
632 , pm_con_tvs = ex_tvs
633 , pm_con_dicts = dicts
634 , pm_con_args = args }]
635
636 NPat (L _ ol) mb_neg _eq ty -> translateNPat fam_insts ol mb_neg ty
637
638 LitPat lit
639 -- If it is a string then convert it to a list of characters
640 | HsString src s <- lit ->
641 foldr (mkListPatVec charTy) [nilPattern charTy] <$>
642 translatePatVec fam_insts (map (LitPat . HsChar src) (unpackFS s))
643 | otherwise -> return [mkLitPattern lit]
644
645 PArrPat ps ty -> do
646 tidy_ps <- translatePatVec fam_insts (map unLoc ps)
647 let fake_con = RealDataCon (parrFakeCon (length ps))
648 return [vanillaConPattern fake_con [ty] (concat tidy_ps)]
649
650 TuplePat ps boxity tys -> do
651 tidy_ps <- translatePatVec fam_insts (map unLoc ps)
652 let tuple_con = RealDataCon (tupleDataCon boxity (length ps))
653 return [vanillaConPattern tuple_con tys (concat tidy_ps)]
654
655 SumPat p alt arity ty -> do
656 tidy_p <- translatePat fam_insts (unLoc p)
657 let sum_con = RealDataCon (sumDataCon alt arity)
658 return [vanillaConPattern sum_con ty tidy_p]
659
660 -- --------------------------------------------------------------------------
661 -- Not supposed to happen
662 ConPatIn {} -> panic "Check.translatePat: ConPatIn"
663 SplicePat {} -> panic "Check.translatePat: SplicePat"
664 SigPatIn {} -> panic "Check.translatePat: SigPatIn"
665
666 -- | Translate an overloaded literal (see `tidyNPat' in deSugar/MatchLit.hs)
667 translateNPat :: FamInstEnvs
668 -> HsOverLit Id -> Maybe (SyntaxExpr Id) -> Type -> DsM PatVec
669 translateNPat fam_insts (OverLit val False _ ty) mb_neg outer_ty
670 | not type_change, isStringTy ty, HsIsString src s <- val, Nothing <- mb_neg
671 = translatePat fam_insts (LitPat (HsString src s))
672 | not type_change, isIntTy ty, HsIntegral src i <- val
673 = translatePat fam_insts (mk_num_lit HsInt src i)
674 | not type_change, isWordTy ty, HsIntegral src i <- val
675 = translatePat fam_insts (mk_num_lit HsWordPrim src i)
676 where
677 type_change = not (outer_ty `eqType` ty)
678 mk_num_lit c src i = LitPat $ case mb_neg of
679 Nothing -> c src i
680 Just _ -> c src (-i)
681 translateNPat _ ol mb_neg _
682 = return [PmLit { pm_lit_lit = PmOLit (isJust mb_neg) ol }]
683
684 -- | Translate a list of patterns (Note: each pattern is translated
685 -- to a pattern vector but we do not concatenate the results).
686 translatePatVec :: FamInstEnvs -> [Pat Id] -> DsM [PatVec]
687 translatePatVec fam_insts pats = mapM (translatePat fam_insts) pats
688
689 -- | Translate a constructor pattern
690 translateConPatVec :: FamInstEnvs -> [Type] -> [TyVar]
691 -> ConLike -> HsConPatDetails Id -> DsM PatVec
692 translateConPatVec fam_insts _univ_tys _ex_tvs _ (PrefixCon ps)
693 = concat <$> translatePatVec fam_insts (map unLoc ps)
694 translateConPatVec fam_insts _univ_tys _ex_tvs _ (InfixCon p1 p2)
695 = concat <$> translatePatVec fam_insts (map unLoc [p1,p2])
696 translateConPatVec fam_insts univ_tys ex_tvs c (RecCon (HsRecFields fs _))
697 -- Nothing matched. Make up some fresh term variables
698 | null fs = mkPmVars arg_tys
699 -- The data constructor was not defined using record syntax. For the
700 -- pattern to be in record syntax it should be empty (e.g. Just {}).
701 -- So just like the previous case.
702 | null orig_lbls = ASSERT(null matched_lbls) mkPmVars arg_tys
703 -- Some of the fields appear, in the original order (there may be holes).
704 -- Generate a simple constructor pattern and make up fresh variables for
705 -- the rest of the fields
706 | matched_lbls `subsetOf` orig_lbls
707 = ASSERT(length orig_lbls == length arg_tys)
708 let translateOne (lbl, ty) = case lookup lbl matched_pats of
709 Just p -> translatePat fam_insts p
710 Nothing -> mkPmVars [ty]
711 in concatMapM translateOne (zip orig_lbls arg_tys)
712 -- The fields that appear are not in the correct order. Make up fresh
713 -- variables for all fields and add guards after matching, to force the
714 -- evaluation in the correct order.
715 | otherwise = do
716 arg_var_pats <- mkPmVars arg_tys
717 translated_pats <- forM matched_pats $ \(x,pat) -> do
718 pvec <- translatePat fam_insts pat
719 return (x, pvec)
720
721 let zipped = zip orig_lbls [ x | PmVar x <- arg_var_pats ]
722 guards = map (\(name,pvec) -> case lookup name zipped of
723 Just x -> PmGrd pvec (PmExprVar (idName x))
724 Nothing -> panic "translateConPatVec: lookup")
725 translated_pats
726
727 return (arg_var_pats ++ guards)
728 where
729 -- The actual argument types (instantiated)
730 arg_tys = conLikeInstOrigArgTys c (univ_tys ++ mkTyVarTys ex_tvs)
731
732 -- Some label information
733 orig_lbls = map flSelector $ conLikeFieldLabels c
734 matched_pats = [ (getName (unLoc (hsRecFieldId x)), unLoc (hsRecFieldArg x))
735 | L _ x <- fs]
736 matched_lbls = [ name | (name, _pat) <- matched_pats ]
737
738 subsetOf :: Eq a => [a] -> [a] -> Bool
739 subsetOf [] _ = True
740 subsetOf (_:_) [] = False
741 subsetOf (x:xs) (y:ys)
742 | x == y = subsetOf xs ys
743 | otherwise = subsetOf (x:xs) ys
744
745 -- Translate a single match
746 translateMatch :: FamInstEnvs -> LMatch Id (LHsExpr Id) -> DsM (PatVec,[PatVec])
747 translateMatch fam_insts (L _ (Match _ lpats _ grhss)) = do
748 pats' <- concat <$> translatePatVec fam_insts pats
749 guards' <- mapM (translateGuards fam_insts) guards
750 return (pats', guards')
751 where
752 extractGuards :: LGRHS Id (LHsExpr Id) -> [GuardStmt Id]
753 extractGuards (L _ (GRHS gs _)) = map unLoc gs
754
755 pats = map unLoc lpats
756 guards = map extractGuards (grhssGRHSs grhss)
757
758 -- -----------------------------------------------------------------------
759 -- * Transform source guards (GuardStmt Id) to PmPats (Pattern)
760
761 -- | Translate a list of guard statements to a pattern vector
762 translateGuards :: FamInstEnvs -> [GuardStmt Id] -> DsM PatVec
763 translateGuards fam_insts guards = do
764 all_guards <- concat <$> mapM (translateGuard fam_insts) guards
765 return (replace_unhandled all_guards)
766 -- It should have been (return all_guards) but it is too expressive.
767 -- Since the term oracle does not handle all constraints we generate,
768 -- we (hackily) replace all constraints the oracle cannot handle with a
769 -- single one (we need to know if there is a possibility of falure).
770 -- See Note [Guards and Approximation] for all guard-related approximations
771 -- we implement.
772 where
773 replace_unhandled :: PatVec -> PatVec
774 replace_unhandled gv
775 | any_unhandled gv = fake_pat : [ p | p <- gv, shouldKeep p ]
776 | otherwise = gv
777
778 any_unhandled :: PatVec -> Bool
779 any_unhandled gv = any (not . shouldKeep) gv
780
781 shouldKeep :: Pattern -> Bool
782 shouldKeep p
783 | PmVar {} <- p = True
784 | PmCon {} <- p = singleConstructor (pm_con_con p)
785 && all shouldKeep (pm_con_args p)
786 shouldKeep (PmGrd pv e)
787 | all shouldKeep pv = True
788 | isNotPmExprOther e = True -- expensive but we want it
789 shouldKeep _other_pat = False -- let the rest..
790
791 -- | Check whether a pattern can fail to match
792 cantFailPattern :: Pattern -> Bool
793 cantFailPattern p
794 | PmVar {} <- p = True
795 | PmCon {} <- p = singleConstructor (pm_con_con p)
796 && all cantFailPattern (pm_con_args p)
797 cantFailPattern (PmGrd pv _e)
798 = all cantFailPattern pv
799 cantFailPattern _ = False
800
801 -- | Translate a guard statement to Pattern
802 translateGuard :: FamInstEnvs -> GuardStmt Id -> DsM PatVec
803 translateGuard fam_insts guard = case guard of
804 BodyStmt e _ _ _ -> translateBoolGuard e
805 LetStmt binds -> translateLet (unLoc binds)
806 BindStmt p e _ _ _ -> translateBind fam_insts p e
807 LastStmt {} -> panic "translateGuard LastStmt"
808 ParStmt {} -> panic "translateGuard ParStmt"
809 TransStmt {} -> panic "translateGuard TransStmt"
810 RecStmt {} -> panic "translateGuard RecStmt"
811 ApplicativeStmt {} -> panic "translateGuard ApplicativeLastStmt"
812
813 -- | Translate let-bindings
814 translateLet :: HsLocalBinds Id -> DsM PatVec
815 translateLet _binds = return []
816
817 -- | Translate a pattern guard
818 translateBind :: FamInstEnvs -> LPat Id -> LHsExpr Id -> DsM PatVec
819 translateBind fam_insts (L _ p) e = do
820 ps <- translatePat fam_insts p
821 return [mkGuard ps (unLoc e)]
822
823 -- | Translate a boolean guard
824 translateBoolGuard :: LHsExpr Id -> DsM PatVec
825 translateBoolGuard e
826 | isJust (isTrueLHsExpr e) = return []
827 -- The formal thing to do would be to generate (True <- True)
828 -- but it is trivial to solve so instead we give back an empty
829 -- PatVec for efficiency
830 | otherwise = return [mkGuard [truePattern] (unLoc e)]
831
832 {- Note [Guards and Approximation]
833 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
834 Even if the algorithm is really expressive, the term oracle we use is not.
835 Hence, several features are not translated *properly* but we approximate.
836 The list includes:
837
838 1. View Patterns
839 ----------------
840 A view pattern @(f -> p)@ should be translated to @x (p <- f x)@. The term
841 oracle does not handle function applications so we know that the generated
842 constraints will not be handled at the end. Hence, we distinguish between two
843 cases:
844 a) Pattern @p@ cannot fail. Then this is just a binding and we do the *right
845 thing*.
846 b) Pattern @p@ can fail. This means that when checking the guard, we will
847 generate several cases, with no useful information. E.g.:
848
849 h (f -> [a,b]) = ...
850 h x ([a,b] <- f x) = ...
851
852 uncovered set = { [x |> { False ~ (f x ~ []) }]
853 , [x |> { False ~ (f x ~ (t1:[])) }]
854 , [x |> { False ~ (f x ~ (t1:t2:t3:t4)) }] }
855
856 So we have two problems:
857 1) Since we do not print the constraints in the general case (they may
858 be too many), the warning will look like this:
859
860 Pattern match(es) are non-exhaustive
861 In an equation for `h':
862 Patterns not matched:
863 _
864 _
865 _
866 Which is not short and not more useful than a single underscore.
867 2) The size of the uncovered set increases a lot, without gaining more
868 expressivity in our warnings.
869
870 Hence, in this case, we replace the guard @([a,b] <- f x)@ with a *dummy*
871 @fake_pat@: @True <- _@. That is, we record that there is a possibility
872 of failure but we minimize it to a True/False. This generates a single
873 warning and much smaller uncovered sets.
874
875 2. Overloaded Lists
876 -------------------
877 An overloaded list @[...]@ should be translated to @x ([...] <- toList x)@. The
878 problem is exactly like above, as its solution. For future reference, the code
879 below is the *right thing to do*:
880
881 ListPat lpats elem_ty (Just (pat_ty, to_list))
882 otherwise -> do
883 (xp, xe) <- mkPmId2Forms pat_ty
884 ps <- translatePatVec (map unLoc lpats)
885 let pats = foldr (mkListPatVec elem_ty) [nilPattern elem_ty] ps
886 g = mkGuard pats (HsApp (noLoc to_list) xe)
887 return [xp,g]
888
889 3. Overloaded Literals
890 ----------------------
891 The case with literals is a bit different. a literal @l@ should be translated
892 to @x (True <- x == from l)@. Since we want to have better warnings for
893 overloaded literals as it is a very common feature, we treat them differently.
894 They are mainly covered in Note [Undecidable Equality on Overloaded Literals]
895 in PmExpr.
896
897 4. N+K Patterns & Pattern Synonyms
898 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
899 An n+k pattern (n+k) should be translated to @x (True <- x >= k) (n <- x-k)@.
900 Since the only pattern of the three that causes failure is guard @(n <- x-k)@,
901 and has two possible outcomes. Hence, there is no benefit in using a dummy and
902 we implement the proper thing. Pattern synonyms are simply not implemented yet.
903 Hence, to be conservative, we generate a dummy pattern, assuming that the
904 pattern can fail.
905
906 5. Actual Guards
907 ----------------
908 During translation, boolean guards and pattern guards are translated properly.
909 Let bindings though are omitted by function @translateLet@. Since they are lazy
910 bindings, we do not actually want to generate a (strict) equality (like we do
911 in the pattern bind case). Hence, we safely drop them.
912
913 Additionally, top-level guard translation (performed by @translateGuards@)
914 replaces guards that cannot be reasoned about (like the ones we described in
915 1-4) with a single @fake_pat@ to record the possibility of failure to match.
916
917 Note [Translate CoPats]
918 ~~~~~~~~~~~~~~~~~~~~~~~
919 The pattern match checker did not know how to handle coerced patterns `CoPat`
920 efficiently, which gave rise to #11276. The original approach translated
921 `CoPat`s:
922
923 pat |> co ===> x (pat <- (e |> co))
924
925 Instead, we now check whether the coercion is a hole or if it is just refl, in
926 which case we can drop it. Unfortunately, data families generate useful
927 coercions so guards are still generated in these cases and checking data
928 families is not really efficient.
929
930 %************************************************************************
931 %* *
932 Utilities for Pattern Match Checking
933 %* *
934 %************************************************************************
935 -}
936
937 -- ----------------------------------------------------------------------------
938 -- * Basic utilities
939
940 -- | Get the type out of a PmPat. For guard patterns (ps <- e) we use the type
941 -- of the first (or the single -WHEREVER IT IS- valid to use?) pattern
942 pmPatType :: PmPat p -> Type
943 pmPatType (PmCon { pm_con_con = con, pm_con_arg_tys = tys })
944 = conLikeResTy con tys
945 pmPatType (PmVar { pm_var_id = x }) = idType x
946 pmPatType (PmLit { pm_lit_lit = l }) = pmLitType l
947 pmPatType (PmNLit { pm_lit_id = x }) = idType x
948 pmPatType (PmGrd { pm_grd_pv = pv })
949 = ASSERT(patVecArity pv == 1) (pmPatType p)
950 where Just p = find ((==1) . patternArity) pv
951
952 -- | Generate a value abstraction for a given constructor (generate
953 -- fresh variables of the appropriate type for arguments)
954 mkOneConFull :: Id -> ConLike -> DsM (ValAbs, ComplexEq, Bag EvVar)
955 -- * x :: T tys, where T is an algebraic data type
956 -- NB: in the case of a data family, T is the *representation* TyCon
957 -- e.g. data instance T (a,b) = T1 a b
958 -- leads to
959 -- data TPair a b = T1 a b -- The "representation" type
960 -- It is TPair, not T, that is given to mkOneConFull
961 --
962 -- * 'con' K is a constructor of data type T
963 --
964 -- After instantiating the universal tyvars of K we get
965 -- K tys :: forall bs. Q => s1 .. sn -> T tys
966 --
967 -- Results: ValAbs: K (y1::s1) .. (yn::sn)
968 -- ComplexEq: x ~ K y1..yn
969 -- [EvVar]: Q
970 mkOneConFull x con = do
971 let -- res_ty == TyConApp (ConLikeTyCon cabs_con) cabs_arg_tys
972 res_ty = idType x
973 (univ_tvs, ex_tvs, eq_spec, thetas, _req_theta , arg_tys, _)
974 = conLikeFullSig con
975 tc_args = case splitTyConApp_maybe res_ty of
976 Just (_, tys) -> tys
977 Nothing -> pprPanic "mkOneConFull: Not TyConApp:" (ppr res_ty)
978 subst1 = zipTvSubst univ_tvs tc_args
979
980 (subst, ex_tvs') <- cloneTyVarBndrs subst1 ex_tvs <$> getUniqueSupplyM
981
982 -- Fresh term variables (VAs) as arguments to the constructor
983 arguments <- mapM mkPmVar (substTys subst arg_tys)
984 -- All constraints bound by the constructor (alpha-renamed)
985 let theta_cs = substTheta subst (eqSpecPreds eq_spec ++ thetas)
986 evvars <- mapM (nameType "pm") theta_cs
987 let con_abs = PmCon { pm_con_con = con
988 , pm_con_arg_tys = tc_args
989 , pm_con_tvs = ex_tvs'
990 , pm_con_dicts = evvars
991 , pm_con_args = arguments }
992 return (con_abs, (PmExprVar (idName x), vaToPmExpr con_abs), listToBag evvars)
993
994 -- ----------------------------------------------------------------------------
995 -- * More smart constructors and fresh variable generation
996
997 -- | Create a guard pattern
998 mkGuard :: PatVec -> HsExpr Id -> Pattern
999 mkGuard pv e
1000 | all cantFailPattern pv = PmGrd pv expr
1001 | PmExprOther {} <- expr = fake_pat
1002 | otherwise = PmGrd pv expr
1003 where
1004 expr = hsExprToPmExpr e
1005
1006 -- | Create a term equality of the form: `(False ~ (x ~ lit))`
1007 mkNegEq :: Id -> PmLit -> ComplexEq
1008 mkNegEq x l = (falsePmExpr, PmExprVar (idName x) `PmExprEq` PmExprLit l)
1009 {-# INLINE mkNegEq #-}
1010
1011 -- | Create a term equality of the form: `(x ~ lit)`
1012 mkPosEq :: Id -> PmLit -> ComplexEq
1013 mkPosEq x l = (PmExprVar (idName x), PmExprLit l)
1014 {-# INLINE mkPosEq #-}
1015
1016 -- | Create a term equality of the form: `(x ~ x)`
1017 -- (always discharged by the term oracle)
1018 mkIdEq :: Id -> ComplexEq
1019 mkIdEq x = (PmExprVar name, PmExprVar name)
1020 where name = idName x
1021 {-# INLINE mkIdEq #-}
1022
1023 -- | Generate a variable pattern of a given type
1024 mkPmVar :: Type -> DsM (PmPat p)
1025 mkPmVar ty = PmVar <$> mkPmId ty
1026 {-# INLINE mkPmVar #-}
1027
1028 -- | Generate many variable patterns, given a list of types
1029 mkPmVars :: [Type] -> DsM PatVec
1030 mkPmVars tys = mapM mkPmVar tys
1031 {-# INLINE mkPmVars #-}
1032
1033 -- | Generate a fresh `Id` of a given type
1034 mkPmId :: Type -> DsM Id
1035 mkPmId ty = getUniqueM >>= \unique ->
1036 let occname = mkVarOccFS (fsLit (show unique))
1037 name = mkInternalName unique occname noSrcSpan
1038 in return (mkLocalId name ty)
1039
1040 -- | Generate a fresh term variable of a given and return it in two forms:
1041 -- * A variable pattern
1042 -- * A variable expression
1043 mkPmId2Forms :: Type -> DsM (Pattern, LHsExpr Id)
1044 mkPmId2Forms ty = do
1045 x <- mkPmId ty
1046 return (PmVar x, noLoc (HsVar (noLoc x)))
1047
1048 -- ----------------------------------------------------------------------------
1049 -- * Converting between Value Abstractions, Patterns and PmExpr
1050
1051 -- | Convert a value abstraction an expression
1052 vaToPmExpr :: ValAbs -> PmExpr
1053 vaToPmExpr (PmCon { pm_con_con = c, pm_con_args = ps })
1054 = PmExprCon c (map vaToPmExpr ps)
1055 vaToPmExpr (PmVar { pm_var_id = x }) = PmExprVar (idName x)
1056 vaToPmExpr (PmLit { pm_lit_lit = l }) = PmExprLit l
1057 vaToPmExpr (PmNLit { pm_lit_id = x }) = PmExprVar (idName x)
1058
1059 -- | Convert a pattern vector to a list of value abstractions by dropping the
1060 -- guards (See Note [Translating As Patterns])
1061 coercePatVec :: PatVec -> [ValAbs]
1062 coercePatVec pv = concatMap coercePmPat pv
1063
1064 -- | Convert a pattern to a list of value abstractions (will be either an empty
1065 -- list if the pattern is a guard pattern, or a singleton list in all other
1066 -- cases) by dropping the guards (See Note [Translating As Patterns])
1067 coercePmPat :: Pattern -> [ValAbs]
1068 coercePmPat (PmVar { pm_var_id = x }) = [PmVar { pm_var_id = x }]
1069 coercePmPat (PmLit { pm_lit_lit = l }) = [PmLit { pm_lit_lit = l }]
1070 coercePmPat (PmCon { pm_con_con = con, pm_con_arg_tys = arg_tys
1071 , pm_con_tvs = tvs, pm_con_dicts = dicts
1072 , pm_con_args = args })
1073 = [PmCon { pm_con_con = con, pm_con_arg_tys = arg_tys
1074 , pm_con_tvs = tvs, pm_con_dicts = dicts
1075 , pm_con_args = coercePatVec args }]
1076 coercePmPat (PmGrd {}) = [] -- drop the guards
1077
1078 -- | Check whether a data constructor is the only way to construct
1079 -- a data type.
1080 singleConstructor :: ConLike -> Bool
1081 singleConstructor (RealDataCon dc) =
1082 case tyConDataCons (dataConTyCon dc) of
1083 [_] -> True
1084 _ -> False
1085 singleConstructor _ = False
1086
1087 -- | For a given conlike, finds all the sets of patterns which could
1088 -- be relevant to that conlike by consulting the result type.
1089 --
1090 -- These come from two places.
1091 -- 1. From data constructors defined with the result type constructor.
1092 -- 2. From `COMPLETE` pragmas which have the same type as the result
1093 -- type constructor.
1094 allCompleteMatches :: ConLike -> [Type] -> DsM [(Provenance, [ConLike])]
1095 allCompleteMatches cl tys = do
1096 let fam = case cl of
1097 RealDataCon dc ->
1098 [(FromBuiltin, map RealDataCon (tyConDataCons (dataConTyCon dc)))]
1099 PatSynCon _ -> []
1100
1101
1102 from_pragma <- map ((FromComplete,) . completeMatch) <$>
1103 case splitTyConApp_maybe (conLikeResTy cl tys) of
1104 Just (tc, _) -> dsGetCompleteMatches tc
1105 Nothing -> return []
1106
1107 let final_groups = fam ++ from_pragma
1108 tracePmD "allCompleteMatches" (ppr final_groups)
1109 return final_groups
1110
1111 -- -----------------------------------------------------------------------
1112 -- * Types and constraints
1113
1114 newEvVar :: Name -> Type -> EvVar
1115 newEvVar name ty = mkLocalId name (toTcType ty)
1116
1117 nameType :: String -> Type -> DsM EvVar
1118 nameType name ty = do
1119 unique <- getUniqueM
1120 let occname = mkVarOccFS (fsLit (name++"_"++show unique))
1121 idname = mkInternalName unique occname noSrcSpan
1122 return (newEvVar idname ty)
1123
1124 {-
1125 %************************************************************************
1126 %* *
1127 The type oracle
1128 %* *
1129 %************************************************************************
1130 -}
1131
1132 -- | Check whether a set of type constraints is satisfiable.
1133 tyOracle :: Bag EvVar -> PmM Bool
1134 tyOracle evs
1135 = liftD $
1136 do { ((_warns, errs), res) <- initTcDsForSolver $ tcCheckSatisfiability evs
1137 ; case res of
1138 Just sat -> return sat
1139 Nothing -> pprPanic "tyOracle" (vcat $ pprErrMsgBagWithLoc errs) }
1140
1141 {-
1142 %************************************************************************
1143 %* *
1144 Sanity Checks
1145 %* *
1146 %************************************************************************
1147 -}
1148
1149 -- | The arity of a pattern/pattern vector is the
1150 -- number of top-level patterns that are not guards
1151 type PmArity = Int
1152
1153 -- | Compute the arity of a pattern vector
1154 patVecArity :: PatVec -> PmArity
1155 patVecArity = sum . map patternArity
1156
1157 -- | Compute the arity of a pattern
1158 patternArity :: Pattern -> PmArity
1159 patternArity (PmGrd {}) = 0
1160 patternArity _other_pat = 1
1161
1162 {-
1163 %************************************************************************
1164 %* *
1165 Heart of the algorithm: Function pmcheck
1166 %* *
1167 %************************************************************************
1168
1169 Main functions are:
1170
1171 * mkInitialUncovered :: [Id] -> PmM Uncovered
1172
1173 Generates the initial uncovered set. Term and type constraints in scope
1174 are checked, if they are inconsistent, the set is empty, otherwise, the
1175 set contains only a vector of variables with the constraints in scope.
1176
1177 * pmcheck :: PatVec -> [PatVec] -> ValVec -> PmM PartialResult
1178
1179 Checks redundancy, coverage and inaccessibility, using auxilary functions
1180 `pmcheckGuards` and `pmcheckHd`. Mainly handles the guard case which is
1181 common in all three checks (see paper) and calls `pmcheckGuards` when the
1182 whole clause is checked, or `pmcheckHd` when the pattern vector does not
1183 start with a guard.
1184
1185 * pmcheckGuards :: [PatVec] -> ValVec -> PmM PartialResult
1186
1187 Processes the guards.
1188
1189 * pmcheckHd :: Pattern -> PatVec -> [PatVec]
1190 -> ValAbs -> ValVec -> PmM PartialResult
1191
1192 Worker: This function implements functions `covered`, `uncovered` and
1193 `divergent` from the paper at once. Slightly different from the paper because
1194 it does not even produce the covered and uncovered sets. Since we only care
1195 about whether a clause covers SOMETHING or if it may forces ANY argument, we
1196 only store a boolean in both cases, for efficiency.
1197 -}
1198
1199 -- | Lift a pattern matching action from a single value vector abstration to a
1200 -- value set abstraction, but calling it on every vector and the combining the
1201 -- results.
1202 runMany :: (ValVec -> PmM PartialResult) -> (Uncovered -> PmM PartialResult)
1203 runMany _ [] = return mempty
1204 runMany pm (m:ms) = mappend <$> pm m <*> runMany pm ms
1205
1206 -- | Generate the initial uncovered set. It initializes the
1207 -- delta with all term and type constraints in scope.
1208 mkInitialUncovered :: [Id] -> PmM Uncovered
1209 mkInitialUncovered vars = do
1210 ty_cs <- liftD getDictsDs
1211 tm_cs <- map toComplex . bagToList <$> liftD getTmCsDs
1212 sat_ty <- tyOracle ty_cs
1213 let initTyCs = if sat_ty then ty_cs else emptyBag
1214 initTmState = fromMaybe initialTmState (tmOracle initialTmState tm_cs)
1215 patterns = map PmVar vars
1216 -- If any of the term/type constraints are non
1217 -- satisfiable then return with the initialTmState. See #12957
1218 return [ValVec patterns (MkDelta initTyCs initTmState)]
1219
1220 -- | Increase the counter for elapsed algorithm iterations, check that the
1221 -- limit is not exceeded and call `pmcheck`
1222 pmcheckI :: PatVec -> [PatVec] -> ValVec -> PmM PartialResult
1223 pmcheckI ps guards vva = do
1224 n <- liftD incrCheckPmIterDs
1225 tracePm "pmCheck" (ppr n <> colon <+> pprPatVec ps
1226 $$ hang (text "guards:") 2 (vcat (map pprPatVec guards))
1227 $$ pprValVecDebug vva)
1228 res <- pmcheck ps guards vva
1229 tracePm "pmCheckResult:" (ppr res)
1230 return res
1231 {-# INLINE pmcheckI #-}
1232
1233 -- | Increase the counter for elapsed algorithm iterations, check that the
1234 -- limit is not exceeded and call `pmcheckGuards`
1235 pmcheckGuardsI :: [PatVec] -> ValVec -> PmM PartialResult
1236 pmcheckGuardsI gvs vva = liftD incrCheckPmIterDs >> pmcheckGuards gvs vva
1237 {-# INLINE pmcheckGuardsI #-}
1238
1239 -- | Increase the counter for elapsed algorithm iterations, check that the
1240 -- limit is not exceeded and call `pmcheckHd`
1241 pmcheckHdI :: Pattern -> PatVec -> [PatVec] -> ValAbs -> ValVec
1242 -> PmM PartialResult
1243 pmcheckHdI p ps guards va vva = do
1244 n <- liftD incrCheckPmIterDs
1245 tracePm "pmCheckHdI" (ppr n <> colon <+> pprPmPatDebug p
1246 $$ pprPatVec ps
1247 $$ hang (text "guards:") 2 (vcat (map pprPatVec guards))
1248 $$ pprPmPatDebug va
1249 $$ pprValVecDebug vva)
1250
1251 res <- pmcheckHd p ps guards va vva
1252 tracePm "pmCheckHdI: res" (ppr res)
1253 return res
1254 {-# INLINE pmcheckHdI #-}
1255
1256 -- | Matching function: Check simultaneously a clause (takes separately the
1257 -- patterns and the list of guards) for exhaustiveness, redundancy and
1258 -- inaccessibility.
1259 pmcheck :: PatVec -> [PatVec] -> ValVec -> PmM PartialResult
1260 pmcheck [] guards vva@(ValVec [] _)
1261 | null guards = return $ mempty { presultCovered = Covered }
1262 | otherwise = pmcheckGuardsI guards vva
1263
1264 -- Guard
1265 pmcheck (p@(PmGrd pv e) : ps) guards vva@(ValVec vas delta)
1266 -- short-circuit if the guard pattern is useless.
1267 -- we just have two possible outcomes: fail here or match and recurse
1268 -- none of the two contains any useful information about the failure
1269 -- though. So just have these two cases but do not do all the boilerplate
1270 | isFakeGuard pv e = forces . mkCons vva <$> pmcheckI ps guards vva
1271 | otherwise = do
1272 y <- liftD $ mkPmId (pmPatType p)
1273 let tm_state = extendSubst y e (delta_tm_cs delta)
1274 delta' = delta { delta_tm_cs = tm_state }
1275 utail <$> pmcheckI (pv ++ ps) guards (ValVec (PmVar y : vas) delta')
1276
1277 pmcheck [] _ (ValVec (_:_) _) = panic "pmcheck: nil-cons"
1278 pmcheck (_:_) _ (ValVec [] _) = panic "pmcheck: cons-nil"
1279
1280 pmcheck (p:ps) guards (ValVec (va:vva) delta)
1281 = pmcheckHdI p ps guards va (ValVec vva delta)
1282
1283 -- | Check the list of guards
1284 pmcheckGuards :: [PatVec] -> ValVec -> PmM PartialResult
1285 pmcheckGuards [] vva = return (usimple [vva])
1286 pmcheckGuards (gv:gvs) vva = do
1287 (PartialResult prov1 cs vsa ds) <- pmcheckI gv [] vva
1288 (PartialResult prov2 css vsas dss) <- runMany (pmcheckGuardsI gvs) vsa
1289 return $ PartialResult (prov1 `mappend` prov2)
1290 (cs `mappend` css)
1291 vsas
1292 (ds `mappend` dss)
1293
1294 -- | Worker function: Implements all cases described in the paper for all three
1295 -- functions (`covered`, `uncovered` and `divergent`) apart from the `Guard`
1296 -- cases which are handled by `pmcheck`
1297 pmcheckHd :: Pattern -> PatVec -> [PatVec] -> ValAbs -> ValVec
1298 -> PmM PartialResult
1299
1300 -- Var
1301 pmcheckHd (PmVar x) ps guards va (ValVec vva delta)
1302 | Just tm_state <- solveOneEq (delta_tm_cs delta)
1303 (PmExprVar (idName x), vaToPmExpr va)
1304 = ucon va <$> pmcheckI ps guards (ValVec vva (delta {delta_tm_cs = tm_state}))
1305 | otherwise = return mempty
1306
1307 -- ConCon
1308 pmcheckHd ( p@(PmCon {pm_con_con = c1, pm_con_args = args1})) ps guards
1309 (va@(PmCon {pm_con_con = c2, pm_con_args = args2})) (ValVec vva delta)
1310 | c1 /= c2 =
1311 return (usimple [ValVec (va:vva) delta])
1312 | otherwise = kcon c1 (pm_con_arg_tys p) (pm_con_tvs p) (pm_con_dicts p)
1313 <$> pmcheckI (args1 ++ ps) guards (ValVec (args2 ++ vva) delta)
1314
1315 -- LitLit
1316 pmcheckHd (PmLit l1) ps guards (va@(PmLit l2)) vva =
1317 case eqPmLit l1 l2 of
1318 True -> ucon va <$> pmcheckI ps guards vva
1319 False -> return $ ucon va (usimple [vva])
1320
1321 -- ConVar
1322 pmcheckHd (p@(PmCon { pm_con_con = con, pm_con_arg_tys = tys }))
1323 ps guards
1324 (PmVar x) (ValVec vva delta) = do
1325 (prov, complete_match) <- select =<< liftD (allCompleteMatches con tys)
1326
1327 cons_cs <- mapM (liftD . mkOneConFull x) complete_match
1328
1329 inst_vsa <- flip concatMapM cons_cs $ \(va, tm_ct, ty_cs) -> do
1330 let ty_state = ty_cs `unionBags` delta_ty_cs delta -- not actually a state
1331 sat_ty <- if isEmptyBag ty_cs then return True
1332 else tyOracle ty_state
1333 return $ case (sat_ty, solveOneEq (delta_tm_cs delta) tm_ct) of
1334 (True, Just tm_state) -> [ValVec (va:vva) (MkDelta ty_state tm_state)]
1335 _ty_or_tm_failed -> []
1336
1337 set_provenance prov .
1338 force_if (canDiverge (idName x) (delta_tm_cs delta)) <$>
1339 runMany (pmcheckI (p:ps) guards) inst_vsa
1340
1341 -- LitVar
1342 pmcheckHd (p@(PmLit l)) ps guards (PmVar x) (ValVec vva delta)
1343 = force_if (canDiverge (idName x) (delta_tm_cs delta)) <$>
1344 mkUnion non_matched <$>
1345 case solveOneEq (delta_tm_cs delta) (mkPosEq x l) of
1346 Just tm_state -> pmcheckHdI p ps guards (PmLit l) $
1347 ValVec vva (delta {delta_tm_cs = tm_state})
1348 Nothing -> return mempty
1349 where
1350 us | Just tm_state <- solveOneEq (delta_tm_cs delta) (mkNegEq x l)
1351 = [ValVec (PmNLit x [l] : vva) (delta { delta_tm_cs = tm_state })]
1352 | otherwise = []
1353
1354 non_matched = usimple us
1355
1356 -- LitNLit
1357 pmcheckHd (p@(PmLit l)) ps guards
1358 (PmNLit { pm_lit_id = x, pm_lit_not = lits }) (ValVec vva delta)
1359 | all (not . eqPmLit l) lits
1360 , Just tm_state <- solveOneEq (delta_tm_cs delta) (mkPosEq x l)
1361 -- Both guards check the same so it would be sufficient to have only
1362 -- the second one. Nevertheless, it is much cheaper to check whether
1363 -- the literal is in the list so we check it first, to avoid calling
1364 -- the term oracle (`solveOneEq`) if possible
1365 = mkUnion non_matched <$>
1366 pmcheckHdI p ps guards (PmLit l)
1367 (ValVec vva (delta { delta_tm_cs = tm_state }))
1368 | otherwise = return non_matched
1369 where
1370 us | Just tm_state <- solveOneEq (delta_tm_cs delta) (mkNegEq x l)
1371 = [ValVec (PmNLit x (l:lits) : vva) (delta { delta_tm_cs = tm_state })]
1372 | otherwise = []
1373
1374 non_matched = usimple us
1375
1376 -- ----------------------------------------------------------------------------
1377 -- The following three can happen only in cases like #322 where constructors
1378 -- and overloaded literals appear in the same match. The general strategy is
1379 -- to replace the literal (positive/negative) by a variable and recurse. The
1380 -- fact that the variable is equal to the literal is recorded in `delta` so
1381 -- no information is lost
1382
1383 -- LitCon
1384 pmcheckHd (PmLit l) ps guards (va@(PmCon {})) (ValVec vva delta)
1385 = do y <- liftD $ mkPmId (pmPatType va)
1386 let tm_state = extendSubst y (PmExprLit l) (delta_tm_cs delta)
1387 delta' = delta { delta_tm_cs = tm_state }
1388 pmcheckHdI (PmVar y) ps guards va (ValVec vva delta')
1389
1390 -- ConLit
1391 pmcheckHd (p@(PmCon {})) ps guards (PmLit l) (ValVec vva delta)
1392 = do y <- liftD $ mkPmId (pmPatType p)
1393 let tm_state = extendSubst y (PmExprLit l) (delta_tm_cs delta)
1394 delta' = delta { delta_tm_cs = tm_state }
1395 pmcheckHdI p ps guards (PmVar y) (ValVec vva delta')
1396
1397 -- ConNLit
1398 pmcheckHd (p@(PmCon {})) ps guards (PmNLit { pm_lit_id = x }) vva
1399 = pmcheckHdI p ps guards (PmVar x) vva
1400
1401 -- Impossible: handled by pmcheck
1402 pmcheckHd (PmGrd {}) _ _ _ _ = panic "pmcheckHd: Guard"
1403
1404 -- ----------------------------------------------------------------------------
1405 -- * Utilities for main checking
1406
1407 updateVsa :: (ValSetAbs -> ValSetAbs) -> (PartialResult -> PartialResult)
1408 updateVsa f p@(PartialResult { presultUncovered = old })
1409 = p { presultUncovered = f old }
1410
1411
1412 -- | Initialise with default values for covering and divergent information.
1413 usimple :: ValSetAbs -> PartialResult
1414 usimple vsa = mempty { presultUncovered = vsa }
1415
1416 -- | Take the tail of all value vector abstractions in the uncovered set
1417 utail :: PartialResult -> PartialResult
1418 utail = updateVsa upd
1419 where upd vsa = [ ValVec vva delta | ValVec (_:vva) delta <- vsa ]
1420
1421 -- | Prepend a value abstraction to all value vector abstractions in the
1422 -- uncovered set
1423 ucon :: ValAbs -> PartialResult -> PartialResult
1424 ucon va = updateVsa upd
1425 where
1426 upd vsa = [ ValVec (va:vva) delta | ValVec vva delta <- vsa ]
1427
1428 -- | Given a data constructor of arity `a` and an uncovered set containing
1429 -- value vector abstractions of length `(a+n)`, pass the first `n` value
1430 -- abstractions to the constructor (Hence, the resulting value vector
1431 -- abstractions will have length `n+1`)
1432 kcon :: ConLike -> [Type] -> [TyVar] -> [EvVar]
1433 -> PartialResult -> PartialResult
1434 kcon con arg_tys ex_tvs dicts
1435 = let n = conLikeArity con
1436 upd vsa =
1437 [ ValVec (va:vva) delta
1438 | ValVec vva' delta <- vsa
1439 , let (args, vva) = splitAt n vva'
1440 , let va = PmCon { pm_con_con = con
1441 , pm_con_arg_tys = arg_tys
1442 , pm_con_tvs = ex_tvs
1443 , pm_con_dicts = dicts
1444 , pm_con_args = args } ]
1445 in updateVsa upd
1446
1447 -- | Get the union of two covered, uncovered and divergent value set
1448 -- abstractions. Since the covered and divergent sets are represented by a
1449 -- boolean, union means computing the logical or (at least one of the two is
1450 -- non-empty).
1451
1452 mkUnion :: PartialResult -> PartialResult -> PartialResult
1453 mkUnion = mappend
1454
1455 -- | Add a value vector abstraction to a value set abstraction (uncovered).
1456 mkCons :: ValVec -> PartialResult -> PartialResult
1457 mkCons vva = updateVsa (vva:)
1458
1459 -- | Set the divergent set to not empty
1460 forces :: PartialResult -> PartialResult
1461 forces pres = pres { presultDivergent = Diverged }
1462
1463 -- | Set the divergent set to non-empty if the flag is `True`
1464 force_if :: Bool -> PartialResult -> PartialResult
1465 force_if True pres = forces pres
1466 force_if False pres = pres
1467
1468 set_provenance :: Provenance -> PartialResult -> PartialResult
1469 set_provenance prov pr = pr { presultProvenence = prov }
1470
1471 -- ----------------------------------------------------------------------------
1472 -- * Propagation of term constraints inwards when checking nested matches
1473
1474 {- Note [Type and Term Equality Propagation]
1475 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1476 When checking a match it would be great to have all type and term information
1477 available so we can get more precise results. For this reason we have functions
1478 `addDictsDs' and `addTmCsDs' in PmMonad that store in the environment type and
1479 term constraints (respectively) as we go deeper.
1480
1481 The type constraints we propagate inwards are collected by `collectEvVarsPats'
1482 in HsPat.hs. This handles bug #4139 ( see example
1483 https://ghc.haskell.org/trac/ghc/attachment/ticket/4139/GADTbug.hs )
1484 where this is needed.
1485
1486 For term equalities we do less, we just generate equalities for HsCase. For
1487 example we accurately give 2 redundancy warnings for the marked cases:
1488
1489 f :: [a] -> Bool
1490 f x = case x of
1491
1492 [] -> case x of -- brings (x ~ []) in scope
1493 [] -> True
1494 (_:_) -> False -- can't happen
1495
1496 (_:_) -> case x of -- brings (x ~ (_:_)) in scope
1497 (_:_) -> True
1498 [] -> False -- can't happen
1499
1500 Functions `genCaseTmCs1' and `genCaseTmCs2' are responsible for generating
1501 these constraints.
1502 -}
1503
1504 -- | Generate equalities when checking a case expression:
1505 -- case x of { p1 -> e1; ... pn -> en }
1506 -- When we go deeper to check e.g. e1 we record two equalities:
1507 -- (x ~ y), where y is the initial uncovered when checking (p1; .. ; pn)
1508 -- and (x ~ p1).
1509 genCaseTmCs2 :: Maybe (LHsExpr Id) -- Scrutinee
1510 -> [Pat Id] -- LHS (should have length 1)
1511 -> [Id] -- MatchVars (should have length 1)
1512 -> DsM (Bag SimpleEq)
1513 genCaseTmCs2 Nothing _ _ = return emptyBag
1514 genCaseTmCs2 (Just scr) [p] [var] = do
1515 fam_insts <- dsGetFamInstEnvs
1516 [e] <- map vaToPmExpr . coercePatVec <$> translatePat fam_insts p
1517 let scr_e = lhsExprToPmExpr scr
1518 return $ listToBag [(var, e), (var, scr_e)]
1519 genCaseTmCs2 _ _ _ = panic "genCaseTmCs2: HsCase"
1520
1521 -- | Generate a simple equality when checking a case expression:
1522 -- case x of { matches }
1523 -- When checking matches we record that (x ~ y) where y is the initial
1524 -- uncovered. All matches will have to satisfy this equality.
1525 genCaseTmCs1 :: Maybe (LHsExpr Id) -> [Id] -> Bag SimpleEq
1526 genCaseTmCs1 Nothing _ = emptyBag
1527 genCaseTmCs1 (Just scr) [var] = unitBag (var, lhsExprToPmExpr scr)
1528 genCaseTmCs1 _ _ = panic "genCaseTmCs1: HsCase"
1529
1530 {- Note [Literals in PmPat]
1531 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1532 Instead of translating a literal to a variable accompanied with a guard, we
1533 treat them like constructor patterns. The following example from
1534 "./libraries/base/GHC/IO/Encoding.hs" shows why:
1535
1536 mkTextEncoding' :: CodingFailureMode -> String -> IO TextEncoding
1537 mkTextEncoding' cfm enc = case [toUpper c | c <- enc, c /= '-'] of
1538 "UTF8" -> return $ UTF8.mkUTF8 cfm
1539 "UTF16" -> return $ UTF16.mkUTF16 cfm
1540 "UTF16LE" -> return $ UTF16.mkUTF16le cfm
1541 ...
1542
1543 Each clause gets translated to a list of variables with an equal number of
1544 guards. For every guard we generate two cases (equals True/equals False) which
1545 means that we generate 2^n cases to feed the oracle with, where n is the sum of
1546 the length of all strings that appear in the patterns. For this particular
1547 example this means over 2^40 cases. Instead, by representing them like with
1548 constructor we get the following:
1549 1. We exploit the common prefix with our representation of VSAs
1550 2. We prune immediately non-reachable cases
1551 (e.g. False == (x == "U"), True == (x == "U"))
1552
1553 Note [Translating As Patterns]
1554 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1555 Instead of translating x@p as: x (p <- x)
1556 we instead translate it as: p (x <- coercePattern p)
1557 for performance reasons. For example:
1558
1559 f x@True = 1
1560 f y@False = 2
1561
1562 Gives the following with the first translation:
1563
1564 x |> {x == False, x == y, y == True}
1565
1566 If we use the second translation we get an empty set, independently of the
1567 oracle. Since the pattern `p' may contain guard patterns though, it cannot be
1568 used as an expression. That's why we call `coercePatVec' to drop the guard and
1569 `vaToPmExpr' to transform the value abstraction to an expression in the
1570 guard pattern (value abstractions are a subset of expressions). We keep the
1571 guards in the first pattern `p' though.
1572
1573
1574 %************************************************************************
1575 %* *
1576 Pretty printing of exhaustiveness/redundancy check warnings
1577 %* *
1578 %************************************************************************
1579 -}
1580
1581 -- | Check whether any part of pattern match checking is enabled (does not
1582 -- matter whether it is the redundancy check or the exhaustiveness check).
1583 isAnyPmCheckEnabled :: DynFlags -> DsMatchContext -> Bool
1584 isAnyPmCheckEnabled dflags (DsMatchContext kind _loc)
1585 = wopt Opt_WarnOverlappingPatterns dflags || exhaustive dflags kind
1586
1587 instance Outputable ValVec where
1588 ppr (ValVec vva delta)
1589 = let (residual_eqs, subst) = wrapUpTmState (delta_tm_cs delta)
1590 vector = substInValAbs subst vva
1591 in ppr_uncovered (vector, residual_eqs)
1592
1593 -- | Apply a term substitution to a value vector abstraction. All VAs are
1594 -- transformed to PmExpr (used only before pretty printing).
1595 substInValAbs :: PmVarEnv -> [ValAbs] -> [PmExpr]
1596 substInValAbs subst = map (exprDeepLookup subst . vaToPmExpr)
1597
1598 -- | Wrap up the term oracle's state once solving is complete. Drop any
1599 -- information about unhandled constraints (involving HsExprs) and flatten
1600 -- (height 1) the substitution.
1601 wrapUpTmState :: TmState -> ([ComplexEq], PmVarEnv)
1602 wrapUpTmState (residual, (_, subst)) = (residual, flattenPmVarEnv subst)
1603
1604 -- | Issue all the warnings (coverage, exhaustiveness, inaccessibility)
1605 dsPmWarn :: DynFlags -> DsMatchContext -> PmResult -> DsM ()
1606 dsPmWarn dflags ctx@(DsMatchContext kind loc) pm_result
1607 = when (flag_i || flag_u) $ do
1608 let exists_r = flag_i && notNull redundant && onlyBuiltin
1609 exists_i = flag_i && notNull inaccessible && onlyBuiltin
1610 exists_u = flag_u && (case uncovered of
1611 TypeOfUncovered _ -> True
1612 UncoveredPatterns u -> notNull u)
1613
1614 when exists_r $ forM_ redundant $ \(L l q) -> do
1615 putSrcSpanDs l (warnDs (Reason Opt_WarnOverlappingPatterns)
1616 (pprEqn q "is redundant"))
1617 when exists_i $ forM_ inaccessible $ \(L l q) -> do
1618 putSrcSpanDs l (warnDs (Reason Opt_WarnOverlappingPatterns)
1619 (pprEqn q "has inaccessible right hand side"))
1620 when exists_u $ putSrcSpanDs loc $ warnDs flag_u_reason $
1621 case uncovered of
1622 TypeOfUncovered ty -> warnEmptyCase ty
1623 UncoveredPatterns candidates -> pprEqns candidates
1624 where
1625 PmResult
1626 { pmresultProvenance = prov
1627 , pmresultRedundant = redundant
1628 , pmresultUncovered = uncovered
1629 , pmresultInaccessible = inaccessible } = pm_result
1630
1631 flag_i = wopt Opt_WarnOverlappingPatterns dflags
1632 flag_u = exhaustive dflags kind
1633 flag_u_reason = maybe NoReason Reason (exhaustiveWarningFlag kind)
1634
1635 onlyBuiltin = prov == FromBuiltin
1636
1637 maxPatterns = maxUncoveredPatterns dflags
1638
1639 -- Print a single clause (for redundant/with-inaccessible-rhs)
1640 pprEqn q txt = pp_context True ctx (text txt) $ \f -> ppr_eqn f kind q
1641
1642 -- Print several clauses (for uncovered clauses)
1643 pprEqns qs = pp_context False ctx (text "are non-exhaustive") $ \_ ->
1644 case qs of -- See #11245
1645 [ValVec [] _]
1646 -> text "Guards do not cover entire pattern space"
1647 _missing -> let us = map ppr qs
1648 in hang (text "Patterns not matched:") 4
1649 (vcat (take maxPatterns us)
1650 $$ dots maxPatterns us)
1651
1652 -- Print a type-annotated wildcard (for non-exhaustive `EmptyCase`s for
1653 -- which we only know the type and have no inhabitants at hand)
1654 warnEmptyCase ty = pp_context False ctx (text "are non-exhaustive") $ \_ ->
1655 hang (text "Patterns not matched:") 4 (underscore <+> dcolon <+> ppr ty)
1656
1657 -- | Issue a warning when the predefined number of iterations is exceeded
1658 -- for the pattern match checker
1659 warnPmIters :: DynFlags -> DsMatchContext -> DsM ()
1660 warnPmIters dflags (DsMatchContext kind loc)
1661 = when (flag_i || flag_u) $ do
1662 iters <- maxPmCheckIterations <$> getDynFlags
1663 putSrcSpanDs loc (warnDs NoReason (msg iters))
1664 where
1665 ctxt = pprMatchContext kind
1666 msg is = fsep [ text "Pattern match checker exceeded"
1667 , parens (ppr is), text "iterations in", ctxt <> dot
1668 , text "(Use -fmax-pmcheck-iterations=n"
1669 , text "to set the maximun number of iterations to n)" ]
1670
1671 flag_i = wopt Opt_WarnOverlappingPatterns dflags
1672 flag_u = exhaustive dflags kind
1673
1674 dots :: Int -> [a] -> SDoc
1675 dots maxPatterns qs
1676 | qs `lengthExceeds` maxPatterns = text "..."
1677 | otherwise = empty
1678
1679 -- | Check whether the exhaustiveness checker should run (exhaustiveness only)
1680 exhaustive :: DynFlags -> HsMatchContext id -> Bool
1681 exhaustive dflags = maybe False (`wopt` dflags) . exhaustiveWarningFlag
1682
1683 -- | Denotes whether an exhaustiveness check is supported, and if so,
1684 -- via which 'WarningFlag' it's controlled.
1685 -- Returns 'Nothing' if check is not supported.
1686 exhaustiveWarningFlag :: HsMatchContext id -> Maybe WarningFlag
1687 exhaustiveWarningFlag (FunRhs {}) = Just Opt_WarnIncompletePatterns
1688 exhaustiveWarningFlag CaseAlt = Just Opt_WarnIncompletePatterns
1689 exhaustiveWarningFlag IfAlt = Nothing
1690 exhaustiveWarningFlag LambdaExpr = Just Opt_WarnIncompleteUniPatterns
1691 exhaustiveWarningFlag PatBindRhs = Just Opt_WarnIncompleteUniPatterns
1692 exhaustiveWarningFlag ProcExpr = Just Opt_WarnIncompleteUniPatterns
1693 exhaustiveWarningFlag RecUpd = Just Opt_WarnIncompletePatternsRecUpd
1694 exhaustiveWarningFlag ThPatSplice = Nothing
1695 exhaustiveWarningFlag PatSyn = Nothing
1696 exhaustiveWarningFlag ThPatQuote = Nothing
1697 exhaustiveWarningFlag (StmtCtxt {}) = Nothing -- Don't warn about incomplete patterns
1698 -- in list comprehensions, pattern guards
1699 -- etc. They are often *supposed* to be
1700 -- incomplete
1701
1702 -- True <==> singular
1703 pp_context :: Bool -> DsMatchContext -> SDoc -> ((SDoc -> SDoc) -> SDoc) -> SDoc
1704 pp_context singular (DsMatchContext kind _loc) msg rest_of_msg_fun
1705 = vcat [text txt <+> msg,
1706 sep [ text "In" <+> ppr_match <> char ':'
1707 , nest 4 (rest_of_msg_fun pref)]]
1708 where
1709 txt | singular = "Pattern match"
1710 | otherwise = "Pattern match(es)"
1711
1712 (ppr_match, pref)
1713 = case kind of
1714 FunRhs (L _ fun) _ -> (pprMatchContext kind,
1715 \ pp -> ppr fun <+> pp)
1716 _ -> (pprMatchContext kind, \ pp -> pp)
1717
1718 ppr_pats :: HsMatchContext Name -> [Pat Id] -> SDoc
1719 ppr_pats kind pats
1720 = sep [sep (map ppr pats), matchSeparator kind, text "..."]
1721
1722 ppr_eqn :: (SDoc -> SDoc) -> HsMatchContext Name -> [LPat Id] -> SDoc
1723 ppr_eqn prefixF kind eqn = prefixF (ppr_pats kind (map unLoc eqn))
1724
1725 ppr_constraint :: (SDoc,[PmLit]) -> SDoc
1726 ppr_constraint (var, lits) = var <+> text "is not one of"
1727 <+> braces (pprWithCommas ppr lits)
1728
1729 ppr_uncovered :: ([PmExpr], [ComplexEq]) -> SDoc
1730 ppr_uncovered (expr_vec, complex)
1731 | null cs = fsep vec -- there are no literal constraints
1732 | otherwise = hang (fsep vec) 4 $
1733 text "where" <+> vcat (map ppr_constraint cs)
1734 where
1735 sdoc_vec = mapM pprPmExprWithParens expr_vec
1736 (vec,cs) = runPmPprM sdoc_vec (filterComplex complex)
1737
1738 {- Note [Representation of Term Equalities]
1739 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1740 In the paper, term constraints always take the form (x ~ e). Of course, a more
1741 general constraint of the form (e1 ~ e1) can always be transformed to an
1742 equivalent set of the former constraints, by introducing a fresh, intermediate
1743 variable: { y ~ e1, y ~ e1 }. Yet, implementing this representation gave rise
1744 to #11160 (incredibly bad performance for literal pattern matching). Two are
1745 the main sources of this problem (the actual problem is how these two interact
1746 with each other):
1747
1748 1. Pattern matching on literals generates twice as many constraints as needed.
1749 Consider the following (tests/ghci/should_run/ghcirun004):
1750
1751 foo :: Int -> Int
1752 foo 1 = 0
1753 ...
1754 foo 5000 = 4999
1755
1756 The covered and uncovered set *should* look like:
1757 U0 = { x |> {} }
1758
1759 C1 = { 1 |> { x ~ 1 } }
1760 U1 = { x |> { False ~ (x ~ 1) } }
1761 ...
1762 C10 = { 10 |> { False ~ (x ~ 1), .., False ~ (x ~ 9), x ~ 10 } }
1763 U10 = { x |> { False ~ (x ~ 1), .., False ~ (x ~ 9), False ~ (x ~ 10) } }
1764 ...
1765
1766 If we replace { False ~ (x ~ 1) } with { y ~ False, y ~ (x ~ 1) }
1767 we get twice as many constraints. Also note that half of them are just the
1768 substitution [x |-> False].
1769
1770 2. The term oracle (`tmOracle` in deSugar/TmOracle) uses equalities of the form
1771 (x ~ e) as substitutions [x |-> e]. More specifically, function
1772 `extendSubstAndSolve` applies such substitutions in the residual constraints
1773 and partitions them in the affected and non-affected ones, which are the new
1774 worklist. Essentially, this gives quadradic behaviour on the number of the
1775 residual constraints. (This would not be the case if the term oracle used
1776 mutable variables but, since we use it to handle disjunctions on value set
1777 abstractions (`Union` case), we chose a pure, incremental interface).
1778
1779 Now the problem becomes apparent (e.g. for clause 300):
1780 * Set U300 contains 300 substituting constraints [y_i |-> False] and 300
1781 constraints that we know that will not reduce (stay in the worklist).
1782 * To check for consistency, we apply the substituting constraints ONE BY ONE
1783 (since `tmOracle` is called incrementally, it does not have all of them
1784 available at once). Hence, we go through the (non-progressing) constraints
1785 over and over, achieving over-quadradic behaviour.
1786
1787 If instead we allow constraints of the form (e ~ e),
1788 * All uncovered sets Ui contain no substituting constraints and i
1789 non-progressing constraints of the form (False ~ (x ~ lit)) so the oracle
1790 behaves linearly.
1791 * All covered sets Ci contain exactly (i-1) non-progressing constraints and
1792 a single substituting constraint. So the term oracle goes through the
1793 constraints only once.
1794
1795 The performance improvement becomes even more important when more arguments are
1796 involved.
1797 -}
1798
1799 -- Debugging Infrastructre
1800
1801 tracePm :: String -> SDoc -> PmM ()
1802 tracePm herald doc = liftD $ tracePmD herald doc
1803
1804
1805 tracePmD :: String -> SDoc -> DsM ()
1806 tracePmD herald doc = do
1807 dflags <- getDynFlags
1808 printer <- mkPrintUnqualifiedDs
1809 liftIO $ dumpIfSet_dyn_printer printer dflags
1810 Opt_D_dump_ec_trace (text herald $$ (nest 2 doc))
1811
1812
1813 pprPmPatDebug :: PmPat a -> SDoc
1814 pprPmPatDebug (PmCon cc _arg_tys _con_tvs _con_dicts con_args)
1815 = hsep [text "PmCon", ppr cc, hsep (map pprPmPatDebug con_args)]
1816 pprPmPatDebug (PmVar vid) = text "PmVar" <+> ppr vid
1817 pprPmPatDebug (PmLit li) = text "PmLit" <+> ppr li
1818 pprPmPatDebug (PmNLit i nl) = text "PmNLit" <+> ppr i <+> ppr nl
1819 pprPmPatDebug (PmGrd pv ge) = text "PmGrd" <+> hsep (map pprPmPatDebug pv)
1820 <+> ppr ge
1821
1822 pprPatVec :: PatVec -> SDoc
1823 pprPatVec ps = hang (text "Pattern:") 2
1824 (brackets $ sep
1825 $ punctuate (comma <> char '\n') (map pprPmPatDebug ps))
1826
1827 pprValAbs :: [ValAbs] -> SDoc
1828 pprValAbs ps = hang (text "ValAbs:") 2
1829 (brackets $ sep
1830 $ punctuate (comma) (map pprPmPatDebug ps))
1831
1832 pprValVecDebug :: ValVec -> SDoc
1833 pprValVecDebug (ValVec vas _d) = text "ValVec" <+>
1834 parens (pprValAbs vas)