[Git][ghc/ghc][wip/T28014] Pmc: Make pattern synonym matches lazy
Sebastian Graf pushed to branch wip/T28014 at Glasgow Haskell Compiler / GHC Commits: 53f8ee02 by Sebastian Graf at 2026-11-22T18:31:42+01:00 Pmc: Make pattern synonym matches lazy A match on a pattern synonym no longer implies that the scrutinee is not bottom. The scrutinee is not bottom only when it failed to match a member of an applicable COMPLETE pragma and no member of that pragma can match it. Fixes #28014 and #17357. - - - - - 10 changed files: - + changelog.d/28014 - compiler/GHC/HsToCore/Pmc/Check.hs - compiler/GHC/HsToCore/Pmc/Solver.hs - compiler/GHC/HsToCore/Pmc/Solver/Types.hs - testsuite/tests/pmcheck/should_compile/T17357.stderr - + testsuite/tests/pmcheck/should_compile/T28014.hs - + testsuite/tests/pmcheck/should_compile/T28014.stderr - + testsuite/tests/pmcheck/should_compile/T28014b.hs - + testsuite/tests/pmcheck/should_compile/T28014b.stderr - testsuite/tests/pmcheck/should_compile/all.T Changes: ===================================== changelog.d/28014 ===================================== @@ -0,0 +1,14 @@ +section: compiler +synopsis: The pattern-match checker no longer assumes that pattern synonym matches force their argument +description: + A match on a pattern synonym excludes ⊥ as a value of the scrutinee only + through a ``COMPLETE`` set: when every member that can match at the type of + the scrutinee failed to match, and that type has a value other than ⊥. + Hence ``-Wredundant-bang-patterns`` and ``-Woverlapping-patterns`` no longer + report bangs or clauses as redundant or inaccessible when deleting them + would change the semantics, and ``-Wincomplete-patterns`` reports matches + that fail on ⊥ fields that a pattern synonym does not force. Redundancy that + rests on the strictness of a pattern synonym outside of an exhausted + ``COMPLETE`` set is no longer reported. +issues: #28014 #17357 +mrs: !17033 ===================================== compiler/GHC/HsToCore/Pmc/Check.hs ===================================== @@ -144,7 +144,7 @@ checkGrd grd = CA $ \inc -> case grd of , cr_approx = Precise } -- Con: Fall through on x ≁ K and refine with x ~ K ys and type info PmCon x con tvs dicts args -> do - !div <- if isPmAltConMatchStrict con + !div <- if pmAltConMatchMayDiverge con then addPhiCtNablas inc (PhiBotCt x) else pure mempty !matched <- addPhiCtNablas inc (PhiConCt x con tvs (map evVarPred dicts) args) ===================================== compiler/GHC/HsToCore/Pmc/Solver.hs ===================================== @@ -547,6 +547,116 @@ clause as redundant, which clearly is unsound. The solution: 3. Immediately reject when we find @x ≁ T2@. Handling of Newtypes is also described in the Appendix of the Lower Your Guards paper, where you can find the solution in a perhaps more digestible format. + +Note [Strictness of pattern synonym matches] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +TODO(sgraf): formulate. Points: + +* A match on a data constructor K forces x, so both x ~ K and x ≁ K imply + x ≁ ⊥. A match on a pattern synonym P need not force x (#28014, #17357): + + pattern F :: a + pattern F <- (const False -> True) + + withBang :: Bool -> Int + withBang F = 1 + withBang !_ = 2 -- Bang not redundant: withBang undefined is ⊥, + -- but 2 without the bang + + So neither x ~ P nor x ≁ P implies x ≁ ⊥ ('isPmAltConMatchStrict'). + +* A match on P may still diverge on ⊥, so the divergent set gets x ~ ⊥ + ('pmAltConMatchMayDiverge'). Example from #17357: + + strictConst :: a -> b -> a + strictConst a b = seq b a + pattern SF <- (strictConst False -> True) + + f2 :: Bool -> Bool -> () + f2 _ True = () + f2 SF True = () -- Inaccessible RHS, not redundant + f2 !_ True = () + f2 _ _ = () + +* Rule. Let C be a COMPLETE set from a pragma that applies at the type τ + of x. If x failed to match a member of C, and no member of C can match x, + then x ≁ ⊥. A member P cannot match x when x failed to match P, or when the + provided constraints of P contradict τ. The pragma asserts that matching + any value of τ, ⊥ included, against the members of C succeeds or diverges. + x ≁ ⊥ is a fact, so redundancy and coverage both use it. + +* Type constraints alone leave ⊥. Here no member of C = {G1, G2} (below) + can match at G Char, and x failed to match only F: + + data U = MkU (G Char) + hc :: U -> Int + hc (MkU F) = 1 -- Not matched: MkU _ + +* Matcher lemma, for the pragma assertion at a τ with a non-⊥ value. + $mP :: forall r. τ -> (args -> r) -> (Void# -> r) -> r. + By parametricity, $mP v k e ∈ {⊥, k args, e (##)}. By monotonicity in v, + if P fails on ⊥ without diverging, P fails on every value. + A non-⊥ value v of τ matches some member P of C. If P failed on ⊥ + without diverging, P fails on v. Contradiction. + +* The vanilla COMPLETE set of a data type needs no rule. A failed match on a + data constructor gives x ≁ ⊥ already. If no data constructor failed but + the set has no inhabitant, τ has no data constructor, and ⊥ stays: + + data T = MkT Void + h :: T -> Int + h (MkT F) = 1 -- Not matched: MkT _. Indeed h (MkT undefined) fails. + +* Implementation in the inhabitation test ('instantiate'). A residual + COMPLETE set from a pragma that lost a member witnesses a failed match on + that member ('matchedPragmaSets'). This covers synonyms with a required + theta, which are not in 'vi_neg' + (Note [Completeness checking with required Thetas]). + - Without such a set, offer ⊥ first, as before. + - Otherwise, search the residual COMPLETE sets for a non-⊥ inhabitant + ('instCompleteSets'). If there is none, offer ⊥ when each of these sets + has an inhabitant ('allInhabited'). + The order is only a matter of performance + (Note [Shortcutting the inhabitation test]). + 'generateInhabitingPatterns' decides on a wildcard the same way. + Wrinkle: 'instCompleteSet' also removes a member that cannot match at the + type of x at the time of the test. A later type refinement that rules out + the remaining members then rules out ⊥ as well. + +* Example: every member failed. + + pattern Nil :: [a] + pattern Nil <- (null -> True) + pattern Cons :: a -> [a] -> [a] + pattern Cons x xs <- (uncons -> Just (x, xs)) + {-# COMPLETE Nil, Cons #-} + + g :: [a] -> Int + g Nil = 0 + g (Cons _ _) = 1 -- Exhaustive + g _ = 2 -- Redundant + +* Example: members that cannot match at τ. + + data G a where { G1' :: G Int; G2' :: G Bool } + pattern G1 :: () => (a ~ Int) => G a + pattern G1 = G1' + pattern G2 :: () => (a ~ Bool) => G a + pattern G2 = G2' + {-# COMPLETE G1, G2 #-} + + fb :: G Int -> Int + fb G1 = 1 -- Exhaustive: G2 cannot match at G Int + +* Precision loss: redundancy that rests on the strictness of P outside an + exhausted COMPLETE set is not reported. + + pattern J :: a -> Maybe a + pattern J x = Just x + + k :: Maybe Int -> Int + k (J _) = 1 + k !_ = 2 -- Bang is dead, but not reported -} ------------------------- @@ -729,7 +839,7 @@ addNotConCt nabla x nalt = do -- otherwise return updated entry and `Just x'` if `x` should be marked dirty, -- where `x'` is the representative of `x`. go :: VarInfo -> MaybeT DsM (Maybe Id, VarInfo) - go vi@(VI x' pos neg _ rcm) = do + go vi@(VI x' pos neg bot rcm) = do -- 1. Bail out quickly when nalt contradicts a solution let contradicts nalt sol = eqPmAltCon (paca_con sol) nalt == Equal guard (not (any (contradicts nalt) pos)) @@ -741,8 +851,10 @@ addNotConCt nabla x nalt = do -- See Note [Completeness checking with required Thetas] | hasRequiredTheta nalt = neg | otherwise = extendPmAltConSet neg nalt - massert (isPmAltConMatchStrict nalt) - let vi' = vi{ vi_neg = neg', vi_bot = IsNotBot } + -- See Note [Strictness of pattern synonym matches] + let bot' | isPmAltConMatchStrict nalt = IsNotBot + | otherwise = bot + let vi' = vi{ vi_neg = neg', vi_bot = bot' } -- 3. Make sure there's at least one other possible constructor mb_rcm' <- lift (markMatched nalt rcm) pure $ case mb_rcm' of @@ -796,8 +908,9 @@ addConCt nabla@MkNabla{ nabla_tm_st = ts@TmSt{ ts_facts=env } } x alt tvs args = MaybeBot -> pure (nabla_with MaybeBot) IsBot -> addBotCt (nabla_with MaybeBot) y IsNotBot -> addNotBotCt (nabla_with MaybeBot) y - _ -> assert (isPmAltConMatchStrict alt ) - pure (nabla_with IsNotBot) -- strict match ==> not ⊥ + _ | isPmAltConMatchStrict alt -> pure (nabla_with IsNotBot) -- strict match ==> not ⊥ + -- See Note [Strictness of pattern synonym matches] + | otherwise -> pure (nabla_with bot) equateTys :: [Type] -> [Type] -> [PhiCt] equateTys ts us = @@ -1372,8 +1485,31 @@ varNeedsTesting old_ty_st MkNabla{nabla_ty_st=new_ty_st} vi = do -- remain that do not satisfy it. This lazy approach just -- avoids doing unnecessary work. instantiate :: Int -> Nabla -> VarInfo -> MaybeT DsM VarInfo -instantiate fuel nabla vi = {-# SCC "instantiate" #-} - (instBot fuel nabla vi <|> instCompleteSets fuel nabla vi) +instantiate fuel nabla vi = {-# SCC "instantiate" #-} do + -- See Note [Strictness of pattern synonym matches] + matched <- lift (matchedPragmaSets vi) + if null matched + then instBot fuel nabla vi <|> instCompleteSets fuel nabla vi + else instCompleteSets fuel nabla vi <|> do + guard =<< lift (allInhabited fuel nabla (vi_id vi) matched) + instBot fuel nabla vi + +-- | The residual COMPLETE sets from pragmas that lost a member, for a variable +-- that might be ⊥. When one of them has no inhabitant, the variable is not ⊥. +-- See Note [Strictness of pattern synonym matches]. +matchedPragmaSets :: VarInfo -> DsM DsCompleteMatches +matchedPragmaSets VI{ vi_bot = IsNotBot } = pure [] +matchedPragmaSets VI{ vi_rcm = rcm } = case rcm_pragmas rcm of + Nothing -> pure [] + Just residuals -> do + originals <- dsGetCompleteMatches + let lost_member orig res = sizeUniqDSet (cmConLikes res) < sizeUniqDSet (cmConLikes orig) + pure [ res | (orig, res) <- zip originals residuals, lost_member orig res ] + +-- | Whether each of the COMPLETE sets has an inhabitant at the variable. +allInhabited :: Int -> Nabla -> Id -> DsCompleteMatches -> DsM Bool +allInhabited fuel nabla x cms = + isJust <$> runMaybeT (foldM (\nabla cm -> instCompleteSet fuel nabla x cm) nabla cms) -- | The \(⊢_{Bot}\) rule from the paper instBot :: Int -> Nabla -> VarInfo -> MaybeT DsM VarInfo @@ -1986,7 +2122,11 @@ generateInhabitingPatterns mode (x:xs) n nabla = do Just clss -> do -- Try each COMPLETE set. nablass' <- forM clss (instantiate_cons y rep_ty xs n newty_nabla) - if any null nablass' && vi_bot vi /= IsNotBot + -- See Note [Strictness of pattern synonym matches] + bot_possible <- if any null nablass' && vi_bot vi /= IsNotBot + then matchedPragmaSets vi >>= allInhabited initFuel newty_nabla y + else pure False + if bot_possible then generateInhabitingPatterns mode xs n newty_nabla -- bot is still possible. Display a wildcard! else do -- Pick the residual COMPLETE set with the smallest cost (see 'completeSetCost'). ===================================== compiler/GHC/HsToCore/Pmc/Solver/Types.hs ===================================== @@ -22,7 +22,7 @@ module GHC.HsToCore.Pmc.Solver.Types ( -- ** Representations for Literals and AltCons PmLit(..), PmLitValue(..), PmAltCon(..), pmLitType, pmAltConType, - isPmAltConMatchStrict, pmAltConImplBangs, + isPmAltConMatchStrict, pmAltConMatchMayDiverge, pmAltConImplBangs, -- *** PmAltConSet PmAltConSet, emptyPmAltConSet, isEmptyPmAltConSet, elemPmAltConSet, @@ -586,14 +586,23 @@ pmAltConType (PmAltLit lit) _arg_tys = assert (null _arg_tys ) $ pmLitType l pmAltConType (PmAltConLike con) arg_tys = conLikeResTy con arg_tys -- | Is a match on this constructor forcing the match variable? --- True of data constructors, literals and pattern synonyms (#17357), but not of --- newtypes. --- See Note [Coverage checking Newtype matches] in GHC.HsToCore.Pmc.Solver. +-- True of data constructors and literals, but not of newtypes and pattern +-- synonyms. +-- See Note [Coverage checking Newtype matches] and +-- Note [Strictness of pattern synonym matches] in GHC.HsToCore.Pmc.Solver. isPmAltConMatchStrict :: PmAltCon -> Bool isPmAltConMatchStrict PmAltLit{} = True -isPmAltConMatchStrict (PmAltConLike PatSynCon{}) = True -- #17357 +isPmAltConMatchStrict (PmAltConLike PatSynCon{}) = False isPmAltConMatchStrict (PmAltConLike (RealDataCon dc)) = not (isNewDataCon dc) +-- | Can a match on this constructor diverge when the match variable is ⊥? +-- True of everything but newtypes. +-- See Note [Coverage checking Newtype matches] and +-- Note [Strictness of pattern synonym matches] in GHC.HsToCore.Pmc.Solver. +pmAltConMatchMayDiverge :: PmAltCon -> Bool +pmAltConMatchMayDiverge (PmAltConLike (RealDataCon dc)) = not (isNewDataCon dc) +pmAltConMatchMayDiverge _ = True + pmAltConImplBangs :: PmAltCon -> [HsImplBang] pmAltConImplBangs PmAltLit{} = [] pmAltConImplBangs (PmAltConLike con) = conLikeImplBangs con ===================================== testsuite/tests/pmcheck/should_compile/T17357.stderr ===================================== @@ -1,20 +1,20 @@ - -T17357.hs:22:1: warning: [-Woverlapping-patterns (in -Wdefault)] +T17357.hs:22:1: warning: [GHC-94210] [-Woverlapping-patterns (in -Wdefault)] Pattern match has inaccessible right hand side In an equation for ‘f’: f F True = ... -T17357.hs:23:1: warning: [-Woverlapping-patterns (in -Wdefault)] +T17357.hs:23:1: warning: [GHC-94210] [-Woverlapping-patterns (in -Wdefault)] Pattern match has inaccessible right hand side In an equation for ‘f’: f !_ True = ... -T17357.hs:30:1: warning: [-Woverlapping-patterns (in -Wdefault)] +T17357.hs:30:1: warning: [GHC-94210] [-Woverlapping-patterns (in -Wdefault)] Pattern match has inaccessible right hand side In an equation for ‘f2’: f2 SF True = ... -T17357.hs:31:1: warning: [-Woverlapping-patterns (in -Wdefault)] +T17357.hs:31:1: warning: [GHC-94210] [-Woverlapping-patterns (in -Wdefault)] Pattern match has inaccessible right hand side In an equation for ‘f2’: f2 !_ True = ... -T17357.hs:42:1: warning: [-Woverlapping-patterns (in -Wdefault)] +T17357.hs:42:1: warning: [GHC-53633] [-Woverlapping-patterns (in -Wdefault)] Pattern match is redundant In an equation for ‘f3’: f3 !_ = ... + ===================================== testsuite/tests/pmcheck/should_compile/T28014.hs ===================================== @@ -0,0 +1,82 @@ +{-# LANGUAGE BangPatterns, GADTs, PatternSynonyms, ViewPatterns #-} +module T28014 where + +import Data.List (uncons) +import Data.Void + +-- | Never matches, and does not force its argument. +pattern F :: a +pattern F <- (const False -> True) + +-- | The bang is not redundant: withBang undefined is ⊥, but would be 2 +-- without the bang. +withBang :: Bool -> Int +withBang F = 1 +withBang !_ = 2 + +data T = MkT Void + +-- | Not exhaustive: h (MkT undefined) fails to match. +h :: T -> Int +h (MkT F) = 1 + +pattern Nil :: [a] +pattern Nil <- (null -> True) +pattern Cons :: a -> [a] -> [a] +pattern Cons x xs <- (uncons -> Just (x, xs)) +{-# COMPLETE Nil, Cons #-} + +-- | Exhaustive, and the last clause is redundant. +g :: [a] -> Int +g Nil = 0 +g (Cons _ _) = 1 +g _ = 2 + +-- | The last clause is redundant. +gBang :: [a] -> Int +gBang Nil = 0 +gBang (Cons _ _) = 1 +gBang !_ = 2 + +data G a where + G1' :: G Int + G2' :: G Bool + +pattern G1 :: () => (a ~ Int) => G a +pattern G1 = G1' +pattern G2 :: () => (a ~ Bool) => G a +pattern G2 = G2' +{-# COMPLETE G1, G2 #-} + +-- | Exhaustive: G2 cannot match at G Int. +fb :: G Int -> Int +fb G1 = 1 + +data U = MkU (G Char) + +-- | Exhaustive, by the COMPLETE pragma. +hu :: U -> Int +hu (MkU G1) = 1 + +-- | Not exhaustive: no member of the COMPLETE set for G can match at G Char, +-- and hc (MkU F) fails on MkU undefined. +hc :: U -> Int +hc (MkU F) = 1 + +-- | E Int has no constructor. +data E a where + E1 :: E Bool + +-- | No clause is inaccessible: w undefined G1' is 2. +w :: E a -> G a -> Int +w F _ = 1 +w _ G1' = 2 +w _ G2' = 3 + +pattern J :: a -> Maybe a +pattern J x = Just x + +-- | The bang is dead, but the checker can't see that J forces its argument. +k :: Maybe Int -> Int +k (J _) = 1 +k !_ = 2 ===================================== testsuite/tests/pmcheck/should_compile/T28014.stderr ===================================== @@ -0,0 +1,32 @@ +T28014.hs:21:1: warning: [GHC-62161] [-Wincomplete-patterns (in -Wextra)] + Pattern match(es) are non-exhaustive + In an equation for ‘h’: + Patterns of type ‘T’ not matched: MkT p where p is not one of {F} + +T28014.hs:33:1: warning: [GHC-53633] [-Woverlapping-patterns (in -Wdefault)] + Pattern match is redundant + In an equation for ‘g’: g _ = ... + +T28014.hs:39:1: warning: [GHC-53633] [-Woverlapping-patterns (in -Wdefault)] + Pattern match is redundant + In an equation for ‘gBang’: gBang !_ = ... + +T28014.hs:59:1: warning: [GHC-94210] [-Woverlapping-patterns (in -Wdefault)] + Pattern match has inaccessible right hand side + In an equation for ‘hu’: hu (MkU G1) = ... + +T28014.hs:59:9: warning: [GHC-40564] [-Winaccessible-code (in -Wdefault)] + • Inaccessible code in + a pattern with pattern synonym: + G1 :: forall a. () => (a ~ Int) => G a, + in an equation for ‘hu’ + Couldn't match type ‘Char’ with ‘Int’ + • In the pattern: G1 + In the pattern: MkU G1 + In an equation for ‘hu’: hu (MkU G1) = 1 + +T28014.hs:64:1: warning: [GHC-62161] [-Wincomplete-patterns (in -Wextra)] + Pattern match(es) are non-exhaustive + In an equation for ‘hc’: + Patterns of type ‘U’ not matched: MkU p where p is not one of {F} + ===================================== testsuite/tests/pmcheck/should_compile/T28014b.hs ===================================== @@ -0,0 +1,19 @@ +{-# LANGUAGE GADTs, PatternSynonyms, ViewPatterns #-} +module T28014b where + +pattern F :: a +pattern F <- (const False -> True) +{-# COMPLETE F #-} + +data G a where + G1' :: G Int + G2' :: G Bool + +data E a where + E1 :: E Bool + +-- | By the COMPLETE pragma, the first clause covers everything. +w :: E a -> G a -> Int +w F _ = 1 +w _ G1' = 2 +w _ G2' = 3 ===================================== testsuite/tests/pmcheck/should_compile/T28014b.stderr ===================================== @@ -0,0 +1,8 @@ +T28014b.hs:18:1: warning: [GHC-53633] [-Woverlapping-patterns (in -Wdefault)] + Pattern match is redundant + In an equation for ‘w’: w _ G1' = ... + +T28014b.hs:19:1: warning: [GHC-53633] [-Woverlapping-patterns (in -Wdefault)] + Pattern match is redundant + In an equation for ‘w’: w _ G2' = ... + ===================================== testsuite/tests/pmcheck/should_compile/all.T ===================================== @@ -56,7 +56,7 @@ test('T17219', expect_broken(17219), compile, [overlapping_incomplete]) test('T17234', normal, compile, [overlapping_incomplete]) test('T17248', normal, compile, [overlapping_incomplete]) test('T17340', normal, compile, ['-Wredundant-bang-patterns']) -test('T17357', expect_broken(17357), compile, [overlapping_incomplete]) +test('T17357', normal, compile, [overlapping_incomplete]) test('T17376', normal, compile, [overlapping_incomplete]) test('T17378', normal, compile, [overlapping_incomplete]) test('T17465', normal, compile, [overlapping_incomplete]) @@ -195,3 +195,5 @@ test('T27323b', normal, compile, ['-Wredundant-bang-patterns']) test('T27360', normal, compile, [overlapping_incomplete + '-g3']) test('T27892a', normal, compile, [overlapping_incomplete]) test('T28095', normal, compile, [overlapping_incomplete]) +test('T28014', normal, compile, [overlapping_incomplete + '-Wredundant-bang-patterns']) +test('T28014b', normal, compile, [overlapping_incomplete]) View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/53f8ee02e55a316faf95d711e0e60b12... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/53f8ee02e55a316faf95d711e0e60b12... You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
participants (1)
-
Sebastian Graf (@sgraf812)