2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
9 {-# OPTIONS -fno-warn-incomplete-patterns #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
16 module Match ( match, matchEquations, matchWrapper, matchSimply, matchSinglePat ) where
18 #include "HsVersions.h"
20 import {-#SOURCE#-} DsExpr (dsLExpr)
51 This function is a wrapper of @match@, it must be called from all the parts where
52 it was called match, but only substitutes the firs call, ....
53 if the associated flags are declared, warnings will be issued.
54 It can not be called matchWrapper because this name already exists :-(
59 matchCheck :: DsMatchContext
60 -> [Id] -- Vars rep'ing the exprs we're matching with
61 -> Type -- Type of the case expression
62 -> [EquationInfo] -- Info about patterns, etc. (type synonym below)
63 -> DsM MatchResult -- Desugared result!
65 matchCheck ctx vars ty qs = do
67 matchCheck_really dflags ctx vars ty qs
69 matchCheck_really :: DynFlags
75 matchCheck_really dflags ctx vars ty qs
76 | incomplete && shadow = do
77 dsShadowWarn ctx eqns_shadow
78 dsIncompleteWarn ctx pats
81 dsIncompleteWarn ctx pats
84 dsShadowWarn ctx eqns_shadow
88 where (pats, eqns_shadow) = check qs
89 incomplete = want_incomplete && (notNull pats)
90 want_incomplete = case ctx of
91 DsMatchContext RecUpd _ ->
92 dopt Opt_WarnIncompletePatternsRecUpd dflags
94 dopt Opt_WarnIncompletePatterns dflags
95 shadow = dopt Opt_WarnOverlappingPatterns dflags
96 && not (null eqns_shadow)
99 This variable shows the maximum number of lines of output generated for warnings.
100 It will limit the number of patterns/equations displayed to@ maximum_output@.
102 (ToDo: add command-line option?)
105 maximum_output :: Int
109 The next two functions create the warning message.
112 dsShadowWarn :: DsMatchContext -> [EquationInfo] -> DsM ()
113 dsShadowWarn ctx@(DsMatchContext kind loc) qs
114 = putSrcSpanDs loc (warnDs warn)
116 warn | qs `lengthExceeds` maximum_output
117 = pp_context ctx (ptext (sLit "are overlapped"))
118 (\ f -> vcat (map (ppr_eqn f kind) (take maximum_output qs)) $$
121 = pp_context ctx (ptext (sLit "are overlapped"))
122 (\ f -> vcat $ map (ppr_eqn f kind) qs)
125 dsIncompleteWarn :: DsMatchContext -> [ExhaustivePat] -> DsM ()
126 dsIncompleteWarn ctx@(DsMatchContext kind loc) pats
127 = putSrcSpanDs loc (warnDs warn)
129 warn = pp_context ctx (ptext (sLit "are non-exhaustive"))
130 (\_ -> hang (ptext (sLit "Patterns not matched:"))
131 4 ((vcat $ map (ppr_incomplete_pats kind)
132 (take maximum_output pats))
135 dots | pats `lengthExceeds` maximum_output = ptext (sLit "...")
138 pp_context :: DsMatchContext -> SDoc -> ((SDoc -> SDoc) -> SDoc) -> SDoc
139 pp_context (DsMatchContext kind _loc) msg rest_of_msg_fun
140 = vcat [ptext (sLit "Pattern match(es)") <+> msg,
141 sep [ptext (sLit "In") <+> ppr_match <> char ':', nest 4 (rest_of_msg_fun pref)]]
145 FunRhs fun _ -> (pprMatchContext kind, \ pp -> ppr fun <+> pp)
146 _ -> (pprMatchContext kind, \ pp -> pp)
148 ppr_pats :: Outputable a => [a] -> SDoc
149 ppr_pats pats = sep (map ppr pats)
151 ppr_shadow_pats :: HsMatchContext Name -> [Pat Id] -> SDoc
152 ppr_shadow_pats kind pats
153 = sep [ppr_pats pats, matchSeparator kind, ptext (sLit "...")]
155 ppr_incomplete_pats :: HsMatchContext Name -> ExhaustivePat -> SDoc
156 ppr_incomplete_pats _ (pats,[]) = ppr_pats pats
157 ppr_incomplete_pats _ (pats,constraints) =
158 sep [ppr_pats pats, ptext (sLit "with"),
159 sep (map ppr_constraint constraints)]
161 ppr_constraint :: (Name,[HsLit]) -> SDoc
162 ppr_constraint (var,pats) = sep [ppr var, ptext (sLit "`notElem`"), ppr pats]
164 ppr_eqn :: (SDoc -> SDoc) -> HsMatchContext Name -> EquationInfo -> SDoc
165 ppr_eqn prefixF kind eqn = prefixF (ppr_shadow_pats kind (eqn_pats eqn))
169 %************************************************************************
171 The main matching function
173 %************************************************************************
175 The function @match@ is basically the same as in the Wadler chapter,
176 except it is monadised, to carry around the name supply, info about
179 Notes on @match@'s arguments, assuming $m$ equations and $n$ patterns:
182 A list of $n$ variable names, those variables presumably bound to the
183 $n$ expressions being matched against the $n$ patterns. Using the
184 list of $n$ expressions as the first argument showed no benefit and
188 The second argument, a list giving the ``equation info'' for each of
192 the $n$ patterns for that equation, and
194 a list of Core bindings [@(Id, CoreExpr)@ pairs] to be ``stuck on
195 the front'' of the matching code, as in:
201 and finally: (ToDo: fill in)
203 The right way to think about the ``after-match function'' is that it
204 is an embryonic @CoreExpr@ with a ``hole'' at the end for the
205 final ``else expression''.
208 There is a type synonym, @EquationInfo@, defined in module @DsUtils@.
210 An experiment with re-ordering this information about equations (in
211 particular, having the patterns available in column-major order)
215 A default expression---what to evaluate if the overall pattern-match
216 fails. This expression will (almost?) always be
217 a measly expression @Var@, unless we know it will only be used once
218 (as we do in @glue_success_exprs@).
220 Leaving out this third argument to @match@ (and slamming in lots of
221 @Var "fail"@s) is a positively {\em bad} idea, because it makes it
222 impossible to share the default expressions. (Also, it stands no
223 chance of working in our post-upheaval world of @Locals@.)
226 Note: @match@ is often called via @matchWrapper@ (end of this module),
227 a function that does much of the house-keeping that goes with a call
230 It is also worth mentioning the {\em typical} way a block of equations
231 is desugared with @match@. At each stage, it is the first column of
232 patterns that is examined. The steps carried out are roughly:
235 Tidy the patterns in column~1 with @tidyEqnInfo@ (this may add
236 bindings to the second component of the equation-info):
239 Remove the `as' patterns from column~1.
241 Make all constructor patterns in column~1 into @ConPats@, notably
242 @ListPats@ and @TuplePats@.
244 Handle any irrefutable (or ``twiddle'') @LazyPats@.
247 Now {\em unmix} the equations into {\em blocks} [w\/ local function
248 @unmix_eqns@], in which the equations in a block all have variable
249 patterns in column~1, or they all have constructor patterns in ...
250 (see ``the mixture rule'' in SLPJ).
252 Call @matchEqnBlock@ on each block of equations; it will do the
253 appropriate thing for each kind of column-1 pattern, usually ending up
254 in a recursive call to @match@.
257 We are a little more paranoid about the ``empty rule'' (SLPJ, p.~87)
258 than the Wadler-chapter code for @match@ (p.~93, first @match@ clause).
259 And gluing the ``success expressions'' together isn't quite so pretty.
261 This (more interesting) clause of @match@ uses @tidy_and_unmix_eqns@
262 (a)~to get `as'- and `twiddle'-patterns out of the way (tidying), and
263 (b)~to do ``the mixture rule'' (SLPJ, p.~88) [which really {\em
264 un}mixes the equations], producing a list of equation-info
265 blocks, each block having as its first column of patterns either all
266 constructors, or all variables (or similar beasts), etc.
268 @match_unmixed_eqn_blks@ simply takes the place of the @foldr@ in the
269 Wadler-chapter @match@ (p.~93, last clause), and @match_unmixed_blk@
270 corresponds roughly to @matchVarCon@.
273 match :: [Id] -- Variables rep\'ing the exprs we\'re matching with
274 -> Type -- Type of the case expression
275 -> [EquationInfo] -- Info about patterns, etc. (type synonym below)
276 -> DsM MatchResult -- Desugared result!
279 = ASSERT2( not (null eqns), ppr ty )
280 return (foldr1 combineMatchResults match_results)
282 match_results = [ ASSERT( null (eqn_pats eqn) )
286 match vars@(v:_) ty eqns
287 = ASSERT( not (null eqns ) )
288 do { -- Tidy the first pattern, generating
289 -- auxiliary bindings if necessary
290 (aux_binds, tidy_eqns) <- mapAndUnzipM (tidyEqnInfo v) eqns
292 -- Group the equations and match each group in turn
293 ; let grouped = groupEquations tidy_eqns
295 -- print the view patterns that are commoned up to help debug
296 ; ifOptM Opt_D_dump_view_pattern_commoning (debug grouped)
298 ; match_results <- mapM match_group grouped
299 ; return (adjustMatchResult (foldr1 (.) aux_binds) $
300 foldr1 combineMatchResults match_results) }
302 dropGroup :: [(PatGroup,EquationInfo)] -> [EquationInfo]
305 match_group :: [(PatGroup,EquationInfo)] -> DsM MatchResult
306 match_group eqns@((group,_) : _)
308 PgCon _ -> matchConFamily vars ty (subGroup [(c,e) | (PgCon c, e) <- eqns])
309 PgLit _ -> matchLiterals vars ty (subGroup [(l,e) | (PgLit l, e) <- eqns])
311 PgAny -> matchVariables vars ty (dropGroup eqns)
312 PgN _ -> matchNPats vars ty (dropGroup eqns)
313 PgNpK _ -> matchNPlusKPats vars ty (dropGroup eqns)
314 PgBang -> matchBangs vars ty (dropGroup eqns)
315 PgCo _ -> matchCoercion vars ty (dropGroup eqns)
316 PgView _ _ -> matchView vars ty (dropGroup eqns)
318 -- FIXME: we should also warn about view patterns that should be
319 -- commoned up but are not
321 -- print some stuff to see what's getting grouped
322 -- use -dppr-debug to see the resolution of overloaded lits
324 let gs = map (\group -> foldr (\ (p,_) -> \acc ->
325 case p of PgView e _ -> e:acc
326 _ -> acc) [] group) eqns
327 maybeWarn [] = return ()
328 maybeWarn l = warnDs (vcat l)
330 maybeWarn $ (map (\g -> text "Putting these view expressions into the same case:" <+> (ppr g))
331 (filter (not . null) gs))
333 matchVariables :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
334 -- Real true variables, just like in matchVar, SLPJ p 94
335 -- No binding to do: they'll all be wildcards by now (done in tidy)
336 matchVariables (_:vars) ty eqns = match vars ty (shiftEqns eqns)
338 matchBangs :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
339 matchBangs (var:vars) ty eqns
340 = do { match_result <- match (var:vars) ty (map decomposeFirst_Bang eqns)
341 ; return (mkEvalMatchResult var ty match_result) }
343 matchCoercion :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
344 -- Apply the coercion to the match variable and then match that
345 matchCoercion (var:vars) ty (eqns@(eqn1:_))
346 = do { let CoPat co pat _ = firstPat eqn1
347 ; var' <- newUniqueId (idName var) (hsPatType pat)
348 ; match_result <- match (var':vars) ty (map decomposeFirst_Coercion eqns)
349 ; rhs <- dsCoercion co (return (Var var))
350 ; return (mkCoLetMatchResult (NonRec var' rhs) match_result) }
352 matchView :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
353 -- Apply the view function to the match variable and then match that
354 matchView (var:vars) ty (eqns@(eqn1:_))
355 = do { -- we could pass in the expr from the PgView,
356 -- but this needs to extract the pat anyway
357 -- to figure out the type of the fresh variable
358 let ViewPat viewExpr (L _ pat) _ = firstPat eqn1
359 -- do the rest of the compilation
360 ; var' <- newUniqueId (idName var) (hsPatType pat)
361 ; match_result <- match (var':vars) ty (map decomposeFirst_View eqns)
362 -- compile the view expressions
363 ; viewExpr' <- dsLExpr viewExpr
364 ; return (mkViewMatchResult var' viewExpr' var match_result) }
366 -- decompose the first pattern and leave the rest alone
367 decomposeFirstPat :: (Pat Id -> Pat Id) -> EquationInfo -> EquationInfo
368 decomposeFirstPat extractpat (eqn@(EqnInfo { eqn_pats = pat : pats }))
369 = eqn { eqn_pats = extractpat pat : pats}
371 decomposeFirst_Coercion, decomposeFirst_Bang, decomposeFirst_View :: EquationInfo -> EquationInfo
373 decomposeFirst_Coercion = decomposeFirstPat (\ (CoPat _ pat _) -> pat)
374 decomposeFirst_Bang = decomposeFirstPat (\ (BangPat pat ) -> unLoc pat)
375 decomposeFirst_View = decomposeFirstPat (\ (ViewPat _ pat _) -> unLoc pat)
379 %************************************************************************
383 %************************************************************************
385 Tidy up the leftmost pattern in an @EquationInfo@, given the variable @v@
386 which will be scrutinised. This means:
389 Replace variable patterns @x@ (@x /= v@) with the pattern @_@,
390 together with the binding @x = v@.
392 Replace the `as' pattern @x@@p@ with the pattern p and a binding @x = v@.
394 Removing lazy (irrefutable) patterns (you don't want to know...).
396 Converting explicit tuple-, list-, and parallel-array-pats into ordinary
399 Convert the literal pat "" to [].
402 The result of this tidying is that the column of patterns will include
406 The @VarPat@ information isn't needed any more after this.
409 @ListPats@, @TuplePats@, etc., are all converted into @ConPats@.
411 \item[@LitPats@ and @NPats@:]
412 @LitPats@/@NPats@ of ``known friendly types'' (Int, Char,
413 Float, Double, at least) are converted to unboxed form; e.g.,
414 \tr{(NPat (HsInt i) _ _)} is converted to:
416 (ConPat I# _ _ [LitPat (HsIntPrim i)])
421 tidyEqnInfo :: Id -> EquationInfo
422 -> DsM (DsWrapper, EquationInfo)
423 -- DsM'd because of internal call to dsLHsBinds
424 -- and mkSelectorBinds.
425 -- "tidy1" does the interesting stuff, looking at
426 -- one pattern and fiddling the list of bindings.
428 -- POST CONDITION: head pattern in the EqnInfo is
436 tidyEqnInfo v eqn@(EqnInfo { eqn_pats = pat : pats }) = do
437 (wrap, pat') <- tidy1 v pat
438 return (wrap, eqn { eqn_pats = do pat' : pats })
440 tidy1 :: Id -- The Id being scrutinised
441 -> Pat Id -- The pattern against which it is to be matched
442 -> DsM (DsWrapper, -- Extra bindings to do before the match
443 Pat Id) -- Equivalent pattern
445 -------------------------------------------------------
446 -- (pat', mr') = tidy1 v pat mr
447 -- tidies the *outer level only* of pat, giving pat'
448 -- It eliminates many pattern forms (as-patterns, variable patterns,
449 -- list patterns, etc) yielding one of:
456 tidy1 v (ParPat pat) = tidy1 v (unLoc pat)
457 tidy1 v (SigPatOut pat _) = tidy1 v (unLoc pat)
458 tidy1 _ (WildPat ty) = return (idDsWrapper, WildPat ty)
460 -- case v of { x -> mr[] }
461 -- = case v of { _ -> let x=v in mr[] }
463 = return (wrapBind var v, WildPat (idType var))
465 tidy1 v (VarPatOut var binds)
466 = do { prs <- dsLHsBinds binds
467 ; return (wrapBind var v . mkCoreLet (Rec prs),
468 WildPat (idType var)) }
470 -- case v of { x@p -> mr[] }
471 -- = case v of { p -> let x=v in mr[] }
472 tidy1 v (AsPat (L _ var) pat)
473 = do { (wrap, pat') <- tidy1 v (unLoc pat)
474 ; return (wrapBind var v . wrap, pat') }
476 {- now, here we handle lazy patterns:
477 tidy1 v ~p bs = (v, v1 = case v of p -> v1 :
478 v2 = case v of p -> v2 : ... : bs )
480 where the v_i's are the binders in the pattern.
482 ToDo: in "v_i = ... -> v_i", are the v_i's really the same thing?
484 The case expr for v_i is just: match [v] [(p, [], \ x -> Var v_i)] any_expr
487 tidy1 v (LazyPat pat)
488 = do { sel_prs <- mkSelectorBinds pat (Var v)
489 ; let sel_binds = [NonRec b rhs | (b,rhs) <- sel_prs]
490 ; return (mkCoreLets sel_binds, WildPat (idType v)) }
492 tidy1 _ (ListPat pats ty)
493 = return (idDsWrapper, unLoc list_ConPat)
495 list_ty = mkListTy ty
496 list_ConPat = foldr (\ x y -> mkPrefixConPat consDataCon [x, y] list_ty)
500 -- Introduce fake parallel array constructors to be able to handle parallel
501 -- arrays with the existing machinery for constructor pattern
502 tidy1 _ (PArrPat pats ty)
503 = return (idDsWrapper, unLoc parrConPat)
506 parrConPat = mkPrefixConPat (parrFakeCon arity) pats (mkPArrTy ty)
508 tidy1 _ (TuplePat pats boxity ty)
509 = return (idDsWrapper, unLoc tuple_ConPat)
512 tuple_ConPat = mkPrefixConPat (tupleCon boxity arity) pats ty
514 -- LitPats: we *might* be able to replace these w/ a simpler form
516 = return (idDsWrapper, tidyLitPat lit)
518 -- NPats: we *might* be able to replace these w/ a simpler form
519 tidy1 _ (NPat lit mb_neg eq)
520 = return (idDsWrapper, tidyNPat lit mb_neg eq)
522 -- Everything else goes through unchanged...
524 tidy1 _ non_interesting_pat
525 = return (idDsWrapper, non_interesting_pat)
529 {\bf Previous @matchTwiddled@ stuff:}
531 Now we get to the only interesting part; note: there are choices for
532 translation [from Simon's notes]; translation~1:
539 s = case w of [s,t] -> s
540 t = case w of [s,t] -> t
544 Here \tr{w} is a fresh variable, and the \tr{w}-binding prevents multiple
545 evaluation of \tr{e}. An alternative translation (No.~2):
547 [ w = case e of [s,t] -> (s,t)
548 s = case w of (s,t) -> s
549 t = case w of (s,t) -> t
553 %************************************************************************
555 \subsubsection[improved-unmixing]{UNIMPLEMENTED idea for improved unmixing}
557 %************************************************************************
559 We might be able to optimise unmixing when confronted by
560 only-one-constructor-possible, of which tuples are the most notable
568 This definition would normally be unmixed into four equation blocks,
569 one per equation. But it could be unmixed into just one equation
570 block, because if the one equation matches (on the first column),
571 the others certainly will.
573 You have to be careful, though; the example
581 {\em must} be broken into two blocks at the line shown; otherwise, you
582 are forcing unnecessary evaluation. In any case, the top-left pattern
583 always gives the cue. You could then unmix blocks into groups of...
585 \item[all variables:]
587 \item[constructors or variables (mixed):]
588 Need to make sure the right names get bound for the variable patterns.
589 \item[literals or variables (mixed):]
590 Presumably just a variant on the constructor case (as it is now).
593 %************************************************************************
595 %* matchWrapper: a convenient way to call @match@ *
597 %************************************************************************
598 \subsection[matchWrapper]{@matchWrapper@: a convenient interface to @match@}
600 Calls to @match@ often involve similar (non-trivial) work; that work
601 is collected here, in @matchWrapper@. This function takes as
605 Typchecked @Matches@ (of a function definition, or a case or lambda
606 expression)---the main input;
608 An error message to be inserted into any (runtime) pattern-matching
612 As results, @matchWrapper@ produces:
615 A list of variables (@Locals@) that the caller must ``promise'' to
616 bind to appropriate values; and
618 a @CoreExpr@, the desugared output (main result).
621 The main actions of @matchWrapper@ include:
624 Flatten the @[TypecheckedMatch]@ into a suitable list of
627 Create as many new variables as there are patterns in a pattern-list
628 (in any one of the @EquationInfo@s).
630 Create a suitable ``if it fails'' expression---a call to @error@ using
631 the error-string input; the {\em type} of this fail value can be found
632 by examining one of the RHS expressions in one of the @EquationInfo@s.
634 Call @match@ with all of this information!
638 matchWrapper :: HsMatchContext Name -- For shadowing warning messages
639 -> MatchGroup Id -- Matches being desugared
640 -> DsM ([Id], CoreExpr) -- Results
643 There is one small problem with the Lambda Patterns, when somebody
644 writes something similar to:
648 he/she don't want a warning about incomplete patterns, that is done with
649 the flag @opt_WarnSimplePatterns@.
650 This problem also appears in the:
652 \item @do@ patterns, but if the @do@ can fail
653 it creates another equation if the match can fail
654 (see @DsExpr.doDo@ function)
655 \item @let@ patterns, are treated by @matchSimply@
656 List Comprension Patterns, are treated by @matchSimply@ also
659 We can't call @matchSimply@ with Lambda patterns,
660 due to the fact that lambda patterns can have more than
661 one pattern, and match simply only accepts one pattern.
666 matchWrapper ctxt (MatchGroup matches match_ty)
667 = ASSERT( notNull matches )
668 do { eqns_info <- mapM mk_eqn_info matches
669 ; new_vars <- selectMatchVars arg_pats
670 ; result_expr <- matchEquations ctxt new_vars eqns_info rhs_ty
671 ; return (new_vars, result_expr) }
673 arg_pats = map unLoc (hsLMatchPats (head matches))
674 n_pats = length arg_pats
675 (_, rhs_ty) = splitFunTysN n_pats match_ty
677 mk_eqn_info (L _ (Match pats _ grhss))
678 = do { let upats = map unLoc pats
679 ; match_result <- dsGRHSs ctxt upats grhss rhs_ty
680 ; return (EqnInfo { eqn_pats = upats, eqn_rhs = match_result}) }
683 matchEquations :: HsMatchContext Name
684 -> [Id] -> [EquationInfo] -> Type
686 matchEquations ctxt vars eqns_info rhs_ty
687 = do { dflags <- getDOptsDs
688 ; locn <- getSrcSpanDs
689 ; let ds_ctxt = DsMatchContext ctxt locn
690 error_doc = matchContextErrString ctxt
692 ; match_result <- match_fun dflags ds_ctxt vars rhs_ty eqns_info
694 ; fail_expr <- mkErrorAppDs pAT_ERROR_ID rhs_ty error_doc
695 ; extractMatchResult match_result fail_expr }
697 match_fun dflags ds_ctxt
699 LambdaExpr | dopt Opt_WarnSimplePatterns dflags -> matchCheck ds_ctxt
701 _ -> matchCheck ds_ctxt
704 %************************************************************************
706 \subsection[matchSimply]{@matchSimply@: match a single expression against a single pattern}
708 %************************************************************************
710 @mkSimpleMatch@ is a wrapper for @match@ which deals with the
711 situation where we want to match a single expression against a single
712 pattern. It returns an expression.
715 matchSimply :: CoreExpr -- Scrutinee
716 -> HsMatchContext Name -- Match kind
717 -> LPat Id -- Pattern it should match
718 -> CoreExpr -- Return this if it matches
719 -> CoreExpr -- Return this if it doesn't
722 matchSimply scrut hs_ctx pat result_expr fail_expr = do
724 match_result = cantFailMatchResult result_expr
725 rhs_ty = exprType fail_expr
726 -- Use exprType of fail_expr, because won't refine in the case of failure!
727 match_result' <- matchSinglePat scrut hs_ctx pat rhs_ty match_result
728 extractMatchResult match_result' fail_expr
731 matchSinglePat :: CoreExpr -> HsMatchContext Name -> LPat Id
732 -> Type -> MatchResult -> DsM MatchResult
733 matchSinglePat (Var var) hs_ctx (L _ pat) ty match_result = do
738 | dopt Opt_WarnSimplePatterns dflags = matchCheck ds_ctx
741 ds_ctx = DsMatchContext hs_ctx locn
742 match_fn dflags [var] ty [EqnInfo { eqn_pats = [pat], eqn_rhs = match_result }]
744 matchSinglePat scrut hs_ctx pat ty match_result = do
745 var <- selectSimpleMatchVarL pat
746 match_result' <- matchSinglePat (Var var) hs_ctx pat ty match_result
747 return (adjustMatchResult (bindNonRec var scrut) match_result')
751 %************************************************************************
753 Pattern classification
755 %************************************************************************
759 = PgAny -- Immediate match: variables, wildcards,
761 | PgCon DataCon -- Constructor patterns (incl list, tuple)
762 | PgLit Literal -- Literal patterns
763 | PgN Literal -- Overloaded literals
764 | PgNpK Literal -- n+k patterns
765 | PgBang -- Bang patterns
766 | PgCo Type -- Coercion patterns; the type is the type
767 -- of the pattern *inside*
768 | PgView (LHsExpr Id) -- view pattern (e -> p):
769 -- the LHsExpr is the expression e
770 Type -- the Type is the type of p (equivalently, the result type of e)
772 groupEquations :: [EquationInfo] -> [[(PatGroup, EquationInfo)]]
773 -- If the result is of form [g1, g2, g3],
774 -- (a) all the (pg,eq) pairs in g1 have the same pg
775 -- (b) none of the gi are empty
776 -- The ordering of equations is unchanged
778 = runs same_gp [(patGroup (firstPat eqn), eqn) | eqn <- eqns]
780 same_gp :: (PatGroup,EquationInfo) -> (PatGroup,EquationInfo) -> Bool
781 (pg1,_) `same_gp` (pg2,_) = pg1 `sameGroup` pg2
783 subGroup :: Ord a => [(a, EquationInfo)] -> [[EquationInfo]]
784 -- Input is a particular group. The result sub-groups the
785 -- equations by with particular constructor, literal etc they match.
786 -- Each sub-list in the result has the same PatGroup
787 -- See Note [Take care with pattern order]
789 = map reverse $ eltsFM $ foldl accumulate emptyFM group
791 accumulate pg_map (pg, eqn)
792 = case lookupFM pg_map pg of
793 Just eqns -> addToFM pg_map pg (eqn:eqns)
794 Nothing -> addToFM pg_map pg [eqn]
796 -- pg_map :: FiniteMap a [EquationInfo]
797 -- Equations seen so far in reverse order of appearance
800 Note [Take care with pattern order]
801 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
802 In the subGroup function we must be very careful about pattern re-ordering,
803 Consider the patterns [ (True, Nothing), (False, x), (True, y) ]
804 Then in bringing together the patterns for True, we must not
805 swap the Nothing and y!
809 sameGroup :: PatGroup -> PatGroup -> Bool
810 -- Same group means that a single case expression
811 -- or test will suffice to match both, *and* the order
812 -- of testing within the group is insignificant.
813 sameGroup PgAny PgAny = True
814 sameGroup PgBang PgBang = True
815 sameGroup (PgCon _) (PgCon _) = True -- One case expression
816 sameGroup (PgLit _) (PgLit _) = True -- One case expression
817 sameGroup (PgN l1) (PgN l2) = l1==l2 -- Order is significant
818 sameGroup (PgNpK l1) (PgNpK l2) = l1==l2 -- See Note [Grouping overloaded literal patterns]
819 sameGroup (PgCo t1) (PgCo t2) = t1 `coreEqType` t2
820 -- CoPats are in the same goup only if the type of the
821 -- enclosed pattern is the same. The patterns outside the CoPat
822 -- always have the same type, so this boils down to saying that
823 -- the two coercions are identical.
824 sameGroup (PgView e1 t1) (PgView e2 t2) = viewLExprEq (e1,t1) (e2,t2)
825 -- ViewPats are in the same gorup iff the expressions
826 -- are "equal"---conservatively, we use syntactic equality
827 sameGroup _ _ = False
829 -- an approximation of syntactic equality used for determining when view
830 -- exprs are in the same group.
831 -- this function can always safely return false;
832 -- but doing so will result in the application of the view function being repeated.
834 -- currently: compare applications of literals and variables
835 -- and anything else that we can do without involving other
836 -- HsSyn types in the recursion
838 -- NB we can't assume that the two view expressions have the same type. Consider
839 -- f (e1 -> True) = ...
840 -- f (e2 -> "hi") = ...
841 viewLExprEq :: (LHsExpr Id,Type) -> (LHsExpr Id,Type) -> Bool
842 viewLExprEq (e1,_) (e2,_) =
844 -- short name for recursive call on unLoc
845 lexp e e' = exp (unLoc e) (unLoc e')
847 -- check that two lists have the same length
848 -- and that they match up pairwise
850 lexps [] (_:_) = False
851 lexps (_:_) [] = False
852 lexps (x:xs) (y:ys) = lexp x y && lexps xs ys
854 -- conservative, in that it demands that wrappers be
855 -- syntactically identical and doesn't look under binders
857 -- coarser notions of equality are possible
858 -- (e.g., reassociating compositions,
859 -- equating different ways of writing a coercion)
860 wrap WpHole WpHole = True
861 wrap (WpCompose w1 w2) (WpCompose w1' w2') = wrap w1 w1' && wrap w2 w2'
862 wrap (WpCast c) (WpCast c') = tcEqType c c'
863 wrap (WpApp d) (WpApp d') = d == d'
864 wrap (WpTyApp t) (WpTyApp t') = tcEqType t t'
865 -- Enhancement: could implement equality for more wrappers
866 -- if it seems useful (lams and lets)
869 -- real comparison is on HsExpr's
871 exp (HsPar (L _ e)) e' = exp e e'
872 exp e (HsPar (L _ e')) = exp e e'
873 -- because the expressions do not necessarily have the same type,
874 -- we have to compare the wrappers
875 exp (HsWrap h e) (HsWrap h' e') = wrap h h' && exp e e'
876 exp (HsVar i) (HsVar i') = i == i'
877 -- the instance for IPName derives using the id, so this works if the
879 exp (HsIPVar i) (HsIPVar i') = i == i'
880 exp (HsOverLit l) (HsOverLit l') =
881 -- overloaded lits are equal if they have the same type
882 -- and the data is the same.
883 -- this is coarser than comparing the SyntaxExpr's in l and l',
884 -- which resolve the overloading (e.g., fromInteger 1),
885 -- because these expressions get written as a bunch of different variables
886 -- (presumably to improve sharing)
887 tcEqType (overLitType l) (overLitType l') && l == l'
888 -- comparing the constants seems right
889 exp (HsLit l) (HsLit l') = l == l'
890 exp (HsApp e1 e2) (HsApp e1' e2') = lexp e1 e1' && lexp e2 e2'
891 -- the fixities have been straightened out by now, so it's safe
893 exp (OpApp l o _ ri) (OpApp l' o' _ ri') =
894 lexp l l' && lexp o o' && lexp ri ri'
895 exp (NegApp e n) (NegApp e' n') = lexp e e' && exp n n'
896 exp (SectionL e1 e2) (SectionL e1' e2') =
897 lexp e1 e1' && lexp e2 e2'
898 exp (SectionR e1 e2) (SectionR e1' e2') =
899 lexp e1 e1' && lexp e2 e2'
900 exp (HsIf e e1 e2) (HsIf e' e1' e2') =
901 lexp e e' && lexp e1 e1' && lexp e2 e2'
902 exp (ExplicitList _ ls) (ExplicitList _ ls') = lexps ls ls'
903 exp (ExplicitPArr _ ls) (ExplicitPArr _ ls') = lexps ls ls'
904 exp (ExplicitTuple ls _) (ExplicitTuple ls' _) = lexps ls ls'
905 -- Enhancement: could implement equality for more expressions
906 -- if it seems useful
911 patGroup :: Pat Id -> PatGroup
912 patGroup (WildPat {}) = PgAny
913 patGroup (BangPat {}) = PgBang
914 patGroup (ConPatOut { pat_con = dc }) = PgCon (unLoc dc)
915 patGroup (LitPat lit) = PgLit (hsLitKey lit)
916 patGroup (NPat olit mb_neg _) = PgN (hsOverLitKey olit (isJust mb_neg))
917 patGroup (NPlusKPat _ olit _ _) = PgNpK (hsOverLitKey olit False)
918 patGroup (CoPat _ p _) = PgCo (hsPatType p) -- Type of innelexp pattern
919 patGroup (ViewPat expr p _) = PgView expr (hsPatType (unLoc p))
920 patGroup pat = pprPanic "patGroup" (ppr pat)
923 Note [Grouping overloaded literal patterns]
924 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
931 We can't group the first and third together, because the second may match
932 the same thing as the first. Same goes for *overloaded* literal patterns
936 If the first arg matches '1' but the second does not match 'True', we
937 cannot jump to the third equation! Because the same argument might
939 Hence we don't regard 1 and 2, or (n+1) and (n+2), as part of the same group.