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