2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
9 module Match ( match, matchEquations, matchWrapper, matchSimply, matchSinglePat ) where
11 #include "HsVersions.h"
41 This function is a wrapper of @match@, it must be called from all the parts where
42 it was called match, but only substitutes the firs call, ....
43 if the associated flags are declared, warnings will be issued.
44 It can not be called matchWrapper because this name already exists :-(
49 matchCheck :: DsMatchContext
50 -> [Id] -- Vars rep'ing the exprs we're matching with
51 -> Type -- Type of the case expression
52 -> [EquationInfo] -- Info about patterns, etc. (type synonym below)
53 -> DsM MatchResult -- Desugared result!
55 matchCheck ctx vars ty qs
56 = getDOptsDs `thenDs` \ dflags ->
57 matchCheck_really dflags ctx vars ty qs
59 matchCheck_really dflags ctx vars ty qs
60 | incomplete && shadow =
61 dsShadowWarn ctx eqns_shadow `thenDs` \ () ->
62 dsIncompleteWarn ctx pats `thenDs` \ () ->
65 dsIncompleteWarn ctx pats `thenDs` \ () ->
68 dsShadowWarn ctx eqns_shadow `thenDs` \ () ->
72 where (pats, eqns_shadow) = check qs
73 incomplete = want_incomplete && (notNull pats)
74 want_incomplete = case ctx of
75 DsMatchContext RecUpd _ ->
76 dopt Opt_WarnIncompletePatternsRecUpd dflags
78 dopt Opt_WarnIncompletePatterns dflags
79 shadow = dopt Opt_WarnOverlappingPatterns dflags
80 && not (null eqns_shadow)
83 This variable shows the maximum number of lines of output generated for warnings.
84 It will limit the number of patterns/equations displayed to@ maximum_output@.
86 (ToDo: add command-line option?)
92 The next two functions create the warning message.
95 dsShadowWarn :: DsMatchContext -> [EquationInfo] -> DsM ()
96 dsShadowWarn ctx@(DsMatchContext kind loc) qs
97 = putSrcSpanDs loc (warnDs warn)
99 warn | qs `lengthExceeds` maximum_output
100 = pp_context ctx (ptext SLIT("are overlapped"))
101 (\ f -> vcat (map (ppr_eqn f kind) (take maximum_output qs)) $$
104 = pp_context ctx (ptext SLIT("are overlapped"))
105 (\ f -> vcat $ map (ppr_eqn f kind) qs)
108 dsIncompleteWarn :: DsMatchContext -> [ExhaustivePat] -> DsM ()
109 dsIncompleteWarn ctx@(DsMatchContext kind loc) pats
110 = putSrcSpanDs loc (warnDs warn)
112 warn = pp_context ctx (ptext SLIT("are non-exhaustive"))
113 (\f -> hang (ptext SLIT("Patterns not matched:"))
114 4 ((vcat $ map (ppr_incomplete_pats kind)
115 (take maximum_output pats))
118 dots | pats `lengthExceeds` maximum_output = ptext SLIT("...")
121 pp_context (DsMatchContext kind _loc) msg rest_of_msg_fun
122 = vcat [ptext SLIT("Pattern match(es)") <+> msg,
123 sep [ptext SLIT("In") <+> ppr_match <> char ':', nest 4 (rest_of_msg_fun pref)]]
127 FunRhs fun -> (pprMatchContext kind, \ pp -> ppr fun <+> pp)
128 other -> (pprMatchContext kind, \ pp -> pp)
130 ppr_pats pats = sep (map ppr pats)
132 ppr_shadow_pats kind pats
133 = sep [ppr_pats pats, matchSeparator kind, ptext SLIT("...")]
135 ppr_incomplete_pats kind (pats,[]) = ppr_pats pats
136 ppr_incomplete_pats kind (pats,constraints) =
137 sep [ppr_pats pats, ptext SLIT("with"),
138 sep (map ppr_constraint constraints)]
141 ppr_constraint (var,pats) = sep [ppr var, ptext SLIT("`notElem`"), ppr pats]
143 ppr_eqn prefixF kind eqn = prefixF (ppr_shadow_pats kind (eqn_pats eqn))
147 %************************************************************************
149 The main matching function
151 %************************************************************************
153 The function @match@ is basically the same as in the Wadler chapter,
154 except it is monadised, to carry around the name supply, info about
157 Notes on @match@'s arguments, assuming $m$ equations and $n$ patterns:
160 A list of $n$ variable names, those variables presumably bound to the
161 $n$ expressions being matched against the $n$ patterns. Using the
162 list of $n$ expressions as the first argument showed no benefit and
166 The second argument, a list giving the ``equation info'' for each of
170 the $n$ patterns for that equation, and
172 a list of Core bindings [@(Id, CoreExpr)@ pairs] to be ``stuck on
173 the front'' of the matching code, as in:
179 and finally: (ToDo: fill in)
181 The right way to think about the ``after-match function'' is that it
182 is an embryonic @CoreExpr@ with a ``hole'' at the end for the
183 final ``else expression''.
186 There is a type synonym, @EquationInfo@, defined in module @DsUtils@.
188 An experiment with re-ordering this information about equations (in
189 particular, having the patterns available in column-major order)
193 A default expression---what to evaluate if the overall pattern-match
194 fails. This expression will (almost?) always be
195 a measly expression @Var@, unless we know it will only be used once
196 (as we do in @glue_success_exprs@).
198 Leaving out this third argument to @match@ (and slamming in lots of
199 @Var "fail"@s) is a positively {\em bad} idea, because it makes it
200 impossible to share the default expressions. (Also, it stands no
201 chance of working in our post-upheaval world of @Locals@.)
204 Note: @match@ is often called via @matchWrapper@ (end of this module),
205 a function that does much of the house-keeping that goes with a call
208 It is also worth mentioning the {\em typical} way a block of equations
209 is desugared with @match@. At each stage, it is the first column of
210 patterns that is examined. The steps carried out are roughly:
213 Tidy the patterns in column~1 with @tidyEqnInfo@ (this may add
214 bindings to the second component of the equation-info):
217 Remove the `as' patterns from column~1.
219 Make all constructor patterns in column~1 into @ConPats@, notably
220 @ListPats@ and @TuplePats@.
222 Handle any irrefutable (or ``twiddle'') @LazyPats@.
225 Now {\em unmix} the equations into {\em blocks} [w/ local function
226 @unmix_eqns@], in which the equations in a block all have variable
227 patterns in column~1, or they all have constructor patterns in ...
228 (see ``the mixture rule'' in SLPJ).
230 Call @matchEqnBlock@ on each block of equations; it will do the
231 appropriate thing for each kind of column-1 pattern, usually ending up
232 in a recursive call to @match@.
235 We are a little more paranoid about the ``empty rule'' (SLPJ, p.~87)
236 than the Wadler-chapter code for @match@ (p.~93, first @match@ clause).
237 And gluing the ``success expressions'' together isn't quite so pretty.
239 This (more interesting) clause of @match@ uses @tidy_and_unmix_eqns@
240 (a)~to get `as'- and `twiddle'-patterns out of the way (tidying), and
241 (b)~to do ``the mixture rule'' (SLPJ, p.~88) [which really {\em
242 un}mixes the equations], producing a list of equation-info
243 blocks, each block having as its first column of patterns either all
244 constructors, or all variables (or similar beasts), etc.
246 @match_unmixed_eqn_blks@ simply takes the place of the @foldr@ in the
247 Wadler-chapter @match@ (p.~93, last clause), and @match_unmixed_blk@
248 corresponds roughly to @matchVarCon@.
251 match :: [Id] -- Variables rep'ing the exprs we're matching with
252 -> Type -- Type of the case expression
253 -> [EquationInfo] -- Info about patterns, etc. (type synonym below)
254 -> DsM MatchResult -- Desugared result!
257 = ASSERT2( not (null eqns), ppr ty )
258 returnDs (foldr1 combineMatchResults match_results)
260 match_results = [ ASSERT( null (eqn_pats eqn) )
264 match vars@(v:_) ty eqns
265 = ASSERT( not (null eqns ) )
266 do { -- Tidy the first pattern, generating
267 -- auxiliary bindings if necessary
268 (aux_binds, tidy_eqns) <- mapAndUnzipM (tidyEqnInfo v) eqns
270 -- Group the equations and match each group in turn
271 ; match_results <- mapM match_group (groupEquations tidy_eqns)
273 ; return (adjustMatchResult (foldr1 (.) aux_binds) $
274 foldr1 combineMatchResults match_results) }
276 dropGroup :: [(PatGroup,EquationInfo)] -> [EquationInfo]
279 match_group :: [(PatGroup,EquationInfo)] -> DsM MatchResult
280 match_group eqns@((group,_) : _)
282 PgAny -> matchVariables vars ty (dropGroup eqns)
283 PgCon _ -> matchConFamily vars ty (subGroups eqns)
284 PgLit _ -> matchLiterals vars ty (subGroups eqns)
285 PgN lit -> matchNPats vars ty (subGroups eqns)
286 PgNpK lit -> matchNPlusKPats vars ty (dropGroup eqns)
287 PgBang -> matchBangs vars ty (dropGroup eqns)
288 PgCo _ -> matchCoercion vars ty (dropGroup eqns)
290 matchVariables :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
291 -- Real true variables, just like in matchVar, SLPJ p 94
292 -- No binding to do: they'll all be wildcards by now (done in tidy)
293 matchVariables (var:vars) ty eqns = match vars ty (shiftEqns eqns)
295 matchBangs :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
296 matchBangs (var:vars) ty eqns
297 = do { match_result <- match (var:vars) ty (map shift eqns)
298 ; return (mkEvalMatchResult var ty match_result) }
300 shift eqn@(EqnInfo { eqn_pats = BangPat pat : pats })
301 = eqn { eqn_pats = unLoc pat : pats }
303 matchCoercion :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
304 -- Apply the coercion to the match variable and then match that
305 matchCoercion (var:vars) ty (eqn1:eqns)
306 = do { let CoPat co pat _ = firstPat eqn1
307 ; var' <- newUniqueId (idName var) (hsPatType pat)
308 ; match_result <- match (var':vars) ty (map shift (eqn1:eqns))
309 ; rhs <- dsCoercion co (return (Var var))
310 ; return (mkCoLetMatchResult (NonRec var' rhs) match_result) }
312 shift eqn@(EqnInfo { eqn_pats = CoPat _ pat _ : pats })
313 = eqn { eqn_pats = pat : pats }
316 %************************************************************************
320 %************************************************************************
322 Tidy up the leftmost pattern in an @EquationInfo@, given the variable @v@
323 which will be scrutinised. This means:
326 Replace variable patterns @x@ (@x /= v@) with the pattern @_@,
327 together with the binding @x = v@.
329 Replace the `as' pattern @x@@p@ with the pattern p and a binding @x = v@.
331 Removing lazy (irrefutable) patterns (you don't want to know...).
333 Converting explicit tuple-, list-, and parallel-array-pats into ordinary
336 Convert the literal pat "" to [].
339 The result of this tidying is that the column of patterns will include
343 The @VarPat@ information isn't needed any more after this.
346 @ListPats@, @TuplePats@, etc., are all converted into @ConPats@.
348 \item[@LitPats@ and @NPats@:]
349 @LitPats@/@NPats@ of ``known friendly types'' (Int, Char,
350 Float, Double, at least) are converted to unboxed form; e.g.,
351 \tr{(NPat (HsInt i) _ _)} is converted to:
353 (ConPat I# _ _ [LitPat (HsIntPrim i)])
358 tidyEqnInfo :: Id -> EquationInfo
359 -> DsM (DsWrapper, EquationInfo)
360 -- DsM'd because of internal call to dsLHsBinds
361 -- and mkSelectorBinds.
362 -- "tidy1" does the interesting stuff, looking at
363 -- one pattern and fiddling the list of bindings.
365 -- POST CONDITION: head pattern in the EqnInfo is
373 tidyEqnInfo v eqn@(EqnInfo { eqn_pats = pat : pats })
374 = tidy1 v pat `thenDs` \ (wrap, pat') ->
375 returnDs (wrap, eqn { eqn_pats = pat' : pats })
377 tidy1 :: Id -- The Id being scrutinised
378 -> Pat Id -- The pattern against which it is to be matched
379 -> DsM (DsWrapper, -- Extra bindings to do before the match
380 Pat Id) -- Equivalent pattern
382 -------------------------------------------------------
383 -- (pat', mr') = tidy1 v pat mr
384 -- tidies the *outer level only* of pat, giving pat'
385 -- It eliminates many pattern forms (as-patterns, variable patterns,
386 -- list patterns, etc) yielding one of:
393 tidy1 v (ParPat pat) = tidy1 v (unLoc pat)
394 tidy1 v (SigPatOut pat _) = tidy1 v (unLoc pat)
395 tidy1 v (WildPat ty) = returnDs (idDsWrapper, WildPat ty)
397 -- case v of { x -> mr[] }
398 -- = case v of { _ -> let x=v in mr[] }
400 = returnDs (wrapBind var v, WildPat (idType var))
402 tidy1 v (VarPatOut var binds)
403 = do { prs <- dsLHsBinds binds
404 ; return (wrapBind var v . mkDsLet (Rec prs),
405 WildPat (idType var)) }
407 -- case v of { x@p -> mr[] }
408 -- = case v of { p -> let x=v in mr[] }
409 tidy1 v (AsPat (L _ var) pat)
410 = do { (wrap, pat') <- tidy1 v (unLoc pat)
411 ; return (wrapBind var v . wrap, pat') }
413 {- now, here we handle lazy patterns:
414 tidy1 v ~p bs = (v, v1 = case v of p -> v1 :
415 v2 = case v of p -> v2 : ... : bs )
417 where the v_i's are the binders in the pattern.
419 ToDo: in "v_i = ... -> v_i", are the v_i's really the same thing?
421 The case expr for v_i is just: match [v] [(p, [], \ x -> Var v_i)] any_expr
424 tidy1 v (LazyPat pat)
425 = do { sel_prs <- mkSelectorBinds pat (Var v)
426 ; let sel_binds = [NonRec b rhs | (b,rhs) <- sel_prs]
427 ; returnDs (mkDsLets sel_binds, WildPat (idType v)) }
429 tidy1 v (ListPat pats ty)
430 = returnDs (idDsWrapper, unLoc list_ConPat)
432 list_ty = mkListTy ty
433 list_ConPat = foldr (\ x y -> mkPrefixConPat consDataCon [x, y] list_ty)
437 -- Introduce fake parallel array constructors to be able to handle parallel
438 -- arrays with the existing machinery for constructor pattern
439 tidy1 v (PArrPat pats ty)
440 = returnDs (idDsWrapper, unLoc parrConPat)
443 parrConPat = mkPrefixConPat (parrFakeCon arity) pats (mkPArrTy ty)
445 tidy1 v (TuplePat pats boxity ty)
446 = returnDs (idDsWrapper, unLoc tuple_ConPat)
449 tuple_ConPat = mkPrefixConPat (tupleCon boxity arity) pats ty
451 tidy1 v (DictPat dicts methods)
452 = case num_of_d_and_ms of
453 0 -> tidy1 v (TuplePat [] Boxed unitTy)
454 1 -> tidy1 v (unLoc (head dict_and_method_pats))
455 _ -> tidy1 v (mkVanillaTuplePat dict_and_method_pats Boxed)
457 num_of_d_and_ms = length dicts + length methods
458 dict_and_method_pats = map nlVarPat (dicts ++ methods)
460 -- LitPats: we *might* be able to replace these w/ a simpler form
462 = returnDs (idDsWrapper, tidyLitPat lit)
464 -- NPats: we *might* be able to replace these w/ a simpler form
465 tidy1 v (NPat lit mb_neg eq lit_ty)
466 = returnDs (idDsWrapper, tidyNPat lit mb_neg eq lit_ty)
468 -- Everything else goes through unchanged...
470 tidy1 v non_interesting_pat
471 = returnDs (idDsWrapper, non_interesting_pat)
475 {\bf Previous @matchTwiddled@ stuff:}
477 Now we get to the only interesting part; note: there are choices for
478 translation [from Simon's notes]; translation~1:
485 s = case w of [s,t] -> s
486 t = case w of [s,t] -> t
490 Here \tr{w} is a fresh variable, and the \tr{w}-binding prevents multiple
491 evaluation of \tr{e}. An alternative translation (No.~2):
493 [ w = case e of [s,t] -> (s,t)
494 s = case w of (s,t) -> s
495 t = case w of (s,t) -> t
499 %************************************************************************
501 \subsubsection[improved-unmixing]{UNIMPLEMENTED idea for improved unmixing}
503 %************************************************************************
505 We might be able to optimise unmixing when confronted by
506 only-one-constructor-possible, of which tuples are the most notable
514 This definition would normally be unmixed into four equation blocks,
515 one per equation. But it could be unmixed into just one equation
516 block, because if the one equation matches (on the first column),
517 the others certainly will.
519 You have to be careful, though; the example
527 {\em must} be broken into two blocks at the line shown; otherwise, you
528 are forcing unnecessary evaluation. In any case, the top-left pattern
529 always gives the cue. You could then unmix blocks into groups of...
531 \item[all variables:]
533 \item[constructors or variables (mixed):]
534 Need to make sure the right names get bound for the variable patterns.
535 \item[literals or variables (mixed):]
536 Presumably just a variant on the constructor case (as it is now).
539 %************************************************************************
541 %* matchWrapper: a convenient way to call @match@ *
543 %************************************************************************
544 \subsection[matchWrapper]{@matchWrapper@: a convenient interface to @match@}
546 Calls to @match@ often involve similar (non-trivial) work; that work
547 is collected here, in @matchWrapper@. This function takes as
551 Typchecked @Matches@ (of a function definition, or a case or lambda
552 expression)---the main input;
554 An error message to be inserted into any (runtime) pattern-matching
558 As results, @matchWrapper@ produces:
561 A list of variables (@Locals@) that the caller must ``promise'' to
562 bind to appropriate values; and
564 a @CoreExpr@, the desugared output (main result).
567 The main actions of @matchWrapper@ include:
570 Flatten the @[TypecheckedMatch]@ into a suitable list of
573 Create as many new variables as there are patterns in a pattern-list
574 (in any one of the @EquationInfo@s).
576 Create a suitable ``if it fails'' expression---a call to @error@ using
577 the error-string input; the {\em type} of this fail value can be found
578 by examining one of the RHS expressions in one of the @EquationInfo@s.
580 Call @match@ with all of this information!
584 matchWrapper :: HsMatchContext Name -- For shadowing warning messages
585 -> MatchGroup Id -- Matches being desugared
586 -> DsM ([Id], CoreExpr) -- Results
589 There is one small problem with the Lambda Patterns, when somebody
590 writes something similar to:
594 he/she don't want a warning about incomplete patterns, that is done with
595 the flag @opt_WarnSimplePatterns@.
596 This problem also appears in the:
598 \item @do@ patterns, but if the @do@ can fail
599 it creates another equation if the match can fail
600 (see @DsExpr.doDo@ function)
601 \item @let@ patterns, are treated by @matchSimply@
602 List Comprension Patterns, are treated by @matchSimply@ also
605 We can't call @matchSimply@ with Lambda patterns,
606 due to the fact that lambda patterns can have more than
607 one pattern, and match simply only accepts one pattern.
612 matchWrapper ctxt (MatchGroup matches match_ty)
613 = do { eqns_info <- mapM mk_eqn_info matches
614 ; new_vars <- selectMatchVars arg_pats
615 ; result_expr <- matchEquations ctxt new_vars eqns_info rhs_ty
616 ; return (new_vars, result_expr) }
618 arg_pats = map unLoc (hsLMatchPats (head matches))
619 n_pats = length arg_pats
620 (_, rhs_ty) = splitFunTysN n_pats match_ty
622 mk_eqn_info (L _ (Match pats _ grhss))
623 = do { let upats = map unLoc pats
624 ; match_result <- dsGRHSs ctxt upats grhss rhs_ty
625 ; return (EqnInfo { eqn_pats = upats, eqn_rhs = match_result}) }
628 matchEquations :: HsMatchContext Name
629 -> [Id] -> [EquationInfo] -> Type
631 matchEquations ctxt vars eqns_info rhs_ty
632 = do { dflags <- getDOptsDs
633 ; locn <- getSrcSpanDs
634 ; let ds_ctxt = DsMatchContext ctxt locn
635 error_string = matchContextErrString ctxt
637 ; match_result <- match_fun dflags ds_ctxt vars rhs_ty eqns_info
639 ; fail_expr <- mkErrorAppDs pAT_ERROR_ID rhs_ty error_string
640 ; extractMatchResult match_result fail_expr }
642 match_fun dflags ds_ctxt
644 LambdaExpr | dopt Opt_WarnSimplePatterns dflags -> matchCheck ds_ctxt
646 _ -> matchCheck ds_ctxt
649 %************************************************************************
651 \subsection[matchSimply]{@matchSimply@: match a single expression against a single pattern}
653 %************************************************************************
655 @mkSimpleMatch@ is a wrapper for @match@ which deals with the
656 situation where we want to match a single expression against a single
657 pattern. It returns an expression.
660 matchSimply :: CoreExpr -- Scrutinee
661 -> HsMatchContext Name -- Match kind
662 -> LPat Id -- Pattern it should match
663 -> CoreExpr -- Return this if it matches
664 -> CoreExpr -- Return this if it doesn't
667 matchSimply scrut hs_ctx pat result_expr fail_expr
669 match_result = cantFailMatchResult result_expr
670 rhs_ty = exprType fail_expr
671 -- Use exprType of fail_expr, because won't refine in the case of failure!
673 matchSinglePat scrut hs_ctx pat rhs_ty match_result `thenDs` \ match_result' ->
674 extractMatchResult match_result' fail_expr
677 matchSinglePat :: CoreExpr -> HsMatchContext Name -> LPat Id
678 -> Type -> MatchResult -> DsM MatchResult
679 matchSinglePat (Var var) hs_ctx (L _ pat) ty match_result
680 = getDOptsDs `thenDs` \ dflags ->
681 getSrcSpanDs `thenDs` \ locn ->
684 | dopt Opt_WarnSimplePatterns dflags = matchCheck ds_ctx
687 ds_ctx = DsMatchContext hs_ctx locn
689 match_fn dflags [var] ty [EqnInfo { eqn_pats = [pat], eqn_rhs = match_result }]
691 matchSinglePat scrut hs_ctx pat ty match_result
692 = selectSimpleMatchVarL pat `thenDs` \ var ->
693 matchSinglePat (Var var) hs_ctx pat ty match_result `thenDs` \ match_result' ->
694 returnDs (adjustMatchResult (bindNonRec var scrut) match_result')
698 %************************************************************************
700 Pattern classification
702 %************************************************************************
706 = PgAny -- Immediate match: variables, wildcards,
708 | PgCon DataCon -- Constructor patterns (incl list, tuple)
709 | PgLit Literal -- Literal patterns
710 | PgN Literal -- Overloaded literals
711 | PgNpK Literal -- n+k patterns
712 | PgBang -- Bang patterns
713 | PgCo Type -- Coercion patterns; the type is the type
714 -- of the pattern *inside*
717 groupEquations :: [EquationInfo] -> [[(PatGroup, EquationInfo)]]
718 -- If the result is of form [g1, g2, g3],
719 -- (a) all the (pg,eq) pairs in g1 have the same pg
720 -- (b) none of the gi are empty
722 = runs same_gp [(patGroup (firstPat eqn), eqn) | eqn <- eqns]
724 same_gp :: (PatGroup,EquationInfo) -> (PatGroup,EquationInfo) -> Bool
725 (pg1,_) `same_gp` (pg2,_) = pg1 `sameGroup` pg2
727 subGroups :: [(PatGroup, EquationInfo)] -> [[EquationInfo]]
728 -- Input is a particular group. The result sub-groups the
729 -- equations by with particular constructor, literal etc they match.
730 -- The order may be swizzled, so the matching should be order-independent
731 subGroups groups = map (map snd) (equivClasses cmp groups)
733 (pg1, _) `cmp` (pg2, _) = pg1 `cmp_pg` pg2
734 (PgCon c1) `cmp_pg` (PgCon c2) = c1 `compare` c2
735 (PgLit l1) `cmp_pg` (PgLit l2) = l1 `compare` l2
736 (PgN l1) `cmp_pg` (PgN l2) = l1 `compare` l2
737 -- These are the only cases that are every sub-grouped
739 sameGroup :: PatGroup -> PatGroup -> Bool
740 -- Same group means that a single case expression
741 -- or test will suffice to match both, *and* the order
742 -- of testing within the group is insignificant.
743 sameGroup PgAny PgAny = True
744 sameGroup PgBang PgBang = True
745 sameGroup (PgCon _) (PgCon _) = True -- One case expression
746 sameGroup (PgLit _) (PgLit _) = True -- One case expression
747 sameGroup (PgN l1) (PgN l2) = True -- Needs conditionals
748 sameGroup (PgNpK l1) (PgNpK l2) = l1==l2 -- Order is significant
749 -- See Note [Order of n+k]
750 sameGroup (PgCo t1) (PgCo t2) = t1 `coreEqType` t2
751 -- CoPats are in the same goup only if the type of the
752 -- enclosed pattern is the same. The patterns outside the CoPat
753 -- always have the same type, so this boils down to saying that
754 -- the two coercions are identical.
755 sameGroup _ _ = False
757 patGroup :: Pat Id -> PatGroup
758 patGroup (WildPat {}) = PgAny
759 patGroup (BangPat {}) = PgBang
760 patGroup (ConPatOut { pat_con = dc }) = PgCon (unLoc dc)
761 patGroup (LitPat lit) = PgLit (hsLitKey lit)
762 patGroup (NPat olit mb_neg _ _) = PgN (hsOverLitKey olit (isJust mb_neg))
763 patGroup (NPlusKPat _ olit _ _) = PgNpK (hsOverLitKey olit False)
764 patGroup (CoPat _ p _) = PgCo (hsPatType p) -- Type of inner pattern
765 patGroup pat = pprPanic "patGroup" (ppr pat)
776 We can't group the first and third together, because the second may match
777 the same thing as the first. Contrast
781 where we can group the first and third. Hence we don't regard (n+1) and
782 (n+2) as part of the same group.