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"
13 import {-#SOURCE#-} DsExpr (dsLExpr)
41 import qualified Data.Map as Map
44 This function is a wrapper of @match@, it must be called from all the parts where
45 it was called match, but only substitutes the firs call, ....
46 if the associated flags are declared, warnings will be issued.
47 It can not be called matchWrapper because this name already exists :-(
52 matchCheck :: DsMatchContext
53 -> [Id] -- Vars rep'ing the exprs we're matching with
54 -> Type -- Type of the case expression
55 -> [EquationInfo] -- Info about patterns, etc. (type synonym below)
56 -> DsM MatchResult -- Desugared result!
58 matchCheck ctx vars ty qs = do
60 matchCheck_really dflags ctx vars ty qs
62 matchCheck_really :: DynFlags
68 matchCheck_really dflags ctx vars ty qs
69 | incomplete && shadow = do
70 dsShadowWarn ctx eqns_shadow
71 dsIncompleteWarn ctx pats
74 dsIncompleteWarn ctx pats
77 dsShadowWarn ctx eqns_shadow
81 where (pats, eqns_shadow) = check qs
82 incomplete = want_incomplete && (notNull pats)
83 want_incomplete = case ctx of
84 DsMatchContext RecUpd _ ->
85 dopt Opt_WarnIncompletePatternsRecUpd dflags
87 dopt Opt_WarnIncompletePatterns dflags
88 shadow = dopt Opt_WarnOverlappingPatterns dflags
89 && not (null eqns_shadow)
92 This variable shows the maximum number of lines of output generated for warnings.
93 It will limit the number of patterns/equations displayed to@ maximum_output@.
95 (ToDo: add command-line option?)
102 The next two functions create the warning message.
105 dsShadowWarn :: DsMatchContext -> [EquationInfo] -> DsM ()
106 dsShadowWarn ctx@(DsMatchContext kind loc) qs
107 = putSrcSpanDs loc (warnDs warn)
109 warn | qs `lengthExceeds` maximum_output
110 = pp_context ctx (ptext (sLit "are overlapped"))
111 (\ f -> vcat (map (ppr_eqn f kind) (take maximum_output qs)) $$
114 = pp_context ctx (ptext (sLit "are overlapped"))
115 (\ f -> vcat $ map (ppr_eqn f kind) qs)
118 dsIncompleteWarn :: DsMatchContext -> [ExhaustivePat] -> DsM ()
119 dsIncompleteWarn ctx@(DsMatchContext kind loc) pats
120 = putSrcSpanDs loc (warnDs warn)
122 warn = pp_context ctx (ptext (sLit "are non-exhaustive"))
123 (\_ -> hang (ptext (sLit "Patterns not matched:"))
124 4 ((vcat $ map (ppr_incomplete_pats kind)
125 (take maximum_output pats))
128 dots | pats `lengthExceeds` maximum_output = ptext (sLit "...")
131 pp_context :: DsMatchContext -> SDoc -> ((SDoc -> SDoc) -> SDoc) -> SDoc
132 pp_context (DsMatchContext kind _loc) msg rest_of_msg_fun
133 = vcat [ptext (sLit "Pattern match(es)") <+> msg,
134 sep [ptext (sLit "In") <+> ppr_match <> char ':', nest 4 (rest_of_msg_fun pref)]]
138 FunRhs fun _ -> (pprMatchContext kind, \ pp -> ppr fun <+> pp)
139 _ -> (pprMatchContext kind, \ pp -> pp)
141 ppr_pats :: Outputable a => [a] -> SDoc
142 ppr_pats pats = sep (map ppr pats)
144 ppr_shadow_pats :: HsMatchContext Name -> [Pat Id] -> SDoc
145 ppr_shadow_pats kind pats
146 = sep [ppr_pats pats, matchSeparator kind, ptext (sLit "...")]
148 ppr_incomplete_pats :: HsMatchContext Name -> ExhaustivePat -> SDoc
149 ppr_incomplete_pats _ (pats,[]) = ppr_pats pats
150 ppr_incomplete_pats _ (pats,constraints) =
151 sep [ppr_pats pats, ptext (sLit "with"),
152 sep (map ppr_constraint constraints)]
154 ppr_constraint :: (Name,[HsLit]) -> SDoc
155 ppr_constraint (var,pats) = sep [ppr var, ptext (sLit "`notElem`"), ppr pats]
157 ppr_eqn :: (SDoc -> SDoc) -> HsMatchContext Name -> EquationInfo -> SDoc
158 ppr_eqn prefixF kind eqn = prefixF (ppr_shadow_pats kind (eqn_pats eqn))
162 %************************************************************************
164 The main matching function
166 %************************************************************************
168 The function @match@ is basically the same as in the Wadler chapter,
169 except it is monadised, to carry around the name supply, info about
172 Notes on @match@'s arguments, assuming $m$ equations and $n$ patterns:
175 A list of $n$ variable names, those variables presumably bound to the
176 $n$ expressions being matched against the $n$ patterns. Using the
177 list of $n$ expressions as the first argument showed no benefit and
181 The second argument, a list giving the ``equation info'' for each of
185 the $n$ patterns for that equation, and
187 a list of Core bindings [@(Id, CoreExpr)@ pairs] to be ``stuck on
188 the front'' of the matching code, as in:
194 and finally: (ToDo: fill in)
196 The right way to think about the ``after-match function'' is that it
197 is an embryonic @CoreExpr@ with a ``hole'' at the end for the
198 final ``else expression''.
201 There is a type synonym, @EquationInfo@, defined in module @DsUtils@.
203 An experiment with re-ordering this information about equations (in
204 particular, having the patterns available in column-major order)
208 A default expression---what to evaluate if the overall pattern-match
209 fails. This expression will (almost?) always be
210 a measly expression @Var@, unless we know it will only be used once
211 (as we do in @glue_success_exprs@).
213 Leaving out this third argument to @match@ (and slamming in lots of
214 @Var "fail"@s) is a positively {\em bad} idea, because it makes it
215 impossible to share the default expressions. (Also, it stands no
216 chance of working in our post-upheaval world of @Locals@.)
219 Note: @match@ is often called via @matchWrapper@ (end of this module),
220 a function that does much of the house-keeping that goes with a call
223 It is also worth mentioning the {\em typical} way a block of equations
224 is desugared with @match@. At each stage, it is the first column of
225 patterns that is examined. The steps carried out are roughly:
228 Tidy the patterns in column~1 with @tidyEqnInfo@ (this may add
229 bindings to the second component of the equation-info):
232 Remove the `as' patterns from column~1.
234 Make all constructor patterns in column~1 into @ConPats@, notably
235 @ListPats@ and @TuplePats@.
237 Handle any irrefutable (or ``twiddle'') @LazyPats@.
240 Now {\em unmix} the equations into {\em blocks} [w\/ local function
241 @unmix_eqns@], in which the equations in a block all have variable
242 patterns in column~1, or they all have constructor patterns in ...
243 (see ``the mixture rule'' in SLPJ).
245 Call @matchEqnBlock@ on each block of equations; it will do the
246 appropriate thing for each kind of column-1 pattern, usually ending up
247 in a recursive call to @match@.
250 We are a little more paranoid about the ``empty rule'' (SLPJ, p.~87)
251 than the Wadler-chapter code for @match@ (p.~93, first @match@ clause).
252 And gluing the ``success expressions'' together isn't quite so pretty.
254 This (more interesting) clause of @match@ uses @tidy_and_unmix_eqns@
255 (a)~to get `as'- and `twiddle'-patterns out of the way (tidying), and
256 (b)~to do ``the mixture rule'' (SLPJ, p.~88) [which really {\em
257 un}mixes the equations], producing a list of equation-info
258 blocks, each block having as its first column of patterns either all
259 constructors, or all variables (or similar beasts), etc.
261 @match_unmixed_eqn_blks@ simply takes the place of the @foldr@ in the
262 Wadler-chapter @match@ (p.~93, last clause), and @match_unmixed_blk@
263 corresponds roughly to @matchVarCon@.
266 match :: [Id] -- Variables rep\'ing the exprs we\'re matching with
267 -> Type -- Type of the case expression
268 -> [EquationInfo] -- Info about patterns, etc. (type synonym below)
269 -> DsM MatchResult -- Desugared result!
272 = ASSERT2( not (null eqns), ppr ty )
273 return (foldr1 combineMatchResults match_results)
275 match_results = [ ASSERT( null (eqn_pats eqn) )
279 match vars@(v:_) ty eqns
280 = ASSERT( not (null eqns ) )
281 do { -- Tidy the first pattern, generating
282 -- auxiliary bindings if necessary
283 (aux_binds, tidy_eqns) <- mapAndUnzipM (tidyEqnInfo v) eqns
285 -- Group the equations and match each group in turn
286 ; let grouped = groupEquations tidy_eqns
288 -- print the view patterns that are commoned up to help debug
289 ; ifDOptM Opt_D_dump_view_pattern_commoning (debug grouped)
291 ; match_results <- mapM match_group grouped
292 ; return (adjustMatchResult (foldr1 (.) aux_binds) $
293 foldr1 combineMatchResults match_results) }
295 dropGroup :: [(PatGroup,EquationInfo)] -> [EquationInfo]
298 match_group :: [(PatGroup,EquationInfo)] -> DsM MatchResult
299 match_group [] = panic "match_group"
300 match_group eqns@((group,_) : _)
302 PgCon _ -> matchConFamily vars ty (subGroup [(c,e) | (PgCon c, e) <- eqns])
303 PgLit _ -> matchLiterals vars ty (subGroup [(l,e) | (PgLit l, e) <- eqns])
304 PgAny -> matchVariables vars ty (dropGroup eqns)
305 PgN _ -> matchNPats vars ty (dropGroup eqns)
306 PgNpK _ -> matchNPlusKPats vars ty (dropGroup eqns)
307 PgBang -> matchBangs vars ty (dropGroup eqns)
308 PgCo _ -> matchCoercion vars ty (dropGroup eqns)
309 PgView _ _ -> matchView vars ty (dropGroup eqns)
311 -- FIXME: we should also warn about view patterns that should be
312 -- commoned up but are not
314 -- print some stuff to see what's getting grouped
315 -- use -dppr-debug to see the resolution of overloaded lits
317 let gs = map (\group -> foldr (\ (p,_) -> \acc ->
318 case p of PgView e _ -> e:acc
319 _ -> acc) [] group) eqns
320 maybeWarn [] = return ()
321 maybeWarn l = warnDs (vcat l)
323 maybeWarn $ (map (\g -> text "Putting these view expressions into the same case:" <+> (ppr g))
324 (filter (not . null) gs))
326 matchVariables :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
327 -- Real true variables, just like in matchVar, SLPJ p 94
328 -- No binding to do: they'll all be wildcards by now (done in tidy)
329 matchVariables (_:vars) ty eqns = match vars ty (shiftEqns eqns)
330 matchVariables [] _ _ = panic "matchVariables"
332 matchBangs :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
333 matchBangs (var:vars) ty eqns
334 = do { match_result <- match (var:vars) ty $
335 map (decomposeFirstPat getBangPat) eqns
336 ; return (mkEvalMatchResult var ty match_result) }
337 matchBangs [] _ _ = panic "matchBangs"
339 matchCoercion :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
340 -- Apply the coercion to the match variable and then match that
341 matchCoercion (var:vars) ty (eqns@(eqn1:_))
342 = do { let CoPat co pat _ = firstPat eqn1
343 ; var' <- newUniqueId var (hsPatType pat)
344 ; match_result <- match (var':vars) ty $
345 map (decomposeFirstPat getCoPat) eqns
346 ; co' <- dsHsWrapper co
347 ; let rhs' = co' (Var var)
348 ; return (mkCoLetMatchResult (NonRec var' rhs') match_result) }
349 matchCoercion _ _ _ = panic "matchCoercion"
351 matchView :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
352 -- Apply the view function to the match variable and then match that
353 matchView (var:vars) ty (eqns@(eqn1:_))
354 = do { -- we could pass in the expr from the PgView,
355 -- but this needs to extract the pat anyway
356 -- to figure out the type of the fresh variable
357 let ViewPat viewExpr (L _ pat) _ = firstPat eqn1
358 -- do the rest of the compilation
359 ; var' <- newUniqueId var (hsPatType pat)
360 ; match_result <- match (var':vars) ty $
361 map (decomposeFirstPat getViewPat) eqns
362 -- compile the view expressions
363 ; viewExpr' <- dsLExpr viewExpr
364 ; return (mkViewMatchResult var' viewExpr' var match_result) }
365 matchView _ _ _ = panic "matchView"
367 -- decompose the first pattern and leave the rest alone
368 decomposeFirstPat :: (Pat Id -> Pat Id) -> EquationInfo -> EquationInfo
369 decomposeFirstPat extractpat (eqn@(EqnInfo { eqn_pats = pat : pats }))
370 = eqn { eqn_pats = extractpat pat : pats}
371 decomposeFirstPat _ _ = panic "decomposeFirstPat"
373 getCoPat, getBangPat, getViewPat :: Pat Id -> Pat Id
374 getCoPat (CoPat _ pat _) = pat
375 getCoPat _ = panic "getCoPat"
376 getBangPat (BangPat pat ) = unLoc pat
377 getBangPat _ = panic "getBangPat"
378 getViewPat (ViewPat _ pat _) = unLoc pat
379 getViewPat _ = panic "getBangPat"
382 %************************************************************************
386 %************************************************************************
388 Tidy up the leftmost pattern in an @EquationInfo@, given the variable @v@
389 which will be scrutinised. This means:
392 Replace variable patterns @x@ (@x /= v@) with the pattern @_@,
393 together with the binding @x = v@.
395 Replace the `as' pattern @x@@p@ with the pattern p and a binding @x = v@.
397 Removing lazy (irrefutable) patterns (you don't want to know...).
399 Converting explicit tuple-, list-, and parallel-array-pats into ordinary
402 Convert the literal pat "" to [].
405 The result of this tidying is that the column of patterns will include
409 The @VarPat@ information isn't needed any more after this.
412 @ListPats@, @TuplePats@, etc., are all converted into @ConPats@.
414 \item[@LitPats@ and @NPats@:]
415 @LitPats@/@NPats@ of ``known friendly types'' (Int, Char,
416 Float, Double, at least) are converted to unboxed form; e.g.,
417 \tr{(NPat (HsInt i) _ _)} is converted to:
419 (ConPat I# _ _ [LitPat (HsIntPrim i)])
424 tidyEqnInfo :: Id -> EquationInfo
425 -> DsM (DsWrapper, EquationInfo)
426 -- DsM'd because of internal call to dsLHsBinds
427 -- and mkSelectorBinds.
428 -- "tidy1" does the interesting stuff, looking at
429 -- one pattern and fiddling the list of bindings.
431 -- POST CONDITION: head pattern in the EqnInfo is
439 tidyEqnInfo _ (EqnInfo { eqn_pats = [] })
440 = panic "tidyEqnInfo"
442 tidyEqnInfo v eqn@(EqnInfo { eqn_pats = pat : pats })
443 = do { (wrap, pat') <- tidy1 v pat
444 ; return (wrap, eqn { eqn_pats = do pat' : pats }) }
446 tidy1 :: Id -- The Id being scrutinised
447 -> Pat Id -- The pattern against which it is to be matched
448 -> DsM (DsWrapper, -- Extra bindings to do before the match
449 Pat Id) -- Equivalent pattern
451 -------------------------------------------------------
452 -- (pat', mr') = tidy1 v pat mr
453 -- tidies the *outer level only* of pat, giving pat'
454 -- It eliminates many pattern forms (as-patterns, variable patterns,
455 -- list patterns, etc) yielding one of:
462 tidy1 v (ParPat pat) = tidy1 v (unLoc pat)
463 tidy1 v (SigPatOut pat _) = tidy1 v (unLoc pat)
464 tidy1 _ (WildPat ty) = return (idDsWrapper, WildPat ty)
466 -- case v of { x -> mr[] }
467 -- = case v of { _ -> let x=v in mr[] }
469 = return (wrapBind var v, WildPat (idType var))
471 tidy1 v (VarPatOut var binds)
472 = do { ds_ev_binds <- dsTcEvBinds binds
473 ; return (wrapBind var v . wrapDsEvBinds ds_ev_binds,
474 WildPat (idType var)) }
476 -- case v of { x@p -> mr[] }
477 -- = case v of { p -> let x=v in mr[] }
478 tidy1 v (AsPat (L _ var) pat)
479 = do { (wrap, pat') <- tidy1 v (unLoc pat)
480 ; return (wrapBind var v . wrap, pat') }
482 {- now, here we handle lazy patterns:
483 tidy1 v ~p bs = (v, v1 = case v of p -> v1 :
484 v2 = case v of p -> v2 : ... : bs )
486 where the v_i's are the binders in the pattern.
488 ToDo: in "v_i = ... -> v_i", are the v_i's really the same thing?
490 The case expr for v_i is just: match [v] [(p, [], \ x -> Var v_i)] any_expr
493 tidy1 v (LazyPat pat)
494 = do { sel_prs <- mkSelectorBinds pat (Var v)
495 ; let sel_binds = [NonRec b rhs | (b,rhs) <- sel_prs]
496 ; return (mkCoreLets sel_binds, WildPat (idType v)) }
498 tidy1 _ (ListPat pats ty)
499 = return (idDsWrapper, unLoc list_ConPat)
501 list_ty = mkListTy ty
502 list_ConPat = foldr (\ x y -> mkPrefixConPat consDataCon [x, y] list_ty)
506 -- Introduce fake parallel array constructors to be able to handle parallel
507 -- arrays with the existing machinery for constructor pattern
508 tidy1 _ (PArrPat pats ty)
509 = return (idDsWrapper, unLoc parrConPat)
512 parrConPat = mkPrefixConPat (parrFakeCon arity) pats (mkPArrTy ty)
514 tidy1 _ (TuplePat pats boxity ty)
515 = return (idDsWrapper, unLoc tuple_ConPat)
518 tuple_ConPat = mkPrefixConPat (tupleCon boxity arity) pats ty
520 -- LitPats: we *might* be able to replace these w/ a simpler form
522 = return (idDsWrapper, tidyLitPat lit)
524 -- NPats: we *might* be able to replace these w/ a simpler form
525 tidy1 _ (NPat lit mb_neg eq)
526 = return (idDsWrapper, tidyNPat lit mb_neg eq)
528 -- BangPatterns: Pattern matching is already strict in constructors,
529 -- tuples etc, so the last case strips off the bang for thoses patterns.
530 tidy1 v (BangPat (L _ (LazyPat p))) = tidy1 v (BangPat p)
531 tidy1 v (BangPat (L _ (ParPat p))) = tidy1 v (BangPat p)
532 tidy1 _ p@(BangPat (L _(VarPat _))) = return (idDsWrapper, p)
533 tidy1 _ p@(BangPat (L _(VarPatOut _ _))) = return (idDsWrapper, p)
534 tidy1 _ p@(BangPat (L _ (WildPat _))) = return (idDsWrapper, p)
535 tidy1 _ p@(BangPat (L _ (CoPat _ _ _))) = return (idDsWrapper, p)
536 tidy1 _ p@(BangPat (L _ (SigPatIn _ _))) = return (idDsWrapper, p)
537 tidy1 _ p@(BangPat (L _ (SigPatOut _ _))) = return (idDsWrapper, p)
538 tidy1 v (BangPat (L _ (AsPat (L _ var) pat)))
539 = do { (wrap, pat') <- tidy1 v (BangPat pat)
540 ; return (wrapBind var v . wrap, pat') }
541 tidy1 v (BangPat (L _ p)) = tidy1 v p
543 -- Everything else goes through unchanged...
545 tidy1 _ non_interesting_pat
546 = return (idDsWrapper, non_interesting_pat)
550 {\bf Previous @matchTwiddled@ stuff:}
552 Now we get to the only interesting part; note: there are choices for
553 translation [from Simon's notes]; translation~1:
560 s = case w of [s,t] -> s
561 t = case w of [s,t] -> t
565 Here \tr{w} is a fresh variable, and the \tr{w}-binding prevents multiple
566 evaluation of \tr{e}. An alternative translation (No.~2):
568 [ w = case e of [s,t] -> (s,t)
569 s = case w of (s,t) -> s
570 t = case w of (s,t) -> t
574 %************************************************************************
576 \subsubsection[improved-unmixing]{UNIMPLEMENTED idea for improved unmixing}
578 %************************************************************************
580 We might be able to optimise unmixing when confronted by
581 only-one-constructor-possible, of which tuples are the most notable
589 This definition would normally be unmixed into four equation blocks,
590 one per equation. But it could be unmixed into just one equation
591 block, because if the one equation matches (on the first column),
592 the others certainly will.
594 You have to be careful, though; the example
602 {\em must} be broken into two blocks at the line shown; otherwise, you
603 are forcing unnecessary evaluation. In any case, the top-left pattern
604 always gives the cue. You could then unmix blocks into groups of...
606 \item[all variables:]
608 \item[constructors or variables (mixed):]
609 Need to make sure the right names get bound for the variable patterns.
610 \item[literals or variables (mixed):]
611 Presumably just a variant on the constructor case (as it is now).
614 %************************************************************************
616 %* matchWrapper: a convenient way to call @match@ *
618 %************************************************************************
619 \subsection[matchWrapper]{@matchWrapper@: a convenient interface to @match@}
621 Calls to @match@ often involve similar (non-trivial) work; that work
622 is collected here, in @matchWrapper@. This function takes as
626 Typchecked @Matches@ (of a function definition, or a case or lambda
627 expression)---the main input;
629 An error message to be inserted into any (runtime) pattern-matching
633 As results, @matchWrapper@ produces:
636 A list of variables (@Locals@) that the caller must ``promise'' to
637 bind to appropriate values; and
639 a @CoreExpr@, the desugared output (main result).
642 The main actions of @matchWrapper@ include:
645 Flatten the @[TypecheckedMatch]@ into a suitable list of
648 Create as many new variables as there are patterns in a pattern-list
649 (in any one of the @EquationInfo@s).
651 Create a suitable ``if it fails'' expression---a call to @error@ using
652 the error-string input; the {\em type} of this fail value can be found
653 by examining one of the RHS expressions in one of the @EquationInfo@s.
655 Call @match@ with all of this information!
659 matchWrapper :: HsMatchContext Name -- For shadowing warning messages
660 -> MatchGroup Id -- Matches being desugared
661 -> DsM ([Id], CoreExpr) -- Results
664 There is one small problem with the Lambda Patterns, when somebody
665 writes something similar to:
669 he/she don't want a warning about incomplete patterns, that is done with
670 the flag @opt_WarnSimplePatterns@.
671 This problem also appears in the:
673 \item @do@ patterns, but if the @do@ can fail
674 it creates another equation if the match can fail
675 (see @DsExpr.doDo@ function)
676 \item @let@ patterns, are treated by @matchSimply@
677 List Comprension Patterns, are treated by @matchSimply@ also
680 We can't call @matchSimply@ with Lambda patterns,
681 due to the fact that lambda patterns can have more than
682 one pattern, and match simply only accepts one pattern.
687 matchWrapper ctxt (MatchGroup matches match_ty)
688 = ASSERT( notNull matches )
689 do { eqns_info <- mapM mk_eqn_info matches
690 ; new_vars <- selectMatchVars arg_pats
691 ; result_expr <- matchEquations ctxt new_vars eqns_info rhs_ty
692 ; return (new_vars, result_expr) }
694 arg_pats = map unLoc (hsLMatchPats (head matches))
695 n_pats = length arg_pats
696 (_, rhs_ty) = splitFunTysN n_pats match_ty
698 mk_eqn_info (L _ (Match pats _ grhss))
699 = do { let upats = map unLoc pats
700 ; match_result <- dsGRHSs ctxt upats grhss rhs_ty
701 ; return (EqnInfo { eqn_pats = upats, eqn_rhs = match_result}) }
704 matchEquations :: HsMatchContext Name
705 -> [Id] -> [EquationInfo] -> Type
707 matchEquations ctxt vars eqns_info rhs_ty
708 = do { locn <- getSrcSpanDs
709 ; let ds_ctxt = DsMatchContext ctxt locn
710 error_doc = matchContextErrString ctxt
712 ; match_result <- matchCheck ds_ctxt vars rhs_ty eqns_info
714 ; fail_expr <- mkErrorAppDs pAT_ERROR_ID rhs_ty error_doc
715 ; extractMatchResult match_result fail_expr }
718 %************************************************************************
720 \subsection[matchSimply]{@matchSimply@: match a single expression against a single pattern}
722 %************************************************************************
724 @mkSimpleMatch@ is a wrapper for @match@ which deals with the
725 situation where we want to match a single expression against a single
726 pattern. It returns an expression.
729 matchSimply :: CoreExpr -- Scrutinee
730 -> HsMatchContext Name -- Match kind
731 -> LPat Id -- Pattern it should match
732 -> CoreExpr -- Return this if it matches
733 -> CoreExpr -- Return this if it doesn't
735 -- Do not warn about incomplete patterns; see matchSinglePat comments
736 matchSimply scrut hs_ctx pat result_expr fail_expr = do
738 match_result = cantFailMatchResult result_expr
739 rhs_ty = exprType fail_expr
740 -- Use exprType of fail_expr, because won't refine in the case of failure!
741 match_result' <- matchSinglePat scrut hs_ctx pat rhs_ty match_result
742 extractMatchResult match_result' fail_expr
745 matchSinglePat :: CoreExpr -> HsMatchContext Name -> LPat Id
746 -> Type -> MatchResult -> DsM MatchResult
747 -- Do not warn about incomplete patterns
748 -- Used for things like [ e | pat <- stuff ], where
749 -- incomplete patterns are just fine
750 matchSinglePat (Var var) _ (L _ pat) ty match_result
751 = match [var] ty [EqnInfo { eqn_pats = [pat], eqn_rhs = match_result }]
753 matchSinglePat scrut hs_ctx pat ty match_result = do
754 var <- selectSimpleMatchVarL pat
755 match_result' <- matchSinglePat (Var var) hs_ctx pat ty match_result
756 return (adjustMatchResult (bindNonRec var scrut) match_result')
760 %************************************************************************
762 Pattern classification
764 %************************************************************************
768 = PgAny -- Immediate match: variables, wildcards,
770 | PgCon DataCon -- Constructor patterns (incl list, tuple)
771 | PgLit Literal -- Literal patterns
772 | PgN Literal -- Overloaded literals
773 | PgNpK Literal -- n+k patterns
774 | PgBang -- Bang patterns
775 | PgCo Type -- Coercion patterns; the type is the type
776 -- of the pattern *inside*
777 | PgView (LHsExpr Id) -- view pattern (e -> p):
778 -- the LHsExpr is the expression e
779 Type -- the Type is the type of p (equivalently, the result type of e)
781 groupEquations :: [EquationInfo] -> [[(PatGroup, EquationInfo)]]
782 -- If the result is of form [g1, g2, g3],
783 -- (a) all the (pg,eq) pairs in g1 have the same pg
784 -- (b) none of the gi are empty
785 -- The ordering of equations is unchanged
787 = runs same_gp [(patGroup (firstPat eqn), eqn) | eqn <- eqns]
789 same_gp :: (PatGroup,EquationInfo) -> (PatGroup,EquationInfo) -> Bool
790 (pg1,_) `same_gp` (pg2,_) = pg1 `sameGroup` pg2
792 subGroup :: Ord a => [(a, EquationInfo)] -> [[EquationInfo]]
793 -- Input is a particular group. The result sub-groups the
794 -- equations by with particular constructor, literal etc they match.
795 -- Each sub-list in the result has the same PatGroup
796 -- See Note [Take care with pattern order]
798 = map reverse $ Map.elems $ foldl accumulate Map.empty group
800 accumulate pg_map (pg, eqn)
801 = case Map.lookup pg pg_map of
802 Just eqns -> Map.insert pg (eqn:eqns) pg_map
803 Nothing -> Map.insert pg [eqn] pg_map
805 -- pg_map :: Map a [EquationInfo]
806 -- Equations seen so far in reverse order of appearance
809 Note [Take care with pattern order]
810 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
811 In the subGroup function we must be very careful about pattern re-ordering,
812 Consider the patterns [ (True, Nothing), (False, x), (True, y) ]
813 Then in bringing together the patterns for True, we must not
814 swap the Nothing and y!
818 sameGroup :: PatGroup -> PatGroup -> Bool
819 -- Same group means that a single case expression
820 -- or test will suffice to match both, *and* the order
821 -- of testing within the group is insignificant.
822 sameGroup PgAny PgAny = True
823 sameGroup PgBang PgBang = True
824 sameGroup (PgCon _) (PgCon _) = True -- One case expression
825 sameGroup (PgLit _) (PgLit _) = True -- One case expression
826 sameGroup (PgN l1) (PgN l2) = l1==l2 -- Order is significant
827 sameGroup (PgNpK l1) (PgNpK l2) = l1==l2 -- See Note [Grouping overloaded literal patterns]
828 sameGroup (PgCo t1) (PgCo t2) = t1 `coreEqType` t2
829 -- CoPats are in the same goup only if the type of the
830 -- enclosed pattern is the same. The patterns outside the CoPat
831 -- always have the same type, so this boils down to saying that
832 -- the two coercions are identical.
833 sameGroup (PgView e1 t1) (PgView e2 t2) = viewLExprEq (e1,t1) (e2,t2)
834 -- ViewPats are in the same gorup iff the expressions
835 -- are "equal"---conservatively, we use syntactic equality
836 sameGroup _ _ = False
838 -- An approximation of syntactic equality used for determining when view
839 -- exprs are in the same group.
840 -- This function can always safely return false;
841 -- but doing so will result in the application of the view function being repeated.
843 -- Currently: compare applications of literals and variables
844 -- and anything else that we can do without involving other
845 -- HsSyn types in the recursion
847 -- NB we can't assume that the two view expressions have the same type. Consider
848 -- f (e1 -> True) = ...
849 -- f (e2 -> "hi") = ...
850 viewLExprEq :: (LHsExpr Id,Type) -> (LHsExpr Id,Type) -> Bool
851 viewLExprEq (e1,_) (e2,_) = lexp e1 e2
853 lexp :: LHsExpr Id -> LHsExpr Id -> Bool
854 lexp e e' = exp (unLoc e) (unLoc e')
857 exp :: HsExpr Id -> HsExpr Id -> Bool
858 -- real comparison is on HsExpr's
860 exp (HsPar (L _ e)) e' = exp e e'
861 exp e (HsPar (L _ e')) = exp e e'
862 -- because the expressions do not necessarily have the same type,
863 -- we have to compare the wrappers
864 exp (HsWrap h e) (HsWrap h' e') = wrap h h' && exp e e'
865 exp (HsVar i) (HsVar i') = i == i'
866 -- the instance for IPName derives using the id, so this works if the
868 exp (HsIPVar i) (HsIPVar i') = i == i'
869 exp (HsOverLit l) (HsOverLit l') =
870 -- Overloaded lits are equal if they have the same type
871 -- and the data is the same.
872 -- this is coarser than comparing the SyntaxExpr's in l and l',
873 -- which resolve the overloading (e.g., fromInteger 1),
874 -- because these expressions get written as a bunch of different variables
875 -- (presumably to improve sharing)
876 tcEqType (overLitType l) (overLitType l') && l == l'
877 exp (HsApp e1 e2) (HsApp e1' e2') = lexp e1 e1' && lexp e2 e2'
878 -- the fixities have been straightened out by now, so it's safe
880 exp (OpApp l o _ ri) (OpApp l' o' _ ri') =
881 lexp l l' && lexp o o' && lexp ri ri'
882 exp (NegApp e n) (NegApp e' n') = lexp e e' && exp n n'
883 exp (SectionL e1 e2) (SectionL e1' e2') =
884 lexp e1 e1' && lexp e2 e2'
885 exp (SectionR e1 e2) (SectionR e1' e2') =
886 lexp e1 e1' && lexp e2 e2'
887 exp (ExplicitTuple es1 _) (ExplicitTuple es2 _) =
888 eq_list tup_arg es1 es2
889 exp (HsIf e e1 e2) (HsIf e' e1' e2') =
890 lexp e e' && lexp e1 e1' && lexp e2 e2'
892 -- Enhancement: could implement equality for more expressions
893 -- if it seems useful
894 -- But no need for HsLit, ExplicitList, ExplicitTuple,
895 -- because they cannot be functions
899 tup_arg (Present e1) (Present e2) = lexp e1 e2
900 tup_arg (Missing t1) (Missing t2) = tcEqType t1 t2
904 wrap :: HsWrapper -> HsWrapper -> Bool
905 -- Conservative, in that it demands that wrappers be
906 -- syntactically identical and doesn't look under binders
908 -- Coarser notions of equality are possible
909 -- (e.g., reassociating compositions,
910 -- equating different ways of writing a coercion)
911 wrap WpHole WpHole = True
912 wrap (WpCompose w1 w2) (WpCompose w1' w2') = wrap w1 w1' && wrap w2 w2'
913 wrap (WpCast c) (WpCast c') = tcEqType c c'
914 wrap (WpEvApp et1) (WpEvApp et2) = ev_term et1 et2
915 wrap (WpTyApp t) (WpTyApp t') = tcEqType t t'
916 -- Enhancement: could implement equality for more wrappers
917 -- if it seems useful (lams and lets)
921 ev_term :: EvTerm -> EvTerm -> Bool
922 ev_term (EvId a) (EvId b) = a==b
923 ev_term (EvCoercion a) (EvCoercion b) = tcEqType a b
927 eq_list :: (a->a->Bool) -> [a] -> [a] -> Bool
928 eq_list _ [] [] = True
929 eq_list _ [] (_:_) = False
930 eq_list _ (_:_) [] = False
931 eq_list eq (x:xs) (y:ys) = eq x y && eq_list eq xs ys
933 patGroup :: Pat Id -> PatGroup
934 patGroup (WildPat {}) = PgAny
935 patGroup (BangPat {}) = PgBang
936 patGroup (ConPatOut { pat_con = dc }) = PgCon (unLoc dc)
937 patGroup (LitPat lit) = PgLit (hsLitKey lit)
938 patGroup (NPat olit mb_neg _) = PgN (hsOverLitKey olit (isJust mb_neg))
939 patGroup (NPlusKPat _ olit _ _) = PgNpK (hsOverLitKey olit False)
940 patGroup (CoPat _ p _) = PgCo (hsPatType p) -- Type of innelexp pattern
941 patGroup (ViewPat expr p _) = PgView expr (hsPatType (unLoc p))
942 patGroup pat = pprPanic "patGroup" (ppr pat)
945 Note [Grouping overloaded literal patterns]
946 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
953 We can't group the first and third together, because the second may match
954 the same thing as the first. Same goes for *overloaded* literal patterns
958 If the first arg matches '1' but the second does not match 'True', we
959 cannot jump to the third equation! Because the same argument might
961 Hence we don't regard 1 and 2, or (n+1) and (n+2), as part of the same group.