[project @ 2000-10-24 08:40:09 by simonpj]
[ghc-hetmet.git] / ghc / compiler / deSugar / Match.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[Main_match]{The @match@ function}
5
6 \begin{code}
7 module Match ( match, matchExport, matchWrapper, matchSimply, matchSinglePat ) where
8
9 #include "HsVersions.h"
10
11 import CmdLineOpts      ( DynFlag(..), dopt )
12 import HsSyn            
13 import TcHsSyn          ( TypecheckedPat, TypecheckedMatch )
14 import DsHsSyn          ( outPatType )
15 import Check            ( check, ExhaustivePat )
16 import CoreSyn
17 import CoreUtils        ( bindNonRec )
18 import DsMonad
19 import DsGRHSs          ( dsGRHSs )
20 import DsUtils
21 import Id               ( idType, recordSelectorFieldLabel, Id )
22 import DataCon          ( dataConFieldLabels, dataConInstOrigArgTys )
23 import MatchCon         ( matchConFamily )
24 import MatchLit         ( matchLiterals )
25 import PrelInfo         ( pAT_ERROR_ID )
26 import Type             ( splitAlgTyConApp, mkTyVarTys, Type )
27 import TysWiredIn       ( nilDataCon, consDataCon, mkTupleTy, mkListTy, tupleCon )
28 import BasicTypes       ( Boxity(..) )
29 import UniqSet
30 import ErrUtils         ( addErrLocHdrLine, dontAddErrLoc )
31 import Outputable
32 \end{code}
33
34 This function is a wrapper of @match@, it must be called from all the parts where 
35 it was called match, but only substitutes the firs call, ....
36 if the associated flags are declared, warnings will be issued.
37 It can not be called matchWrapper because this name already exists :-(
38
39 JJCQ 30-Nov-1997
40
41 \begin{code}
42 matchExport :: [Id]             -- Vars rep'ing the exprs we're matching with
43             -> [EquationInfo]   -- Info about patterns, etc. (type synonym below)
44             -> DsM MatchResult  -- Desugared result!
45
46
47 matchExport vars qs
48    = getDOptsDs                                 `thenDs` \ dflags ->
49      matchExport_really dflags vars qs
50
51 matchExport_really dflags vars qs@((EqnInfo _ ctx _ (MatchResult _ _)) : _)
52   | incomplete && shadow = 
53       dsShadowWarn ctx eqns_shadow              `thenDs`   \ () ->
54       dsIncompleteWarn ctx pats                 `thenDs`   \ () ->
55       match vars qs
56   | incomplete            = 
57       dsIncompleteWarn ctx pats                 `thenDs`   \ () ->
58       match vars qs
59   | shadow                = 
60       dsShadowWarn ctx eqns_shadow              `thenDs`   \ () ->
61       match vars qs
62   | otherwise             =
63       match vars qs
64   where (pats,indexs) = check qs
65         incomplete    = dopt Opt_WarnIncompletePatterns dflags
66                         && (length pats /= 0)
67         shadow        = dopt Opt_WarnOverlappingPatterns dflags
68                         && sizeUniqSet indexs < no_eqns
69         no_eqns       = length qs
70         unused_eqns   = uniqSetToList (mkUniqSet [1..no_eqns] `minusUniqSet` indexs)
71         eqns_shadow   = map (\n -> qs!!(n - 1)) unused_eqns
72 \end{code}
73
74 This variable shows the maximum number of lines of output generated for warnings.
75 It will limit the number of patterns/equations displayed to@ maximum_output@.
76
77 (ToDo: add command-line option?)
78
79 \begin{code}
80 maximum_output = 4
81 \end{code}
82
83 The next two functions create the warning message.
84
85 \begin{code}
86 dsShadowWarn :: DsMatchContext -> [EquationInfo] -> DsM ()
87 dsShadowWarn ctx@(DsMatchContext kind _ _) qs = dsWarn warn 
88         where
89           warn | length qs > maximum_output
90                = pp_context ctx (ptext SLIT("are overlapped"))
91                             (\ f -> vcat (map (ppr_eqn f kind) (take maximum_output qs)) $$
92                             ptext SLIT("..."))
93                | otherwise
94                = pp_context ctx (ptext SLIT("are overlapped"))
95                             (\ f -> vcat $ map (ppr_eqn f kind) qs)
96
97
98 dsIncompleteWarn :: DsMatchContext -> [ExhaustivePat] -> DsM ()
99 dsIncompleteWarn ctx@(DsMatchContext kind _ _) pats = dsWarn warn 
100         where
101           warn = pp_context ctx (ptext SLIT("are non-exhaustive"))
102                             (\f -> hang (ptext SLIT("Patterns not matched:"))
103                                    4 ((vcat $ map (ppr_incomplete_pats kind)
104                                                   (take maximum_output pats))
105                                       $$ dots))
106
107           dots | length pats > maximum_output = ptext SLIT("...")
108                | otherwise                    = empty
109
110 pp_context NoMatchContext msg rest_of_msg_fun
111   = dontAddErrLoc "" (ptext SLIT("Some match(es)") <+> hang msg 8 (rest_of_msg_fun id))
112
113 pp_context (DsMatchContext kind pats loc) msg rest_of_msg_fun
114   = case pp_match kind pats of
115       (ppr_match, pref) ->
116           addErrLocHdrLine loc message (nest 8 (rest_of_msg_fun pref))
117         where
118           message = ptext SLIT("Pattern match(es)") <+> msg <+> ppr_match <> char ':'
119  where
120     pp_match (FunMatch fun) pats
121       = let ppr_fun = ppr fun in
122         ( hsep [ptext SLIT("in the definition of function"), quotes ppr_fun]
123         , (\ x -> ppr_fun <+> x)
124         )
125
126     pp_match CaseMatch pats
127       = (hang (ptext SLIT("in a group of case alternatives beginning"))
128            4 (ppr_pats pats)
129         , id
130         )
131
132     pp_match RecUpdMatch pats
133       = (hang (ptext SLIT("in a record-update construct"))
134            4 (ppr_pats pats)
135         , id
136         )
137
138     pp_match PatBindMatch pats
139       = ( hang (ptext SLIT("in a pattern binding"))
140             4 (ppr_pats pats)
141         , id
142         )
143
144     pp_match LambdaMatch pats
145       = ( hang (ptext SLIT("in a lambda abstraction"))
146             4 (ppr_pats pats)
147         , id
148         )
149
150     pp_match DoBindMatch pats
151       = ( hang (ptext SLIT("in a `do' pattern binding"))
152              4 (ppr_pats pats)
153         , id
154         )
155
156     pp_match ListCompMatch pats
157       = ( hang (ptext SLIT("in a `list comprension' pattern binding"))
158              4 (ppr_pats pats)
159         , id
160         ) 
161
162     pp_match LetMatch pats
163       = ( hang (ptext SLIT("in a `let' pattern binding"))
164              4 (ppr_pats pats)
165         , id
166         )
167
168 ppr_pats pats = sep (map ppr pats)
169
170 separator (FunMatch _)    = SLIT("=")
171 separator (CaseMatch)     = SLIT("->") 
172 separator (LambdaMatch)   = SLIT("->") 
173 separator (PatBindMatch)  = panic "When is this used?"
174 separator (RecUpdMatch)   = panic "When is this used?"
175 separator (DoBindMatch)   = SLIT("<-")  
176 separator (ListCompMatch) = SLIT("<-")  
177 separator (LetMatch)      = SLIT("=")
178                  
179 ppr_shadow_pats kind pats
180   = sep [ppr_pats pats, ptext (separator kind), ptext SLIT("...")]
181     
182 ppr_incomplete_pats kind (pats,[]) = ppr_pats pats
183 ppr_incomplete_pats kind (pats,constraints) = 
184                          sep [ppr_pats pats, ptext SLIT("with"), 
185                               sep (map ppr_constraint constraints)]
186     
187
188 ppr_constraint (var,pats) = sep [ppr var, ptext SLIT("`notElem`"), ppr pats]
189
190 ppr_eqn prefixF kind (EqnInfo _ _ pats _) = prefixF (ppr_shadow_pats kind pats)
191 \end{code}
192
193
194 The function @match@ is basically the same as in the Wadler chapter,
195 except it is monadised, to carry around the name supply, info about
196 annotations, etc.
197
198 Notes on @match@'s arguments, assuming $m$ equations and $n$ patterns:
199 \begin{enumerate}
200 \item
201 A list of $n$ variable names, those variables presumably bound to the
202 $n$ expressions being matched against the $n$ patterns.  Using the
203 list of $n$ expressions as the first argument showed no benefit and
204 some inelegance.
205
206 \item
207 The second argument, a list giving the ``equation info'' for each of
208 the $m$ equations:
209 \begin{itemize}
210 \item
211 the $n$ patterns for that equation, and
212 \item
213 a list of Core bindings [@(Id, CoreExpr)@ pairs] to be ``stuck on
214 the front'' of the matching code, as in:
215 \begin{verbatim}
216 let <binds>
217 in  <matching-code>
218 \end{verbatim}
219 \item
220 and finally: (ToDo: fill in)
221
222 The right way to think about the ``after-match function'' is that it
223 is an embryonic @CoreExpr@ with a ``hole'' at the end for the
224 final ``else expression''.
225 \end{itemize}
226
227 There is a type synonym, @EquationInfo@, defined in module @DsUtils@.
228
229 An experiment with re-ordering this information about equations (in
230 particular, having the patterns available in column-major order)
231 showed no benefit.
232
233 \item
234 A default expression---what to evaluate if the overall pattern-match
235 fails.  This expression will (almost?) always be
236 a measly expression @Var@, unless we know it will only be used once
237 (as we do in @glue_success_exprs@).
238
239 Leaving out this third argument to @match@ (and slamming in lots of
240 @Var "fail"@s) is a positively {\em bad} idea, because it makes it
241 impossible to share the default expressions.  (Also, it stands no
242 chance of working in our post-upheaval world of @Locals@.)
243 \end{enumerate}
244 So, the full type signature:
245 \begin{code}
246 match :: [Id]             -- Variables rep'ing the exprs we're matching with
247       -> [EquationInfo]   -- Info about patterns, etc. (type synonym below)
248       -> DsM MatchResult  -- Desugared result!
249 \end{code}
250
251 Note: @match@ is often called via @matchWrapper@ (end of this module),
252 a function that does much of the house-keeping that goes with a call
253 to @match@.
254
255 It is also worth mentioning the {\em typical} way a block of equations
256 is desugared with @match@.  At each stage, it is the first column of
257 patterns that is examined.  The steps carried out are roughly:
258 \begin{enumerate}
259 \item
260 Tidy the patterns in column~1 with @tidyEqnInfo@ (this may add
261 bindings to the second component of the equation-info):
262 \begin{itemize}
263 \item
264 Remove the `as' patterns from column~1.
265 \item
266 Make all constructor patterns in column~1 into @ConPats@, notably
267 @ListPats@ and @TuplePats@.
268 \item
269 Handle any irrefutable (or ``twiddle'') @LazyPats@.
270 \end{itemize}
271 \item
272 Now {\em unmix} the equations into {\em blocks} [w/ local function
273 @unmix_eqns@], in which the equations in a block all have variable
274 patterns in column~1, or they all have constructor patterns in ...
275 (see ``the mixture rule'' in SLPJ).
276 \item
277 Call @matchUnmixedEqns@ on each block of equations; it will do the
278 appropriate thing for each kind of column-1 pattern, usually ending up
279 in a recursive call to @match@.
280 \end{enumerate}
281
282 %************************************************************************
283 %*                                                                      *
284 %*  match: empty rule                                                   *
285 %*                                                                      *
286 %************************************************************************
287 \subsection[Match-empty-rule]{The ``empty rule''}
288
289 We are a little more paranoid about the ``empty rule'' (SLPJ, p.~87)
290 than the Wadler-chapter code for @match@ (p.~93, first @match@ clause).
291 And gluing the ``success expressions'' together isn't quite so pretty.
292
293 \begin{code}
294 match [] eqns_info
295   = complete_matches eqns_info
296   where
297     complete_matches [eqn] 
298         = complete_match eqn
299  
300     complete_matches (eqn:eqns)
301         = complete_match eqn            `thenDs` \ match_result1 ->
302           complete_matches eqns         `thenDs` \ match_result2 ->
303           returnDs (combineMatchResults match_result1 match_result2)
304
305     complete_match (EqnInfo _ _ pats match_result)
306         = ASSERT( null pats )
307           returnDs match_result
308 \end{code}
309
310 %************************************************************************
311 %*                                                                      *
312 %*  match: non-empty rule                                               *
313 %*                                                                      *
314 %************************************************************************
315 \subsection[Match-nonempty]{@match@ when non-empty: unmixing}
316
317 This (more interesting) clause of @match@ uses @tidy_and_unmix_eqns@
318 (a)~to get `as'- and `twiddle'-patterns out of the way (tidying), and
319 (b)~to do ``the mixture rule'' (SLPJ, p.~88) [which really {\em
320 un}mixes the equations], producing a list of equation-info
321 blocks, each block having as its first column of patterns either all
322 constructors, or all variables (or similar beasts), etc.
323
324 @match_unmixed_eqn_blks@ simply takes the place of the @foldr@ in the
325 Wadler-chapter @match@ (p.~93, last clause), and @match_unmixed_blk@
326 corresponds roughly to @matchVarCon@.
327
328 \begin{code}
329 match vars@(v:vs) eqns_info
330   = mapDs (tidyEqnInfo v) eqns_info     `thenDs` \ tidy_eqns_info ->
331     let
332         tidy_eqns_blks = unmix_eqns tidy_eqns_info
333     in
334     match_unmixed_eqn_blks vars tidy_eqns_blks
335   where
336     unmix_eqns []    = []
337     unmix_eqns [eqn] = [ [eqn] ]
338     unmix_eqns (eq1@(EqnInfo _ _ (p1:p1s) _) : eq2@(EqnInfo _ _ (p2:p2s) _) : eqs)
339       = if (  (isWildPat p1 && isWildPat p2)
340            || (isConPat  p1 && isConPat  p2)
341            || (isLitPat  p1 && isLitPat  p2) ) then
342             eq1 `tack_onto` unmixed_rest
343         else
344             [ eq1 ] : unmixed_rest
345       where
346         unmixed_rest = unmix_eqns (eq2:eqs)
347
348         x `tack_onto` xss   = ( x : head xss) : tail xss
349
350     -----------------------------------------------------------------------
351     -- loop through the blocks:
352     -- subsequent blocks create a "fail expr" for the first one...
353     match_unmixed_eqn_blks :: [Id]
354                            -> [ [EquationInfo] ]        -- List of eqn BLOCKS
355                            -> DsM MatchResult
356
357     match_unmixed_eqn_blks vars [] = panic "match_unmixed_eqn_blks"
358
359     match_unmixed_eqn_blks vars [eqn_blk] = matchUnmixedEqns vars eqn_blk 
360
361     match_unmixed_eqn_blks vars (eqn_blk:eqn_blks) 
362       = matchUnmixedEqns vars eqn_blk           `thenDs` \ match_result1 ->  -- try to match with first blk
363         match_unmixed_eqn_blks vars eqn_blks    `thenDs` \ match_result2 ->
364         returnDs (combineMatchResults match_result1 match_result2)
365 \end{code}
366
367 Tidy up the leftmost pattern in an @EquationInfo@, given the variable @v@
368 which will be scrutinised.  This means:
369 \begin{itemize}
370 \item
371 Replace variable patterns @x@ (@x /= v@) with the pattern @_@,
372 together with the binding @x = v@.
373 \item
374 Replace the `as' pattern @x@@p@ with the pattern p and a binding @x = v@.
375 \item
376 Removing lazy (irrefutable) patterns (you don't want to know...).
377 \item
378 Converting explicit tuple- and list-pats into ordinary @ConPats@.
379 \item
380 Convert the literal pat "" to [].
381 \end{itemize}
382
383 The result of this tidying is that the column of patterns will include
384 {\em only}:
385 \begin{description}
386 \item[@WildPats@:]
387 The @VarPat@ information isn't needed any more after this.
388
389 \item[@ConPats@:]
390 @ListPats@, @TuplePats@, etc., are all converted into @ConPats@.
391
392 \item[@LitPats@ and @NPats@:]
393 @LitPats@/@NPats@ of ``known friendly types'' (Int, Char,
394 Float,  Double, at least) are converted to unboxed form; e.g.,
395 \tr{(NPat (HsInt i) _ _)} is converted to:
396 \begin{verbatim}
397 (ConPat I# _ _ [LitPat (HsIntPrim i) _])
398 \end{verbatim}
399 \end{description}
400
401 \begin{code}
402 tidyEqnInfo :: Id -> EquationInfo -> DsM EquationInfo
403         -- DsM'd because of internal call to "match".
404         -- "tidy1" does the interesting stuff, looking at
405         -- one pattern and fiddling the list of bindings.
406         --
407         -- POST CONDITION: head pattern in the EqnInfo is
408         --      WildPat
409         --      ConPat
410         --      NPat
411         --      LitPat
412         --      NPlusKPat
413         -- but no other
414
415 tidyEqnInfo v (EqnInfo n ctx (pat : pats) match_result)
416   = tidy1 v pat match_result    `thenDs` \ (pat', match_result') ->
417     returnDs (EqnInfo n ctx (pat' : pats) match_result')
418
419 tidy1 :: Id                                     -- The Id being scrutinised
420       -> TypecheckedPat                         -- The pattern against which it is to be matched
421       -> MatchResult                            -- Current thing do do after matching
422       -> DsM (TypecheckedPat,                   -- Equivalent pattern
423               MatchResult)                      -- Augmented thing to do afterwards
424                                                 -- The augmentation usually takes the form
425                                                 -- of new bindings to be added to the front
426
427 tidy1 v (VarPat var) match_result
428   = returnDs (WildPat (idType var), match_result')
429   where
430     match_result' | v == var  = match_result
431                   | otherwise = adjustMatchResult (bindNonRec var (Var v)) match_result
432
433 tidy1 v (AsPat var pat) match_result
434   = tidy1 v pat match_result'
435   where
436     match_result' | v == var  = match_result
437                   | otherwise = adjustMatchResult (bindNonRec var (Var v)) match_result
438
439 tidy1 v (WildPat ty) match_result
440   = returnDs (WildPat ty, match_result)
441
442 {- now, here we handle lazy patterns:
443     tidy1 v ~p bs = (v, v1 = case v of p -> v1 :
444                         v2 = case v of p -> v2 : ... : bs )
445
446     where the v_i's are the binders in the pattern.
447
448     ToDo: in "v_i = ... -> v_i", are the v_i's really the same thing?
449
450     The case expr for v_i is just: match [v] [(p, [], \ x -> Var v_i)] any_expr
451 -}
452
453 tidy1 v (LazyPat pat) match_result
454   = mkSelectorBinds pat (Var v)         `thenDs` \ sel_binds ->
455     returnDs (WildPat (idType v),
456               mkCoLetsMatchResult [NonRec b rhs | (b,rhs) <- sel_binds] match_result)
457
458 -- re-express <con-something> as (ConPat ...) [directly]
459
460 tidy1 v (RecPat data_con pat_ty ex_tvs dicts rpats) match_result
461   | null rpats
462   =     -- Special case for C {}, which can be used for 
463         -- a constructor that isn't declared to have
464         -- fields at all
465     returnDs (ConPat data_con pat_ty ex_tvs dicts (map WildPat con_arg_tys'), match_result)
466
467   | otherwise
468   = returnDs (ConPat data_con pat_ty ex_tvs dicts pats, match_result)
469   where
470     pats             = map mk_pat tagged_arg_tys
471
472         -- Boring stuff to find the arg-tys of the constructor
473     (_, inst_tys, _) = splitAlgTyConApp pat_ty
474     con_arg_tys'     = dataConInstOrigArgTys data_con (inst_tys ++ mkTyVarTys ex_tvs)
475     tagged_arg_tys   = con_arg_tys' `zip` (dataConFieldLabels data_con)
476
477         -- mk_pat picks a WildPat of the appropriate type for absent fields,
478         -- and the specified pattern for present fields
479     mk_pat (arg_ty, lbl) = case [pat | (sel_id,pat,_) <- rpats,
480                                         recordSelectorFieldLabel sel_id == lbl
481                                 ] of
482                                 (pat:pats) -> ASSERT( null pats )
483                                               pat
484                                 []         -> WildPat arg_ty
485
486 tidy1 v (ListPat ty pats) match_result
487   = returnDs (list_ConPat, match_result)
488   where
489     list_ty = mkListTy ty
490     list_ConPat
491       = foldr (\ x -> \y -> ConPat consDataCon list_ty [] [] [x, y])
492               (ConPat nilDataCon  list_ty [] [] [])
493               pats
494
495 tidy1 v (TuplePat pats boxity) match_result
496   = returnDs (tuple_ConPat, match_result)
497   where
498     arity = length pats
499     tuple_ConPat
500       = ConPat (tupleCon boxity arity)
501                (mkTupleTy boxity arity (map outPatType pats)) [] [] 
502                pats
503
504 tidy1 v (DictPat dicts methods) match_result
505   = case num_of_d_and_ms of
506         0 -> tidy1 v (TuplePat [] Boxed) match_result
507         1 -> tidy1 v (head dict_and_method_pats) match_result
508         _ -> tidy1 v (TuplePat dict_and_method_pats Boxed) match_result
509   where
510     num_of_d_and_ms      = length dicts + length methods
511     dict_and_method_pats = map VarPat (dicts ++ methods)
512
513 -- LitPats: we *might* be able to replace these w/ a simpler form
514 tidy1 v pat@(LitPat lit lit_ty) match_result
515   = returnDs (tidyLitPat lit pat, match_result)
516
517 -- NPats: we *might* be able to replace these w/ a simpler form
518 tidy1 v pat@(NPat lit lit_ty _) match_result
519   = returnDs (tidyNPat lit lit_ty pat, match_result)
520
521 -- and everything else goes through unchanged...
522
523 tidy1 v non_interesting_pat match_result
524   = returnDs (non_interesting_pat, match_result)
525 \end{code}
526
527 \noindent
528 {\bf Previous @matchTwiddled@ stuff:}
529
530 Now we get to the only interesting part; note: there are choices for
531 translation [from Simon's notes]; translation~1:
532 \begin{verbatim}
533 deTwiddle [s,t] e
534 \end{verbatim}
535 returns
536 \begin{verbatim}
537 [ w = e,
538   s = case w of [s,t] -> s
539   t = case w of [s,t] -> t
540 ]
541 \end{verbatim}
542
543 Here \tr{w} is a fresh variable, and the \tr{w}-binding prevents multiple
544 evaluation of \tr{e}.  An alternative translation (No.~2):
545 \begin{verbatim}
546 [ w = case e of [s,t] -> (s,t)
547   s = case w of (s,t) -> s
548   t = case w of (s,t) -> t
549 ]
550 \end{verbatim}
551
552 %************************************************************************
553 %*                                                                      *
554 \subsubsection[improved-unmixing]{UNIMPLEMENTED idea for improved unmixing}
555 %*                                                                      *
556 %************************************************************************
557
558 We might be able to optimise unmixing when confronted by
559 only-one-constructor-possible, of which tuples are the most notable
560 examples.  Consider:
561 \begin{verbatim}
562 f (a,b,c) ... = ...
563 f d ... (e:f) = ...
564 f (g,h,i) ... = ...
565 f j ...       = ...
566 \end{verbatim}
567 This definition would normally be unmixed into four equation blocks,
568 one per equation.  But it could be unmixed into just one equation
569 block, because if the one equation matches (on the first column),
570 the others certainly will.
571
572 You have to be careful, though; the example
573 \begin{verbatim}
574 f j ...       = ...
575 -------------------
576 f (a,b,c) ... = ...
577 f d ... (e:f) = ...
578 f (g,h,i) ... = ...
579 \end{verbatim}
580 {\em must} be broken into two blocks at the line shown; otherwise, you
581 are forcing unnecessary evaluation.  In any case, the top-left pattern
582 always gives the cue.  You could then unmix blocks into groups of...
583 \begin{description}
584 \item[all variables:]
585 As it is now.
586 \item[constructors or variables (mixed):]
587 Need to make sure the right names get bound for the variable patterns.
588 \item[literals or variables (mixed):]
589 Presumably just a variant on the constructor case (as it is now).
590 \end{description}
591
592 %************************************************************************
593 %*                                                                      *
594 %* match on an unmixed block: the real business                         *
595 %*                                                                      *
596 %************************************************************************
597 \subsection[matchUnmixedEqns]{@matchUnmixedEqns@: getting down to business}
598
599 The function @matchUnmixedEqns@ is where the matching stuff sets to
600 work a block of equations, to which the mixture rule has been applied.
601 Its arguments and results are the same as for the ``top-level'' @match@.
602
603 \begin{code}
604 matchUnmixedEqns :: [Id]
605                   -> [EquationInfo]
606                   -> DsM MatchResult
607
608 matchUnmixedEqns [] _ = panic "matchUnmixedEqns: no names"
609
610 matchUnmixedEqns all_vars@(var:vars) eqns_info 
611   | isWildPat first_pat
612   = ASSERT( all isWildPat column_1_pats )       -- Sanity check
613         -- Real true variables, just like in matchVar, SLPJ p 94
614         -- No binding to do: they'll all be wildcards by now (done in tidy)
615     match vars remaining_eqns_info
616
617   | isConPat first_pat
618   = ASSERT( patsAreAllCons column_1_pats )
619     matchConFamily all_vars eqns_info 
620
621   | isLitPat first_pat
622   = ASSERT( patsAreAllLits column_1_pats )
623         -- see notes in MatchLiteral
624         -- not worried about the same literal more than once in a column
625         -- (ToDo: sort this out later)
626     matchLiterals all_vars eqns_info
627
628   where
629     first_pat           = head column_1_pats
630     column_1_pats       = [pat                       | EqnInfo _ _ (pat:_)  _            <- eqns_info]
631     remaining_eqns_info = [EqnInfo n ctx pats match_result | EqnInfo n ctx (_:pats) match_result <- eqns_info]
632 \end{code}
633
634 %************************************************************************
635 %*                                                                      *
636 %*  matchWrapper: a convenient way to call @match@                      *
637 %*                                                                      *
638 %************************************************************************
639 \subsection[matchWrapper]{@matchWrapper@: a convenient interface to @match@}
640
641 Calls to @match@ often involve similar (non-trivial) work; that work
642 is collected here, in @matchWrapper@.  This function takes as
643 arguments:
644 \begin{itemize}
645 \item
646 Typchecked @Matches@ (of a function definition, or a case or lambda
647 expression)---the main input;
648 \item
649 An error message to be inserted into any (runtime) pattern-matching
650 failure messages.
651 \end{itemize}
652
653 As results, @matchWrapper@ produces:
654 \begin{itemize}
655 \item
656 A list of variables (@Locals@) that the caller must ``promise'' to
657 bind to appropriate values; and
658 \item
659 a @CoreExpr@, the desugared output (main result).
660 \end{itemize}
661
662 The main actions of @matchWrapper@ include:
663 \begin{enumerate}
664 \item
665 Flatten the @[TypecheckedMatch]@ into a suitable list of
666 @EquationInfo@s.
667 \item
668 Create as many new variables as there are patterns in a pattern-list
669 (in any one of the @EquationInfo@s).
670 \item
671 Create a suitable ``if it fails'' expression---a call to @error@ using
672 the error-string input; the {\em type} of this fail value can be found
673 by examining one of the RHS expressions in one of the @EquationInfo@s.
674 \item
675 Call @match@ with all of this information!
676 \end{enumerate}
677
678 \begin{code}
679 matchWrapper :: DsMatchKind                     -- For shadowing warning messages
680              -> [TypecheckedMatch]              -- Matches being desugared
681              -> String                          -- Error message if the match fails
682              -> DsM ([Id], CoreExpr)    -- Results
683 \end{code}
684
685  There is one small problem with the Lambda Patterns, when somebody
686  writes something similar to:
687 \begin{verbatim}
688     (\ (x:xs) -> ...)
689 \end{verbatim}
690  he/she don't want a warning about incomplete patterns, that is done with 
691  the flag @opt_WarnSimplePatterns@.
692  This problem also appears in the:
693 \begin{itemize}
694 \item @do@ patterns, but if the @do@ can fail
695       it creates another equation if the match can fail
696       (see @DsExpr.doDo@ function)
697 \item @let@ patterns, are treated by @matchSimply@
698    List Comprension Patterns, are treated by @matchSimply@ also
699 \end{itemize}
700
701 We can't call @matchSimply@ with Lambda patterns,
702 due to the fact that lambda patterns can have more than
703 one pattern, and match simply only accepts one pattern.
704
705 JJQC 30-Nov-1997
706
707 \begin{code}
708 matchWrapper kind matches error_string
709   = getDOptsDs                                  `thenDs` \ dflags ->
710     flattenMatches kind matches                 `thenDs` \ (result_ty, eqns_info) ->
711     let
712         EqnInfo _ _ arg_pats _ : _ = eqns_info
713     in
714     mapDs selectMatchVar arg_pats               `thenDs` \ new_vars ->
715     match_fun dflags new_vars eqns_info         `thenDs` \ match_result ->
716
717     mkErrorAppDs pAT_ERROR_ID result_ty error_string    `thenDs` \ fail_expr ->
718     extractMatchResult match_result fail_expr           `thenDs` \ result_expr ->
719     returnDs (new_vars, result_expr)
720   where match_fun dflags
721            = case kind of 
722                 LambdaMatch | dopt Opt_WarnSimplePatterns dflags -> matchExport 
723                             | otherwise                          -> match
724                 _                                                -> matchExport
725 \end{code}
726
727 %************************************************************************
728 %*                                                                      *
729 \subsection[matchSimply]{@matchSimply@: match a single expression against a single pattern}
730 %*                                                                      *
731 %************************************************************************
732
733 @mkSimpleMatch@ is a wrapper for @match@ which deals with the
734 situation where we want to match a single expression against a single
735 pattern. It returns an expression.
736
737 \begin{code}
738 matchSimply :: CoreExpr                 -- Scrutinee
739             -> DsMatchKind              -- Match kind
740             -> TypecheckedPat           -- Pattern it should match
741             -> CoreExpr                 -- Return this if it matches
742             -> CoreExpr                 -- Return this if it doesn't
743             -> DsM CoreExpr
744
745 matchSimply scrut kind pat result_expr fail_expr
746   = getSrcLocDs                                 `thenDs` \ locn ->
747     let
748       ctx          = DsMatchContext kind [pat] locn
749       match_result = cantFailMatchResult result_expr
750     in 
751     matchSinglePat scrut ctx pat match_result   `thenDs` \ match_result' ->
752     extractMatchResult match_result' fail_expr
753
754
755 matchSinglePat :: CoreExpr -> DsMatchContext -> TypecheckedPat
756                -> MatchResult -> DsM MatchResult
757
758 matchSinglePat (Var var) ctx pat match_result
759   = getDOptsDs                                  `thenDs` \ dflags ->
760     match_fn dflags [var] [EqnInfo 1 ctx [pat] match_result]
761   where
762     match_fn dflags
763        | dopt Opt_WarnSimplePatterns dflags = matchExport
764        | otherwise                          = match
765
766 matchSinglePat scrut ctx pat match_result
767   = selectMatchVar pat                                  `thenDs` \ var ->
768     matchSinglePat (Var var) ctx pat match_result       `thenDs` \ match_result' ->
769     returnDs (adjustMatchResult (bindNonRec var scrut) match_result')
770 \end{code}
771
772 %************************************************************************
773 %*                                                                      *
774 %*  flattenMatches : create a list of EquationInfo                      *
775 %*                                                                      *
776 %************************************************************************
777
778 \subsection[flattenMatches]{@flattenMatches@: create @[EquationInfo]@}
779
780 This is actually local to @matchWrapper@.
781
782 \begin{code}
783 flattenMatches
784         :: DsMatchKind
785         -> [TypecheckedMatch]
786         -> DsM (Type, [EquationInfo])
787
788 flattenMatches kind matches
789   = mapAndUnzipDs flatten_match (matches `zip` [1..])   `thenDs` \ (result_tys, eqn_infos) ->
790     let
791         result_ty = head result_tys
792     in
793     ASSERT( all (== result_ty) result_tys )
794     returnDs (result_ty, eqn_infos)
795   where
796     flatten_match (Match _ pats _ grhss, n)
797       = dsGRHSs kind pats grhss                 `thenDs` \ (ty, match_result) ->
798         getSrcLocDs                             `thenDs` \ locn ->
799         returnDs (ty, EqnInfo n (DsMatchContext kind pats locn) pats match_result)
800 \end{code}