c822765110fc4d9f3a3acad8502ed00166f42720
[ghc-hetmet.git] / ghc / compiler / deSugar / Match.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[Main_match]{The @match@ function}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module Match ( match, matchWrapper, matchSimply ) where
10
11 IMP_Ubiq()
12 IMPORT_DELOOPER(DsLoop)         -- here for paranoia-checking reasons
13                         -- and to break dsExpr/dsBinds-ish loop
14
15 import HsSyn            hiding ( collectBinders{-also from CoreSyn-} )
16 import TcHsSyn          ( SYN_IE(TypecheckedPat), SYN_IE(TypecheckedMatch),
17                           SYN_IE(TypecheckedHsBinds), SYN_IE(TypecheckedHsExpr) )
18 import DsHsSyn          ( outPatType, collectTypedPatBinders )
19 import CoreSyn
20
21 import CoreUtils        ( coreExprType )
22 import DsMonad
23 import DsGRHSs          ( dsGRHSs )
24 import DsUtils
25 import MatchCon         ( matchConFamily )
26 import MatchLit         ( matchLiterals )
27
28 import FieldLabel       ( FieldLabel {- Eq instance -} )
29 import Id               ( idType, dataConFieldLabels,
30                           dataConArgTys, recordSelectorFieldLabel,
31                           GenId{-instance-}
32                         )
33 import Name             ( Name {--O only-} )
34 import PprStyle         ( PprStyle(..) )
35 import PprType          ( GenType{-instance-}, GenTyVar{-ditto-} )
36 import PrelVals         ( pAT_ERROR_ID )
37 import Type             ( isPrimType, eqTy, getAppDataTyConExpandingDicts,
38                           instantiateTauTy
39                         )
40 import TyVar            ( GenTyVar{-instance Eq-} )
41 import TysPrim          ( intPrimTy, charPrimTy, floatPrimTy, doublePrimTy,
42                           addrPrimTy, wordPrimTy
43                         )
44 import TysWiredIn       ( nilDataCon, consDataCon, mkTupleTy, mkListTy,
45                           charTy, charDataCon, intTy, intDataCon,
46                           floatTy, floatDataCon, doubleTy, tupleCon,
47                           doubleDataCon, stringTy, addrTy,
48                           addrDataCon, wordTy, wordDataCon
49                         )
50 import Unique           ( Unique{-instance Eq-} )
51 import Util             ( panic, pprPanic, assertPanic )
52 \end{code}
53
54 The function @match@ is basically the same as in the Wadler chapter,
55 except it is monadised, to carry around the name supply, info about
56 annotations, etc.
57
58 Notes on @match@'s arguments, assuming $m$ equations and $n$ patterns:
59 \begin{enumerate}
60 \item
61 A list of $n$ variable names, those variables presumably bound to the
62 $n$ expressions being matched against the $n$ patterns.  Using the
63 list of $n$ expressions as the first argument showed no benefit and
64 some inelegance.
65
66 \item
67 The second argument, a list giving the ``equation info'' for each of
68 the $m$ equations:
69 \begin{itemize}
70 \item
71 the $n$ patterns for that equation, and
72 \item
73 a list of Core bindings [@(Id, CoreExpr)@ pairs] to be ``stuck on
74 the front'' of the matching code, as in:
75 \begin{verbatim}
76 let <binds>
77 in  <matching-code>
78 \end{verbatim}
79 \item
80 and finally: (ToDo: fill in)
81
82 The right way to think about the ``after-match function'' is that it
83 is an embryonic @CoreExpr@ with a ``hole'' at the end for the
84 final ``else expression''.
85 \end{itemize}
86
87 There is a type synonym, @EquationInfo@, defined in module @DsUtils@.
88
89 An experiment with re-ordering this information about equations (in
90 particular, having the patterns available in column-major order)
91 showed no benefit.
92
93 \item
94 A default expression---what to evaluate if the overall pattern-match
95 fails.  This expression will (almost?) always be
96 a measly expression @Var@, unless we know it will only be used once
97 (as we do in @glue_success_exprs@).
98
99 Leaving out this third argument to @match@ (and slamming in lots of
100 @Var "fail"@s) is a positively {\em bad} idea, because it makes it
101 impossible to share the default expressions.  (Also, it stands no
102 chance of working in our post-upheaval world of @Locals@.)
103 \end{enumerate}
104 So, the full type signature:
105 \begin{code}
106 match :: [Id]             -- Variables rep'ing the exprs we're matching with
107       -> [EquationInfo]   -- Info about patterns, etc. (type synonym below)
108       -> [EquationInfo]   -- Potentially shadowing equations above this one
109       -> DsM MatchResult  -- Desugared result!
110 \end{code}
111
112 Note: @match@ is often called via @matchWrapper@ (end of this module),
113 a function that does much of the house-keeping that goes with a call
114 to @match@.
115
116 It is also worth mentioning the {\em typical} way a block of equations
117 is desugared with @match@.  At each stage, it is the first column of
118 patterns that is examined.  The steps carried out are roughly:
119 \begin{enumerate}
120 \item
121 Tidy the patterns in column~1 with @tidyEqnInfo@ (this may add
122 bindings to the second component of the equation-info):
123 \begin{itemize}
124 \item
125 Remove the `as' patterns from column~1.
126 \item
127 Make all constructor patterns in column~1 into @ConPats@, notably
128 @ListPats@ and @TuplePats@.
129 \item
130 Handle any irrefutable (or ``twiddle'') @LazyPats@.
131 \end{itemize}
132 \item
133 Now {\em unmix} the equations into {\em blocks} [w/ local function
134 @unmix_eqns@], in which the equations in a block all have variable
135 patterns in column~1, or they all have constructor patterns in ...
136 (see ``the mixture rule'' in SLPJ).
137 \item
138 Call @matchUnmixedEqns@ on each block of equations; it will do the
139 appropriate thing for each kind of column-1 pattern, usually ending up
140 in a recursive call to @match@.
141 \end{enumerate}
142
143 %************************************************************************
144 %*                                                                      *
145 %*  match: empty rule                                                   *
146 %*                                                                      *
147 %************************************************************************
148 \subsection[Match-empty-rule]{The ``empty rule''}
149
150 We are a little more paranoid about the ``empty rule'' (SLPJ, p.~87)
151 than the Wadler-chapter code for @match@ (p.~93, first @match@ clause).
152 And gluing the ``success expressions'' together isn't quite so pretty.
153
154 \begin{code}
155 match [] eqns_info shadows
156   = pin_eqns eqns_info          `thenDs` \ match_result@(MatchResult _ _ _ cxt) ->
157
158         -- If at this stage we find that at least one of the shadowing
159         -- equations is guaranteed not to fail, then warn of an overlapping pattern
160     if not (all shadow_can_fail shadows) then
161         dsShadowError cxt       `thenDs` \ _ ->
162         returnDs match_result
163     else
164         returnDs match_result
165
166   where
167     pin_eqns [EqnInfo [] match_result] = returnDs match_result
168       -- Last eqn... can't have pats ...
169
170     pin_eqns (EqnInfo [] match_result1 : more_eqns)
171       = pin_eqns more_eqns                      `thenDs` \ match_result2 ->
172         combineMatchResults match_result1 match_result2
173
174     pin_eqns other_pat = panic "match: pin_eqns"
175
176     shadow_can_fail :: EquationInfo -> Bool
177
178     shadow_can_fail (EqnInfo [] (MatchResult CanFail  _ _ _)) = True
179     shadow_can_fail (EqnInfo [] (MatchResult CantFail _ _ _)) = False
180     shadow_can_fail other = panic "match:shadow_can_fail"
181 \end{code}
182
183 %************************************************************************
184 %*                                                                      *
185 %*  match: non-empty rule                                               *
186 %*                                                                      *
187 %************************************************************************
188 \subsection[Match-nonempty]{@match@ when non-empty: unmixing}
189
190 This (more interesting) clause of @match@ uses @tidy_and_unmix_eqns@
191 (a)~to get `as'- and `twiddle'-patterns out of the way (tidying), and
192 (b)~to do ``the mixture rule'' (SLPJ, p.~88) [which really {\em
193 un}mixes the equations], producing a list of equation-info
194 blocks, each block having as its first column of patterns either all
195 constructors, or all variables (or similar beasts), etc.
196
197 @match_unmixed_eqn_blks@ simply takes the place of the @foldr@ in the
198 Wadler-chapter @match@ (p.~93, last clause), and @match_unmixed_blk@
199 corresponds roughly to @matchVarCon@.
200
201 \begin{code}
202 match vars@(v:vs) eqns_info shadows
203   = mapDs (tidyEqnInfo v) eqns_info     `thenDs` \ tidy_eqns_info ->
204     mapDs (tidyEqnInfo v) shadows       `thenDs` \ tidy_shadows ->
205     let
206         tidy_eqns_blks = unmix_eqns tidy_eqns_info
207     in
208     match_unmixed_eqn_blks vars tidy_eqns_blks tidy_shadows
209   where
210     unmix_eqns []    = []
211     unmix_eqns [eqn] = [ [eqn] ]
212     unmix_eqns (eq1@(EqnInfo (p1:p1s) _) : eq2@(EqnInfo (p2:p2s) _) : eqs)
213       = if (  (irrefutablePat p1 && irrefutablePat p2)
214            || (isConPat       p1 && isConPat       p2)
215            || (isLitPat       p1 && isLitPat       p2) ) then
216             eq1 `tack_onto` unmixed_rest
217         else
218             [ eq1 ] : unmixed_rest
219       where
220         unmixed_rest = unmix_eqns (eq2:eqs)
221
222         x `tack_onto` xss   = ( x : head xss) : tail xss
223
224     -----------------------------------------------------------------------
225     -- loop through the blocks:
226     -- subsequent blocks create a "fail expr" for the first one...
227     match_unmixed_eqn_blks :: [Id]
228                            -> [ [EquationInfo] ]        -- List of eqn BLOCKS
229                            -> [EquationInfo]            -- Shadows
230                            -> DsM MatchResult
231
232     match_unmixed_eqn_blks vars [] shadows = panic "match_unmixed_eqn_blks"
233
234     match_unmixed_eqn_blks vars [eqn_blk] shadows = matchUnmixedEqns vars eqn_blk shadows
235
236     match_unmixed_eqn_blks vars (eqn_blk:eqn_blks) shadows
237       = matchUnmixedEqns vars eqn_blk shadows           `thenDs` \ match_result1 ->  -- try to match with first blk
238         match_unmixed_eqn_blks vars eqn_blks shadows'   `thenDs` \ match_result2 ->
239         combineMatchResults match_result1 match_result2
240       where
241         shadows' = eqn_blk ++ shadows
242 \end{code}
243
244 Tidy up the leftmost pattern in an @EquationInfo@, given the variable @v@
245 which will be scrutinised.  This means:
246 \begin{itemize}
247 \item
248 Replace variable patterns @x@ (@x /= v@) with the pattern @_@,
249 together with the binding @x = v@.
250 \item
251 Replace the `as' pattern @x@@p@ with the pattern p and a binding @x = v@.
252 \item
253 Removing lazy (irrefutable) patterns (you don't want to know...).
254 \item
255 Converting explicit tuple- and list-pats into ordinary @ConPats@.
256 \end{itemize}
257
258 The result of this tidying is that the column of patterns will include
259 {\em only}:
260 \begin{description}
261 \item[@WildPats@:]
262 The @VarPat@ information isn't needed any more after this.
263
264 \item[@ConPats@:]
265 @ListPats@, @TuplePats@, etc., are all converted into @ConPats@.
266
267 \item[@LitPats@ and @NPats@:]
268 @LitPats@/@NPats@ of ``known friendly types'' (Int, Char,
269 Float,  Double, at least) are converted to unboxed form; e.g.,
270 \tr{(NPat (HsInt i) _ _)} is converted to:
271 \begin{verbatim}
272 (ConPat I# _ _ [LitPat (HsIntPrim i) _])
273 \end{verbatim}
274 \end{description}
275
276 \begin{code}
277 tidyEqnInfo :: Id -> EquationInfo -> DsM EquationInfo
278         -- DsM'd because of internal call to "match".
279         -- "tidy1" does the interesting stuff, looking at
280         -- one pattern and fiddling the list of bindings.
281 tidyEqnInfo v (EqnInfo (pat : pats) match_result)
282   = tidy1 v pat match_result    `thenDs` \ (pat', match_result') ->
283     returnDs (EqnInfo (pat' : pats) match_result')
284
285 tidy1 :: Id                                     -- The Id being scrutinised
286       -> TypecheckedPat                         -- The pattern against which it is to be matched
287       -> MatchResult                            -- Current thing do do after matching
288       -> DsM (TypecheckedPat,                   -- Equivalent pattern
289               MatchResult)                      -- Augmented thing to do afterwards
290                                                 -- The augmentation usually takes the form
291                                                 -- of new bindings to be added to the front
292
293 tidy1 v (VarPat var) match_result
294   = returnDs (WildPat (idType var),
295               mkCoLetsMatchResult extra_binds match_result)
296   where
297     extra_binds | v == var  = []
298                 | otherwise = [NonRec var (Var v)]
299
300 tidy1 v (AsPat var pat) match_result
301   = tidy1 v pat (mkCoLetsMatchResult extra_binds match_result)
302   where
303     extra_binds | v == var  = []
304                 | otherwise = [NonRec var (Var v)]
305
306 tidy1 v (WildPat ty) match_result
307   = returnDs (WildPat ty, match_result)
308
309 {- now, here we handle lazy patterns:
310     tidy1 v ~p bs = (v, v1 = case v of p -> v1 :
311                         v2 = case v of p -> v2 : ... : bs )
312
313     where the v_i's are the binders in the pattern.
314
315     ToDo: in "v_i = ... -> v_i", are the v_i's really the same thing?
316
317     The case expr for v_i is just: match [v] [(p, [], \ x -> Var v_i)] any_expr
318 -}
319
320 tidy1 v (LazyPat pat) match_result
321   = mkSelectorBinds [] pat l_to_l (Var v)       `thenDs` \ sel_binds ->
322     returnDs (WildPat (idType v),
323               mkCoLetsMatchResult [NonRec b rhs | (b,rhs) <- sel_binds] match_result)
324   where
325     l_to_l = binders `zip` binders      -- Boring
326     binders = collectTypedPatBinders pat
327
328 -- re-express <con-something> as (ConPat ...) [directly]
329
330 tidy1 v (ConOpPat pat1 id pat2 ty) match_result
331   = returnDs (ConPat id ty [pat1, pat2], match_result)
332
333 tidy1 v (RecPat con_id pat_ty rpats) match_result
334   = returnDs (ConPat con_id pat_ty pats, match_result)
335   where
336     pats             = map mk_pat tagged_arg_tys
337
338         -- Boring stuff to find the arg-tys of the constructor
339     (_, inst_tys, _) = {-trace "Match.getAppDataTyConExpandingDicts" $-} getAppDataTyConExpandingDicts pat_ty
340     con_arg_tys'     = dataConArgTys con_id inst_tys 
341     tagged_arg_tys   = con_arg_tys' `zip` (dataConFieldLabels con_id)
342
343         -- mk_pat picks a WildPat of the appropriate type for absent fields,
344         -- and the specified pattern for present fields
345     mk_pat (arg_ty, lbl) = case [pat | (sel_id,pat,_) <- rpats,
346                                         recordSelectorFieldLabel sel_id == lbl
347                                 ] of
348                                 (pat:pats) -> ASSERT( null pats )
349                                               pat
350                                 []         -> WildPat arg_ty
351
352 tidy1 v (ListPat ty pats) match_result
353   = returnDs (list_ConPat, match_result)
354   where
355     list_ty = mkListTy ty
356     list_ConPat
357       = foldr (\ x -> \y -> ConPat consDataCon list_ty [x, y])
358               (ConPat nilDataCon  list_ty [])
359               pats
360
361 tidy1 v (TuplePat pats) match_result
362   = returnDs (tuple_ConPat, match_result)
363   where
364     arity = length pats
365     tuple_ConPat
366       = ConPat (tupleCon arity)
367                (mkTupleTy arity (map outPatType pats))
368                pats
369
370 tidy1 v (DictPat dicts methods) match_result
371   = case num_of_d_and_ms of
372         0 -> tidy1 v (TuplePat []) match_result
373         1 -> tidy1 v (head dict_and_method_pats) match_result
374         _ -> tidy1 v (TuplePat dict_and_method_pats) match_result
375   where
376     num_of_d_and_ms      = length dicts + length methods
377     dict_and_method_pats = map VarPat (dicts ++ methods)
378
379
380 -- deeply ugly mangling for some (common) NPats/LitPats
381
382 -- LitPats: the desugarer only sees these at well-known types
383
384 tidy1 v pat@(LitPat lit lit_ty) match_result
385   | isPrimType lit_ty
386   = returnDs (pat, match_result)
387
388   | lit_ty `eqTy` charTy
389   = returnDs (ConPat charDataCon charTy [LitPat (mk_char lit) charPrimTy],
390               match_result)
391
392   | otherwise = pprPanic "tidy1:LitPat:" (ppr PprDebug pat)
393   where
394     mk_char (HsChar c)    = HsCharPrim c
395
396 -- NPats: we *might* be able to replace these w/ a simpler form
397
398 tidy1 v pat@(NPat lit lit_ty _) match_result
399   = returnDs (better_pat, match_result)
400   where
401     better_pat
402       | lit_ty `eqTy` charTy   = ConPat charDataCon   lit_ty [LitPat (mk_char lit)   charPrimTy]
403       | lit_ty `eqTy` intTy    = ConPat intDataCon    lit_ty [LitPat (mk_int lit)    intPrimTy]
404       | lit_ty `eqTy` wordTy   = ConPat wordDataCon   lit_ty [LitPat (mk_word lit)   wordPrimTy]
405       | lit_ty `eqTy` addrTy   = ConPat addrDataCon   lit_ty [LitPat (mk_addr lit)   addrPrimTy]
406       | lit_ty `eqTy` floatTy  = ConPat floatDataCon  lit_ty [LitPat (mk_float lit)  floatPrimTy]
407       | lit_ty `eqTy` doubleTy = ConPat doubleDataCon lit_ty [LitPat (mk_double lit) doublePrimTy]
408       | otherwise          = pat
409
410     mk_int    (HsInt i)      = HsIntPrim i
411     mk_int    l@(HsLitLit s) = l
412
413     mk_char   (HsChar c)     = HsCharPrim c
414     mk_char   l@(HsLitLit s) = l
415
416     mk_word   l@(HsLitLit s) = l
417
418     mk_addr   l@(HsLitLit s) = l
419
420     mk_float  (HsInt i)      = HsFloatPrim (fromInteger i)
421     mk_float  (HsFrac f)     = HsFloatPrim f
422     mk_float  l@(HsLitLit s) = l
423
424     mk_double (HsInt i)      = HsDoublePrim (fromInteger i)
425     mk_double (HsFrac f)     = HsDoublePrim f
426     mk_double l@(HsLitLit s) = l
427
428 -- and everything else goes through unchanged...
429
430 tidy1 v non_interesting_pat match_result
431   = returnDs (non_interesting_pat, match_result)
432 \end{code}
433
434 PREVIOUS matchTwiddled STUFF:
435
436 Now we get to the only interesting part; note: there are choices for
437 translation [from Simon's notes]; translation~1:
438 \begin{verbatim}
439 deTwiddle [s,t] e
440 \end{verbatim}
441 returns
442 \begin{verbatim}
443 [ w = e,
444   s = case w of [s,t] -> s
445   t = case w of [s,t] -> t
446 ]
447 \end{verbatim}
448
449 Here \tr{w} is a fresh variable, and the \tr{w}-binding prevents multiple
450 evaluation of \tr{e}.  An alternative translation (No.~2):
451 \begin{verbatim}
452 [ w = case e of [s,t] -> (s,t)
453   s = case w of (s,t) -> s
454   t = case w of (s,t) -> t
455 ]
456 \end{verbatim}
457
458 %************************************************************************
459 %*                                                                      *
460 \subsubsection[improved-unmixing]{UNIMPLEMENTED idea for improved unmixing}
461 %*                                                                      *
462 %************************************************************************
463
464 We might be able to optimise unmixing when confronted by
465 only-one-constructor-possible, of which tuples are the most notable
466 examples.  Consider:
467 \begin{verbatim}
468 f (a,b,c) ... = ...
469 f d ... (e:f) = ...
470 f (g,h,i) ... = ...
471 f j ...       = ...
472 \end{verbatim}
473 This definition would normally be unmixed into four equation blocks,
474 one per equation.  But it could be unmixed into just one equation
475 block, because if the one equation matches (on the first column),
476 the others certainly will.
477
478 You have to be careful, though; the example
479 \begin{verbatim}
480 f j ...       = ...
481 -------------------
482 f (a,b,c) ... = ...
483 f d ... (e:f) = ...
484 f (g,h,i) ... = ...
485 \end{verbatim}
486 {\em must} be broken into two blocks at the line shown; otherwise, you
487 are forcing unnecessary evaluation.  In any case, the top-left pattern
488 always gives the cue.  You could then unmix blocks into groups of...
489 \begin{description}
490 \item[all variables:]
491 As it is now.
492 \item[constructors or variables (mixed):]
493 Need to make sure the right names get bound for the variable patterns.
494 \item[literals or variables (mixed):]
495 Presumably just a variant on the constructor case (as it is now).
496 \end{description}
497
498 %************************************************************************
499 %*                                                                      *
500 %* match on an unmixed block: the real business                         *
501 %*                                                                      *
502 %************************************************************************
503 \subsection[matchUnmixedEqns]{@matchUnmixedEqns@: getting down to business}
504
505 The function @matchUnmixedEqns@ is where the matching stuff sets to
506 work a block of equations, to which the mixture rule has been applied.
507 Its arguments and results are the same as for the ``top-level'' @match@.
508
509 \begin{code}
510 matchUnmixedEqns :: [Id]
511                   -> [EquationInfo]
512                   -> [EquationInfo]             -- Shadows
513                   -> DsM MatchResult
514
515 matchUnmixedEqns [] _ _ = panic "matchUnmixedEqns: no names"
516
517 matchUnmixedEqns all_vars@(var:vars) eqns_info shadows
518   | irrefutablePat first_pat
519   = ASSERT( irrefutablePats column_1_pats )     -- Sanity check
520         -- Real true variables, just like in matchVar, SLPJ p 94
521     match vars remaining_eqns_info remaining_shadows
522
523   | isConPat first_pat
524   = ASSERT( patsAreAllCons column_1_pats )
525     matchConFamily all_vars eqns_info shadows
526
527   | isLitPat first_pat
528   = ASSERT( patsAreAllLits column_1_pats )
529         -- see notes in MatchLiteral
530         -- not worried about the same literal more than once in a column
531         -- (ToDo: sort this out later)
532     matchLiterals all_vars eqns_info shadows
533
534   where
535     first_pat           = head column_1_pats
536     column_1_pats       = [pat                       | EqnInfo (pat:_)  _            <- eqns_info]
537     remaining_eqns_info = [EqnInfo pats match_result | EqnInfo (_:pats) match_result <- eqns_info]
538     remaining_shadows   = [EqnInfo pats match_result | EqnInfo (pat:pats) match_result <- shadows,
539                                                        irrefutablePat pat ]
540         -- Discard shadows which can be refuted, since they don't shadow
541         -- a variable
542 \end{code}
543
544 %************************************************************************
545 %*                                                                      *
546 %*  matchWrapper: a convenient way to call @match@                      *
547 %*                                                                      *
548 %************************************************************************
549 \subsection[matchWrapper]{@matchWrapper@: a convenient interface to @match@}
550
551 Calls to @match@ often involve similar (non-trivial) work; that work
552 is collected here, in @matchWrapper@.  This function takes as
553 arguments:
554 \begin{itemize}
555 \item
556 Typchecked @Matches@ (of a function definition, or a case or lambda
557 expression)---the main input;
558 \item
559 An error message to be inserted into any (runtime) pattern-matching
560 failure messages.
561 \end{itemize}
562
563 As results, @matchWrapper@ produces:
564 \begin{itemize}
565 \item
566 A list of variables (@Locals@) that the caller must ``promise'' to
567 bind to appropriate values; and
568 \item
569 a @CoreExpr@, the desugared output (main result).
570 \end{itemize}
571
572 The main actions of @matchWrapper@ include:
573 \begin{enumerate}
574 \item
575 Flatten the @[TypecheckedMatch]@ into a suitable list of
576 @EquationInfo@s.
577 \item
578 Create as many new variables as there are patterns in a pattern-list
579 (in any one of the @EquationInfo@s).
580 \item
581 Create a suitable ``if it fails'' expression---a call to @error@ using
582 the error-string input; the {\em type} of this fail value can be found
583 by examining one of the RHS expressions in one of the @EquationInfo@s.
584 \item
585 Call @match@ with all of this information!
586 \end{enumerate}
587
588 \begin{code}
589 matchWrapper :: DsMatchKind                     -- For shadowing warning messages
590              -> [TypecheckedMatch]              -- Matches being desugared
591              -> String                          -- Error message if the match fails
592              -> DsM ([Id], CoreExpr)    -- Results
593
594 -- a special case for the common ...:
595 --      just one Match
596 --      lots of (all?) unfailable pats
597 --  e.g.,
598 --      f x y z = ....
599
600 matchWrapper kind [(PatMatch (VarPat var) match)] error_string
601   = matchWrapper kind [match] error_string `thenDs` \ (vars, core_expr) ->
602     returnDs (var:vars, core_expr)
603
604 matchWrapper kind [(PatMatch (WildPat ty) match)] error_string
605   = newSysLocalDs ty                  `thenDs` \ var ->
606     matchWrapper kind [match] error_string `thenDs` \ (vars, core_expr) ->
607     returnDs (var:vars, core_expr)
608
609 matchWrapper kind [(GRHSMatch
610                      (GRHSsAndBindsOut [OtherwiseGRHS expr _] binds _))] error_string
611   = dsBinds False binds `thenDs` \ core_binds ->
612     dsExpr  expr        `thenDs` \ core_expr ->
613     returnDs ([], mkCoLetsAny core_binds core_expr)
614
615 ----------------------------------------------------------------------------
616 -- and all the rest... (general case)
617
618 matchWrapper kind matches error_string
619   = flattenMatches kind matches `thenDs` \ eqns_info@(EqnInfo arg_pats (MatchResult _ result_ty _ _) : _) ->
620
621     selectMatchVars arg_pats                            `thenDs` \ new_vars ->
622     match new_vars eqns_info []                         `thenDs` \ match_result ->
623
624     mkErrorAppDs pAT_ERROR_ID result_ty error_string    `thenDs` \ fail_expr ->
625     extractMatchResult match_result fail_expr           `thenDs` \ result_expr ->
626
627     returnDs (new_vars, result_expr)
628 \end{code}
629
630 %************************************************************************
631 %*                                                                      *
632 \subsection[matchSimply]{@matchSimply@: match a single expression against a single pattern}
633 %*                                                                      *
634 %************************************************************************
635
636 @mkSimpleMatch@ is a wrapper for @match@ which deals with the
637 situation where we want to match a single expression against a single
638 pattern. It returns an expression.
639
640 \begin{code}
641 matchSimply :: CoreExpr                 -- Scrutinee
642             -> TypecheckedPat                   -- Pattern it should match
643             -> Type                             -- Type of result
644             -> CoreExpr                 -- Return this if it matches
645             -> CoreExpr                 -- Return this if it does
646             -> DsM CoreExpr
647
648 matchSimply (Var var) pat result_ty result_expr fail_expr
649   = match [var] [eqn_info] []   `thenDs` \ match_result ->
650     extractMatchResult match_result fail_expr
651   where
652     eqn_info = EqnInfo [pat] initial_match_result
653     initial_match_result = MatchResult CantFail
654                                        result_ty
655                                        (\ ignore -> result_expr)
656                                        NoMatchContext
657
658 matchSimply scrut_expr pat result_ty result_expr msg
659   = newSysLocalDs (outPatType pat)                              `thenDs` \ scrut_var ->
660     matchSimply (Var scrut_var) pat result_ty result_expr msg   `thenDs` \ expr ->
661     returnDs (Let (NonRec scrut_var scrut_expr) expr)
662
663
664 extractMatchResult (MatchResult CantFail _ match_fn _) fail_expr
665   = returnDs (match_fn (error "It can't fail!"))
666
667 extractMatchResult (MatchResult CanFail result_ty match_fn _) fail_expr
668   = mkFailurePair result_ty     `thenDs` \ (fail_bind_fn, if_it_fails) ->
669     returnDs (Let (fail_bind_fn fail_expr) (match_fn if_it_fails))
670 \end{code}
671
672 %************************************************************************
673 %*                                                                      *
674 %*  flattenMatches : create a list of EquationInfo                      *
675 %*                                                                      *
676 %************************************************************************
677 \subsection[flattenMatches]{@flattenMatches@: create @[EquationInfo]@}
678
679 This is actually local to @matchWrapper@.
680
681 \begin{code}
682 flattenMatches
683         :: DsMatchKind
684         -> [TypecheckedMatch]
685         -> DsM [EquationInfo]
686
687 flattenMatches kind [] = returnDs []
688
689 flattenMatches kind (match : matches)
690   = flatten_match [] match      `thenDs` \ eqn_info ->
691     flattenMatches kind matches `thenDs` \ eqn_infos ->
692     returnDs (eqn_info : eqn_infos)
693   where
694     flatten_match :: [TypecheckedPat]           -- Reversed list of patterns encountered so far
695                   -> TypecheckedMatch
696                   -> DsM EquationInfo
697
698     flatten_match pats_so_far (PatMatch pat match)
699       = flatten_match (pat:pats_so_far) match
700
701     flatten_match pats_so_far (GRHSMatch (GRHSsAndBindsOut grhss binds ty))
702       = dsBinds False binds                     `thenDs` \ core_binds ->
703         dsGRHSs ty kind pats grhss              `thenDs` \ match_result ->
704         returnDs (EqnInfo pats (mkCoLetsMatchResult core_binds match_result))
705       where
706         pats = reverse pats_so_far      -- They've accumulated in reverse order
707
708     flatten_match pats_so_far (SimpleMatch expr) 
709       = dsExpr expr             `thenDs` \ core_expr ->
710         returnDs (EqnInfo pats
711                     (MatchResult CantFail (coreExprType core_expr) 
712                               (\ ignore -> core_expr)
713                               NoMatchContext))
714         -- The NoMatchContext is just a place holder.  In a simple match,
715         -- the matching can't fail, so we won't generate an error message.
716       where
717         pats = reverse pats_so_far      -- They've accumulated in reverse order
718 \end{code}