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