Remove the unused HsExpr constructor DictPat
[ghc-hetmet.git] / compiler / deSugar / Match.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 The @match@ function
7
8 \begin{code}
9 module Match ( match, matchEquations, matchWrapper, matchSimply, matchSinglePat ) where
10
11 #include "HsVersions.h"
12
13 import DynFlags
14 import HsSyn            
15 import TcHsSyn
16 import Check
17 import CoreSyn
18 import Literal
19 import CoreUtils
20 import DsMonad
21 import DsBinds
22 import DsGRHSs
23 import DsUtils
24 import Id
25 import DataCon
26 import MatchCon
27 import MatchLit
28 import PrelInfo
29 import Type
30 import TysWiredIn
31 import BasicTypes
32 import ListSetOps
33 import SrcLoc
34 import Maybes
35 import Util
36 import Name
37 import Outputable
38 \end{code}
39
40 This function is a wrapper of @match@, it must be called from all the parts where 
41 it was called match, but only substitutes the firs call, ....
42 if the associated flags are declared, warnings will be issued.
43 It can not be called matchWrapper because this name already exists :-(
44
45 JJCQ 30-Nov-1997
46
47 \begin{code}
48 matchCheck ::  DsMatchContext
49             -> [Id]             -- Vars rep'ing the exprs we're matching with
50             -> Type             -- Type of the case expression
51             -> [EquationInfo]   -- Info about patterns, etc. (type synonym below)
52             -> DsM MatchResult  -- Desugared result!
53
54 matchCheck ctx vars ty qs
55    = getDOptsDs                                 `thenDs` \ dflags ->
56      matchCheck_really dflags ctx vars ty qs
57
58 matchCheck_really dflags ctx vars ty qs
59   | incomplete && shadow = 
60       dsShadowWarn ctx eqns_shadow              `thenDs`   \ () ->
61       dsIncompleteWarn ctx pats                 `thenDs`   \ () ->
62       match vars ty qs
63   | incomplete            = 
64       dsIncompleteWarn ctx pats                 `thenDs`   \ () ->
65       match vars ty qs
66   | shadow                = 
67       dsShadowWarn ctx eqns_shadow              `thenDs`   \ () ->
68       match vars ty qs
69   | otherwise             =
70       match vars ty qs
71   where (pats, eqns_shadow) = check qs
72         incomplete    = want_incomplete && (notNull pats)
73         want_incomplete = case ctx of
74                               DsMatchContext RecUpd _ ->
75                                   dopt Opt_WarnIncompletePatternsRecUpd dflags
76                               _ ->
77                                   dopt Opt_WarnIncompletePatterns       dflags
78         shadow        = dopt Opt_WarnOverlappingPatterns dflags
79                         && not (null eqns_shadow)
80 \end{code}
81
82 This variable shows the maximum number of lines of output generated for warnings.
83 It will limit the number of patterns/equations displayed to@ maximum_output@.
84
85 (ToDo: add command-line option?)
86
87 \begin{code}
88 maximum_output = 4
89 \end{code}
90
91 The next two functions create the warning message.
92
93 \begin{code}
94 dsShadowWarn :: DsMatchContext -> [EquationInfo] -> DsM ()
95 dsShadowWarn ctx@(DsMatchContext kind loc) qs
96   = putSrcSpanDs loc (warnDs warn)
97   where
98     warn | qs `lengthExceeds` maximum_output
99          = pp_context ctx (ptext SLIT("are overlapped"))
100                       (\ f -> vcat (map (ppr_eqn f kind) (take maximum_output qs)) $$
101                       ptext SLIT("..."))
102          | otherwise
103          = pp_context ctx (ptext SLIT("are overlapped"))
104                       (\ f -> vcat $ map (ppr_eqn f kind) qs)
105
106
107 dsIncompleteWarn :: DsMatchContext -> [ExhaustivePat] -> DsM ()
108 dsIncompleteWarn ctx@(DsMatchContext kind loc) pats 
109   = putSrcSpanDs loc (warnDs warn)
110         where
111           warn = pp_context ctx (ptext SLIT("are non-exhaustive"))
112                             (\f -> hang (ptext SLIT("Patterns not matched:"))
113                                    4 ((vcat $ map (ppr_incomplete_pats kind)
114                                                   (take maximum_output pats))
115                                       $$ dots))
116
117           dots | pats `lengthExceeds` maximum_output = ptext SLIT("...")
118                | otherwise                           = empty
119
120 pp_context (DsMatchContext kind _loc) msg rest_of_msg_fun
121   = vcat [ptext SLIT("Pattern match(es)") <+> msg,
122           sep [ptext SLIT("In") <+> ppr_match <> char ':', nest 4 (rest_of_msg_fun pref)]]
123   where
124     (ppr_match, pref)
125         = case kind of
126              FunRhs fun -> (pprMatchContext kind, \ pp -> ppr fun <+> pp)
127              other      -> (pprMatchContext kind, \ pp -> pp)
128
129 ppr_pats pats = sep (map ppr pats)
130
131 ppr_shadow_pats kind pats
132   = sep [ppr_pats pats, matchSeparator kind, ptext SLIT("...")]
133     
134 ppr_incomplete_pats kind (pats,[]) = ppr_pats pats
135 ppr_incomplete_pats kind (pats,constraints) = 
136                          sep [ppr_pats pats, ptext SLIT("with"), 
137                               sep (map ppr_constraint constraints)]
138     
139
140 ppr_constraint (var,pats) = sep [ppr var, ptext SLIT("`notElem`"), ppr pats]
141
142 ppr_eqn prefixF kind eqn = prefixF (ppr_shadow_pats kind (eqn_pats eqn))
143 \end{code}
144
145
146 %************************************************************************
147 %*                                                                      *
148                 The main matching function
149 %*                                                                      *
150 %************************************************************************
151
152 The function @match@ is basically the same as in the Wadler chapter,
153 except it is monadised, to carry around the name supply, info about
154 annotations, etc.
155
156 Notes on @match@'s arguments, assuming $m$ equations and $n$ patterns:
157 \begin{enumerate}
158 \item
159 A list of $n$ variable names, those variables presumably bound to the
160 $n$ expressions being matched against the $n$ patterns.  Using the
161 list of $n$ expressions as the first argument showed no benefit and
162 some inelegance.
163
164 \item
165 The second argument, a list giving the ``equation info'' for each of
166 the $m$ equations:
167 \begin{itemize}
168 \item
169 the $n$ patterns for that equation, and
170 \item
171 a list of Core bindings [@(Id, CoreExpr)@ pairs] to be ``stuck on
172 the front'' of the matching code, as in:
173 \begin{verbatim}
174 let <binds>
175 in  <matching-code>
176 \end{verbatim}
177 \item
178 and finally: (ToDo: fill in)
179
180 The right way to think about the ``after-match function'' is that it
181 is an embryonic @CoreExpr@ with a ``hole'' at the end for the
182 final ``else expression''.
183 \end{itemize}
184
185 There is a type synonym, @EquationInfo@, defined in module @DsUtils@.
186
187 An experiment with re-ordering this information about equations (in
188 particular, having the patterns available in column-major order)
189 showed no benefit.
190
191 \item
192 A default expression---what to evaluate if the overall pattern-match
193 fails.  This expression will (almost?) always be
194 a measly expression @Var@, unless we know it will only be used once
195 (as we do in @glue_success_exprs@).
196
197 Leaving out this third argument to @match@ (and slamming in lots of
198 @Var "fail"@s) is a positively {\em bad} idea, because it makes it
199 impossible to share the default expressions.  (Also, it stands no
200 chance of working in our post-upheaval world of @Locals@.)
201 \end{enumerate}
202
203 Note: @match@ is often called via @matchWrapper@ (end of this module),
204 a function that does much of the house-keeping that goes with a call
205 to @match@.
206
207 It is also worth mentioning the {\em typical} way a block of equations
208 is desugared with @match@.  At each stage, it is the first column of
209 patterns that is examined.  The steps carried out are roughly:
210 \begin{enumerate}
211 \item
212 Tidy the patterns in column~1 with @tidyEqnInfo@ (this may add
213 bindings to the second component of the equation-info):
214 \begin{itemize}
215 \item
216 Remove the `as' patterns from column~1.
217 \item
218 Make all constructor patterns in column~1 into @ConPats@, notably
219 @ListPats@ and @TuplePats@.
220 \item
221 Handle any irrefutable (or ``twiddle'') @LazyPats@.
222 \end{itemize}
223 \item
224 Now {\em unmix} the equations into {\em blocks} [w/ local function
225 @unmix_eqns@], in which the equations in a block all have variable
226 patterns in column~1, or they all have constructor patterns in ...
227 (see ``the mixture rule'' in SLPJ).
228 \item
229 Call @matchEqnBlock@ on each block of equations; it will do the
230 appropriate thing for each kind of column-1 pattern, usually ending up
231 in a recursive call to @match@.
232 \end{enumerate}
233
234 We are a little more paranoid about the ``empty rule'' (SLPJ, p.~87)
235 than the Wadler-chapter code for @match@ (p.~93, first @match@ clause).
236 And gluing the ``success expressions'' together isn't quite so pretty.
237
238 This (more interesting) clause of @match@ uses @tidy_and_unmix_eqns@
239 (a)~to get `as'- and `twiddle'-patterns out of the way (tidying), and
240 (b)~to do ``the mixture rule'' (SLPJ, p.~88) [which really {\em
241 un}mixes the equations], producing a list of equation-info
242 blocks, each block having as its first column of patterns either all
243 constructors, or all variables (or similar beasts), etc.
244
245 @match_unmixed_eqn_blks@ simply takes the place of the @foldr@ in the
246 Wadler-chapter @match@ (p.~93, last clause), and @match_unmixed_blk@
247 corresponds roughly to @matchVarCon@.
248
249 \begin{code}
250 match :: [Id]             -- Variables rep'ing the exprs we're matching with
251       -> Type             -- Type of the case expression
252       -> [EquationInfo]   -- Info about patterns, etc. (type synonym below)
253       -> DsM MatchResult  -- Desugared result!
254
255 match [] ty eqns
256   = ASSERT2( not (null eqns), ppr ty )
257     returnDs (foldr1 combineMatchResults match_results)
258   where
259     match_results = [ ASSERT( null (eqn_pats eqn) ) 
260                       eqn_rhs eqn
261                     | eqn <- eqns ]
262
263 match vars@(v:_) ty eqns
264   = ASSERT( not (null eqns ) )
265     do  {       -- Tidy the first pattern, generating
266                 -- auxiliary bindings if necessary
267           (aux_binds, tidy_eqns) <- mapAndUnzipM (tidyEqnInfo v) eqns
268
269                 -- Group the equations and match each group in turn
270         ; match_results <- mapM match_group (groupEquations tidy_eqns)
271
272         ; return (adjustMatchResult (foldr1 (.) aux_binds) $
273                   foldr1 combineMatchResults match_results) }
274   where
275     dropGroup :: [(PatGroup,EquationInfo)] -> [EquationInfo]
276     dropGroup = map snd
277
278     match_group :: [(PatGroup,EquationInfo)] -> DsM MatchResult
279     match_group eqns@((group,_) : _)
280       = case group of
281           PgAny     -> matchVariables  vars ty (dropGroup eqns)
282           PgCon _   -> matchConFamily  vars ty (subGroups eqns)
283           PgLit _   -> matchLiterals   vars ty (subGroups eqns)
284           PgN lit   -> matchNPats      vars ty (subGroups eqns)
285           PgNpK lit -> matchNPlusKPats vars ty (dropGroup eqns)
286           PgBang    -> matchBangs      vars ty (dropGroup eqns)
287           PgCo _    -> matchCoercion   vars ty (dropGroup eqns)
288
289 matchVariables :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
290 -- Real true variables, just like in matchVar, SLPJ p 94
291 -- No binding to do: they'll all be wildcards by now (done in tidy)
292 matchVariables (var:vars) ty eqns = match vars ty (shiftEqns eqns)
293
294 matchBangs :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
295 matchBangs (var:vars) ty eqns
296   = do  { match_result <- match (var:vars) ty (map shift eqns)
297         ; return (mkEvalMatchResult var ty match_result) }
298   where
299     shift eqn@(EqnInfo { eqn_pats = BangPat pat : pats })
300         = eqn { eqn_pats = unLoc pat : pats }
301
302 matchCoercion :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
303 -- Apply the coercion to the match variable and then match that
304 matchCoercion (var:vars) ty (eqn1:eqns)
305   = do  { let CoPat co pat _ = firstPat eqn1
306         ; var' <- newUniqueId (idName var) (hsPatType pat)
307         ; match_result <- match (var':vars) ty (map shift (eqn1:eqns))
308         ; rhs <- dsCoercion co (return (Var var))
309         ; return (mkCoLetMatchResult (NonRec var' rhs) match_result) }
310   where
311     shift eqn@(EqnInfo { eqn_pats = CoPat _ pat _ : pats })
312         = eqn { eqn_pats = pat : pats }
313 \end{code}
314
315 %************************************************************************
316 %*                                                                      *
317                 Tidying patterns
318 %*                                                                      *
319 %************************************************************************
320
321 Tidy up the leftmost pattern in an @EquationInfo@, given the variable @v@
322 which will be scrutinised.  This means:
323 \begin{itemize}
324 \item
325 Replace variable patterns @x@ (@x /= v@) with the pattern @_@,
326 together with the binding @x = v@.
327 \item
328 Replace the `as' pattern @x@@p@ with the pattern p and a binding @x = v@.
329 \item
330 Removing lazy (irrefutable) patterns (you don't want to know...).
331 \item
332 Converting explicit tuple-, list-, and parallel-array-pats into ordinary
333 @ConPats@. 
334 \item
335 Convert the literal pat "" to [].
336 \end{itemize}
337
338 The result of this tidying is that the column of patterns will include
339 {\em only}:
340 \begin{description}
341 \item[@WildPats@:]
342 The @VarPat@ information isn't needed any more after this.
343
344 \item[@ConPats@:]
345 @ListPats@, @TuplePats@, etc., are all converted into @ConPats@.
346
347 \item[@LitPats@ and @NPats@:]
348 @LitPats@/@NPats@ of ``known friendly types'' (Int, Char,
349 Float,  Double, at least) are converted to unboxed form; e.g.,
350 \tr{(NPat (HsInt i) _ _)} is converted to:
351 \begin{verbatim}
352 (ConPat I# _ _ [LitPat (HsIntPrim i)])
353 \end{verbatim}
354 \end{description}
355
356 \begin{code}
357 tidyEqnInfo :: Id -> EquationInfo
358             -> DsM (DsWrapper, EquationInfo)
359         -- DsM'd because of internal call to dsLHsBinds
360         --      and mkSelectorBinds.
361         -- "tidy1" does the interesting stuff, looking at
362         -- one pattern and fiddling the list of bindings.
363         --
364         -- POST CONDITION: head pattern in the EqnInfo is
365         --      WildPat
366         --      ConPat
367         --      NPat
368         --      LitPat
369         --      NPlusKPat
370         -- but no other
371
372 tidyEqnInfo v eqn@(EqnInfo { eqn_pats = pat : pats })
373   = tidy1 v pat         `thenDs` \ (wrap, pat') ->
374     returnDs (wrap, eqn { eqn_pats = pat' : pats })
375
376 tidy1 :: Id                     -- The Id being scrutinised
377       -> Pat Id                 -- The pattern against which it is to be matched
378       -> DsM (DsWrapper,        -- Extra bindings to do before the match
379               Pat Id)           -- Equivalent pattern
380
381 -------------------------------------------------------
382 --      (pat', mr') = tidy1 v pat mr
383 -- tidies the *outer level only* of pat, giving pat'
384 -- It eliminates many pattern forms (as-patterns, variable patterns,
385 -- list patterns, etc) yielding one of:
386 --      WildPat
387 --      ConPatOut
388 --      LitPat
389 --      NPat
390 --      NPlusKPat
391
392 tidy1 v (ParPat pat)      = tidy1 v (unLoc pat) 
393 tidy1 v (SigPatOut pat _) = tidy1 v (unLoc pat) 
394 tidy1 v (WildPat ty)      = returnDs (idDsWrapper, WildPat ty)
395
396         -- case v of { x -> mr[] }
397         -- = case v of { _ -> let x=v in mr[] }
398 tidy1 v (VarPat var)
399   = returnDs (wrapBind var v, WildPat (idType var)) 
400
401 tidy1 v (VarPatOut var binds)
402   = do  { prs <- dsLHsBinds binds
403         ; return (wrapBind var v . mkDsLet (Rec prs),
404                   WildPat (idType var)) }
405
406         -- case v of { x@p -> mr[] }
407         -- = case v of { p -> let x=v in mr[] }
408 tidy1 v (AsPat (L _ var) pat)
409   = do  { (wrap, pat') <- tidy1 v (unLoc pat)
410         ; return (wrapBind var v . wrap, pat') }
411
412 {- now, here we handle lazy patterns:
413     tidy1 v ~p bs = (v, v1 = case v of p -> v1 :
414                         v2 = case v of p -> v2 : ... : bs )
415
416     where the v_i's are the binders in the pattern.
417
418     ToDo: in "v_i = ... -> v_i", are the v_i's really the same thing?
419
420     The case expr for v_i is just: match [v] [(p, [], \ x -> Var v_i)] any_expr
421 -}
422
423 tidy1 v (LazyPat pat)
424   = do  { sel_prs <- mkSelectorBinds pat (Var v)
425         ; let sel_binds =  [NonRec b rhs | (b,rhs) <- sel_prs]
426         ; returnDs (mkDsLets sel_binds, WildPat (idType v)) }
427
428 tidy1 v (ListPat pats ty)
429   = returnDs (idDsWrapper, unLoc list_ConPat)
430   where
431     list_ty     = mkListTy ty
432     list_ConPat = foldr (\ x y -> mkPrefixConPat consDataCon [x, y] list_ty)
433                         (mkNilPat list_ty)
434                         pats
435
436 -- Introduce fake parallel array constructors to be able to handle parallel
437 -- arrays with the existing machinery for constructor pattern
438 tidy1 v (PArrPat pats ty)
439   = returnDs (idDsWrapper, unLoc parrConPat)
440   where
441     arity      = length pats
442     parrConPat = mkPrefixConPat (parrFakeCon arity) pats (mkPArrTy ty)
443
444 tidy1 v (TuplePat pats boxity ty)
445   = returnDs (idDsWrapper, unLoc tuple_ConPat)
446   where
447     arity = length pats
448     tuple_ConPat = mkPrefixConPat (tupleCon boxity arity) pats ty
449
450 -- LitPats: we *might* be able to replace these w/ a simpler form
451 tidy1 v (LitPat lit)
452   = returnDs (idDsWrapper, tidyLitPat lit)
453
454 -- NPats: we *might* be able to replace these w/ a simpler form
455 tidy1 v (NPat lit mb_neg eq lit_ty)
456   = returnDs (idDsWrapper, tidyNPat lit mb_neg eq lit_ty)
457
458 -- Everything else goes through unchanged...
459
460 tidy1 v non_interesting_pat
461   = returnDs (idDsWrapper, non_interesting_pat)
462 \end{code}
463
464 \noindent
465 {\bf Previous @matchTwiddled@ stuff:}
466
467 Now we get to the only interesting part; note: there are choices for
468 translation [from Simon's notes]; translation~1:
469 \begin{verbatim}
470 deTwiddle [s,t] e
471 \end{verbatim}
472 returns
473 \begin{verbatim}
474 [ w = e,
475   s = case w of [s,t] -> s
476   t = case w of [s,t] -> t
477 ]
478 \end{verbatim}
479
480 Here \tr{w} is a fresh variable, and the \tr{w}-binding prevents multiple
481 evaluation of \tr{e}.  An alternative translation (No.~2):
482 \begin{verbatim}
483 [ w = case e of [s,t] -> (s,t)
484   s = case w of (s,t) -> s
485   t = case w of (s,t) -> t
486 ]
487 \end{verbatim}
488
489 %************************************************************************
490 %*                                                                      *
491 \subsubsection[improved-unmixing]{UNIMPLEMENTED idea for improved unmixing}
492 %*                                                                      *
493 %************************************************************************
494
495 We might be able to optimise unmixing when confronted by
496 only-one-constructor-possible, of which tuples are the most notable
497 examples.  Consider:
498 \begin{verbatim}
499 f (a,b,c) ... = ...
500 f d ... (e:f) = ...
501 f (g,h,i) ... = ...
502 f j ...       = ...
503 \end{verbatim}
504 This definition would normally be unmixed into four equation blocks,
505 one per equation.  But it could be unmixed into just one equation
506 block, because if the one equation matches (on the first column),
507 the others certainly will.
508
509 You have to be careful, though; the example
510 \begin{verbatim}
511 f j ...       = ...
512 -------------------
513 f (a,b,c) ... = ...
514 f d ... (e:f) = ...
515 f (g,h,i) ... = ...
516 \end{verbatim}
517 {\em must} be broken into two blocks at the line shown; otherwise, you
518 are forcing unnecessary evaluation.  In any case, the top-left pattern
519 always gives the cue.  You could then unmix blocks into groups of...
520 \begin{description}
521 \item[all variables:]
522 As it is now.
523 \item[constructors or variables (mixed):]
524 Need to make sure the right names get bound for the variable patterns.
525 \item[literals or variables (mixed):]
526 Presumably just a variant on the constructor case (as it is now).
527 \end{description}
528
529 %************************************************************************
530 %*                                                                      *
531 %*  matchWrapper: a convenient way to call @match@                      *
532 %*                                                                      *
533 %************************************************************************
534 \subsection[matchWrapper]{@matchWrapper@: a convenient interface to @match@}
535
536 Calls to @match@ often involve similar (non-trivial) work; that work
537 is collected here, in @matchWrapper@.  This function takes as
538 arguments:
539 \begin{itemize}
540 \item
541 Typchecked @Matches@ (of a function definition, or a case or lambda
542 expression)---the main input;
543 \item
544 An error message to be inserted into any (runtime) pattern-matching
545 failure messages.
546 \end{itemize}
547
548 As results, @matchWrapper@ produces:
549 \begin{itemize}
550 \item
551 A list of variables (@Locals@) that the caller must ``promise'' to
552 bind to appropriate values; and
553 \item
554 a @CoreExpr@, the desugared output (main result).
555 \end{itemize}
556
557 The main actions of @matchWrapper@ include:
558 \begin{enumerate}
559 \item
560 Flatten the @[TypecheckedMatch]@ into a suitable list of
561 @EquationInfo@s.
562 \item
563 Create as many new variables as there are patterns in a pattern-list
564 (in any one of the @EquationInfo@s).
565 \item
566 Create a suitable ``if it fails'' expression---a call to @error@ using
567 the error-string input; the {\em type} of this fail value can be found
568 by examining one of the RHS expressions in one of the @EquationInfo@s.
569 \item
570 Call @match@ with all of this information!
571 \end{enumerate}
572
573 \begin{code}
574 matchWrapper :: HsMatchContext Name     -- For shadowing warning messages
575              -> MatchGroup Id           -- Matches being desugared
576              -> DsM ([Id], CoreExpr)    -- Results
577 \end{code}
578
579  There is one small problem with the Lambda Patterns, when somebody
580  writes something similar to:
581 \begin{verbatim}
582     (\ (x:xs) -> ...)
583 \end{verbatim}
584  he/she don't want a warning about incomplete patterns, that is done with 
585  the flag @opt_WarnSimplePatterns@.
586  This problem also appears in the:
587 \begin{itemize}
588 \item @do@ patterns, but if the @do@ can fail
589       it creates another equation if the match can fail
590       (see @DsExpr.doDo@ function)
591 \item @let@ patterns, are treated by @matchSimply@
592    List Comprension Patterns, are treated by @matchSimply@ also
593 \end{itemize}
594
595 We can't call @matchSimply@ with Lambda patterns,
596 due to the fact that lambda patterns can have more than
597 one pattern, and match simply only accepts one pattern.
598
599 JJQC 30-Nov-1997
600
601 \begin{code}
602 matchWrapper ctxt (MatchGroup matches match_ty)
603   = ASSERT( notNull matches )
604     do  { eqns_info   <- mapM mk_eqn_info matches
605         ; new_vars    <- selectMatchVars arg_pats
606         ; result_expr <- matchEquations ctxt new_vars eqns_info rhs_ty
607         ; return (new_vars, result_expr) }
608   where
609     arg_pats    = map unLoc (hsLMatchPats (head matches))
610     n_pats      = length arg_pats
611     (_, rhs_ty) = splitFunTysN n_pats match_ty
612
613     mk_eqn_info (L _ (Match pats _ grhss))
614       = do { let upats = map unLoc pats
615            ; match_result <- dsGRHSs ctxt upats grhss rhs_ty
616            ; return (EqnInfo { eqn_pats = upats, eqn_rhs  = match_result}) }
617
618
619 matchEquations  :: HsMatchContext Name
620                 -> [Id] -> [EquationInfo] -> Type
621                 -> DsM CoreExpr
622 matchEquations ctxt vars eqns_info rhs_ty
623   = do  { dflags <- getDOptsDs
624         ; locn   <- getSrcSpanDs
625         ; let   ds_ctxt      = DsMatchContext ctxt locn
626                 error_string = matchContextErrString ctxt
627
628         ; match_result <- match_fun dflags ds_ctxt vars rhs_ty eqns_info
629
630         ; fail_expr <- mkErrorAppDs pAT_ERROR_ID rhs_ty error_string
631         ; extractMatchResult match_result fail_expr }
632   where 
633     match_fun dflags ds_ctxt
634        = case ctxt of 
635            LambdaExpr | dopt Opt_WarnSimplePatterns dflags -> matchCheck ds_ctxt
636                       | otherwise                          -> match
637            _                                               -> matchCheck ds_ctxt
638 \end{code}
639
640 %************************************************************************
641 %*                                                                      *
642 \subsection[matchSimply]{@matchSimply@: match a single expression against a single pattern}
643 %*                                                                      *
644 %************************************************************************
645
646 @mkSimpleMatch@ is a wrapper for @match@ which deals with the
647 situation where we want to match a single expression against a single
648 pattern. It returns an expression.
649
650 \begin{code}
651 matchSimply :: CoreExpr                 -- Scrutinee
652             -> HsMatchContext Name      -- Match kind
653             -> LPat Id                  -- Pattern it should match
654             -> CoreExpr                 -- Return this if it matches
655             -> CoreExpr                 -- Return this if it doesn't
656             -> DsM CoreExpr
657
658 matchSimply scrut hs_ctx pat result_expr fail_expr
659   = let
660       match_result = cantFailMatchResult result_expr
661       rhs_ty       = exprType fail_expr
662         -- Use exprType of fail_expr, because won't refine in the case of failure!
663     in 
664     matchSinglePat scrut hs_ctx pat rhs_ty match_result `thenDs` \ match_result' ->
665     extractMatchResult match_result' fail_expr
666
667
668 matchSinglePat :: CoreExpr -> HsMatchContext Name -> LPat Id
669                -> Type -> MatchResult -> DsM MatchResult
670 matchSinglePat (Var var) hs_ctx (L _ pat) ty match_result
671   = getDOptsDs                          `thenDs` \ dflags ->
672     getSrcSpanDs                        `thenDs` \ locn ->
673     let
674         match_fn dflags
675            | dopt Opt_WarnSimplePatterns dflags = matchCheck ds_ctx
676            | otherwise                          = match
677            where
678              ds_ctx = DsMatchContext hs_ctx locn
679     in
680     match_fn dflags [var] ty [EqnInfo { eqn_pats = [pat], eqn_rhs  = match_result }]
681
682 matchSinglePat scrut hs_ctx pat ty match_result
683   = selectSimpleMatchVarL pat                           `thenDs` \ var ->
684     matchSinglePat (Var var) hs_ctx pat ty match_result `thenDs` \ match_result' ->
685     returnDs (adjustMatchResult (bindNonRec var scrut) match_result')
686 \end{code}
687
688
689 %************************************************************************
690 %*                                                                      *
691                 Pattern classification
692 %*                                                                      *
693 %************************************************************************
694
695 \begin{code}
696 data PatGroup
697   = PgAny               -- Immediate match: variables, wildcards, 
698                         --                  lazy patterns
699   | PgCon DataCon       -- Constructor patterns (incl list, tuple)
700   | PgLit Literal       -- Literal patterns
701   | PgN   Literal       -- Overloaded literals
702   | PgNpK Literal       -- n+k patterns
703   | PgBang              -- Bang patterns
704   | PgCo Type           -- Coercion patterns; the type is the type
705                         --      of the pattern *inside*
706
707
708 groupEquations :: [EquationInfo] -> [[(PatGroup, EquationInfo)]]
709 -- If the result is of form [g1, g2, g3], 
710 -- (a) all the (pg,eq) pairs in g1 have the same pg
711 -- (b) none of the gi are empty
712 groupEquations eqns
713   = runs same_gp [(patGroup (firstPat eqn), eqn) | eqn <- eqns]
714   where
715     same_gp :: (PatGroup,EquationInfo) -> (PatGroup,EquationInfo) -> Bool
716     (pg1,_) `same_gp` (pg2,_) = pg1 `sameGroup` pg2
717
718 subGroups :: [(PatGroup, EquationInfo)] -> [[EquationInfo]]
719 -- Input is a particular group.  The result sub-groups the 
720 -- equations by with particular constructor, literal etc they match.
721 -- The order may be swizzled, so the matching should be order-independent
722 subGroups groups = map (map snd) (equivClasses cmp groups)
723   where
724     (pg1, _) `cmp` (pg2, _) = pg1 `cmp_pg` pg2
725     (PgCon c1) `cmp_pg` (PgCon c2) = c1 `compare` c2
726     (PgLit l1) `cmp_pg` (PgLit l2) = l1 `compare` l2
727     (PgN   l1) `cmp_pg` (PgN   l2) = l1 `compare` l2
728         -- These are the only cases that are every sub-grouped
729
730 sameGroup :: PatGroup -> PatGroup -> Bool
731 -- Same group means that a single case expression 
732 -- or test will suffice to match both, *and* the order
733 -- of testing within the group is insignificant.
734 sameGroup PgAny      PgAny      = True
735 sameGroup PgBang     PgBang     = True
736 sameGroup (PgCon _)  (PgCon _)  = True          -- One case expression
737 sameGroup (PgLit _)  (PgLit _)  = True          -- One case expression
738 sameGroup (PgN l1)   (PgN l2)   = True          -- Needs conditionals
739 sameGroup (PgNpK l1) (PgNpK l2) = l1==l2        -- Order is significant
740                                                 -- See Note [Order of n+k]
741 sameGroup (PgCo t1)  (PgCo t2)  = t1 `coreEqType` t2
742         -- CoPats are in the same goup only if the type of the
743         -- enclosed pattern is the same. The patterns outside the CoPat
744         -- always have the same type, so this boils down to saying that
745         -- the two coercions are identical.
746 sameGroup _          _          = False
747  
748 patGroup :: Pat Id -> PatGroup
749 patGroup (WildPat {})                 = PgAny
750 patGroup (BangPat {})                 = PgBang  
751 patGroup (ConPatOut { pat_con = dc }) = PgCon (unLoc dc)
752 patGroup (LitPat lit)                 = PgLit (hsLitKey lit)
753 patGroup (NPat olit mb_neg _ _)       = PgN   (hsOverLitKey olit (isJust mb_neg))
754 patGroup (NPlusKPat _ olit _ _)       = PgNpK (hsOverLitKey olit False)
755 patGroup (CoPat _ p _)                = PgCo  (hsPatType p)     -- Type of inner pattern
756 patGroup pat = pprPanic "patGroup" (ppr pat)
757 \end{code}
758
759 Note [Order of n+k]
760 ~~~~~~~~~~~~~~~~~~~
761 WATCH OUT!  Consider
762
763         f (n+1) = ...
764         f (n+2) = ...
765         f (n+1) = ...
766
767 We can't group the first and third together, because the second may match 
768 the same thing as the first.  Contrast
769         f 1 = ...
770         f 2 = ...
771         f 1 = ...
772 where we can group the first and third.  Hence we don't regard (n+1) and
773 (n+2) as part of the same group.