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