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