Fix Trac #4371: matching of view patterns
[ghc-hetmet.git] / compiler / deSugar / Match.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 The @match@ function
7
8 \begin{code}
9 module Match ( match, matchEquations, matchWrapper, matchSimply, matchSinglePat ) where
10
11 #include "HsVersions.h"
12
13 import {-#SOURCE#-} DsExpr (dsLExpr)
14
15 import DynFlags
16 import HsSyn            
17 import TcHsSyn
18 import Check
19 import CoreSyn
20 import Literal
21 import CoreUtils
22 import MkCore
23 import DsMonad
24 import DsBinds
25 import DsGRHSs
26 import DsUtils
27 import Id
28 import DataCon
29 import MatchCon
30 import MatchLit
31 import Type
32 import TysWiredIn
33 import ListSetOps
34 import SrcLoc
35 import Maybes
36 import Util
37 import Name
38 import Outputable
39 import FastString
40
41 import qualified Data.Map as Map
42 \end{code}
43
44 This function is a wrapper of @match@, it must be called from all the parts where 
45 it was called match, but only substitutes the firs call, ....
46 if the associated flags are declared, warnings will be issued.
47 It can not be called matchWrapper because this name already exists :-(
48
49 JJCQ 30-Nov-1997
50
51 \begin{code}
52 matchCheck ::  DsMatchContext
53             -> [Id]             -- Vars rep'ing the exprs we're matching with
54             -> Type             -- Type of the case expression
55             -> [EquationInfo]   -- Info about patterns, etc. (type synonym below)
56             -> DsM MatchResult  -- Desugared result!
57
58 matchCheck ctx vars ty qs = do
59     dflags <- getDOptsDs
60     matchCheck_really dflags ctx vars ty qs
61
62 matchCheck_really :: DynFlags
63                   -> DsMatchContext
64                   -> [Id]
65                   -> Type
66                   -> [EquationInfo]
67                   -> DsM MatchResult
68 matchCheck_really dflags ctx vars ty qs
69   | incomplete && shadow  = do
70       dsShadowWarn ctx eqns_shadow
71       dsIncompleteWarn ctx pats
72       match vars ty qs
73   | incomplete            = do
74       dsIncompleteWarn ctx pats
75       match vars ty qs
76   | shadow                = do
77       dsShadowWarn ctx eqns_shadow
78       match vars ty qs
79   | otherwise             =
80       match vars ty qs
81   where (pats, eqns_shadow) = check qs
82         incomplete    = want_incomplete && (notNull pats)
83         want_incomplete = case ctx of
84                               DsMatchContext RecUpd _ ->
85                                   dopt Opt_WarnIncompletePatternsRecUpd dflags
86                               _ ->
87                                   dopt Opt_WarnIncompletePatterns       dflags
88         shadow        = dopt Opt_WarnOverlappingPatterns dflags
89                         && not (null eqns_shadow)
90 \end{code}
91
92 This variable shows the maximum number of lines of output generated for warnings.
93 It will limit the number of patterns/equations displayed to@ maximum_output@.
94
95 (ToDo: add command-line option?)
96
97 \begin{code}
98 maximum_output :: Int
99 maximum_output = 4
100 \end{code}
101
102 The next two functions create the warning message.
103
104 \begin{code}
105 dsShadowWarn :: DsMatchContext -> [EquationInfo] -> DsM ()
106 dsShadowWarn ctx@(DsMatchContext kind loc) qs
107   = putSrcSpanDs loc (warnDs warn)
108   where
109     warn | qs `lengthExceeds` maximum_output
110          = pp_context ctx (ptext (sLit "are overlapped"))
111                       (\ f -> vcat (map (ppr_eqn f kind) (take maximum_output qs)) $$
112                       ptext (sLit "..."))
113          | otherwise
114          = pp_context ctx (ptext (sLit "are overlapped"))
115                       (\ f -> vcat $ map (ppr_eqn f kind) qs)
116
117
118 dsIncompleteWarn :: DsMatchContext -> [ExhaustivePat] -> DsM ()
119 dsIncompleteWarn ctx@(DsMatchContext kind loc) pats 
120   = putSrcSpanDs loc (warnDs warn)
121         where
122           warn = pp_context ctx (ptext (sLit "are non-exhaustive"))
123                             (\_ -> hang (ptext (sLit "Patterns not matched:"))
124                                    4 ((vcat $ map (ppr_incomplete_pats kind)
125                                                   (take maximum_output pats))
126                                       $$ dots))
127
128           dots | pats `lengthExceeds` maximum_output = ptext (sLit "...")
129                | otherwise                           = empty
130
131 pp_context :: DsMatchContext -> SDoc -> ((SDoc -> SDoc) -> SDoc) -> SDoc
132 pp_context (DsMatchContext kind _loc) msg rest_of_msg_fun
133   = vcat [ptext (sLit "Pattern match(es)") <+> msg,
134           sep [ptext (sLit "In") <+> ppr_match <> char ':', nest 4 (rest_of_msg_fun pref)]]
135   where
136     (ppr_match, pref)
137         = case kind of
138              FunRhs fun _ -> (pprMatchContext kind, \ pp -> ppr fun <+> pp)
139              _            -> (pprMatchContext kind, \ pp -> pp)
140
141 ppr_pats :: Outputable a => [a] -> SDoc
142 ppr_pats pats = sep (map ppr pats)
143
144 ppr_shadow_pats :: HsMatchContext Name -> [Pat Id] -> SDoc
145 ppr_shadow_pats kind pats
146   = sep [ppr_pats pats, matchSeparator kind, ptext (sLit "...")]
147
148 ppr_incomplete_pats :: HsMatchContext Name -> ExhaustivePat -> SDoc
149 ppr_incomplete_pats _ (pats,[]) = ppr_pats pats
150 ppr_incomplete_pats _ (pats,constraints) =
151                          sep [ppr_pats pats, ptext (sLit "with"), 
152                               sep (map ppr_constraint constraints)]
153
154 ppr_constraint :: (Name,[HsLit]) -> SDoc
155 ppr_constraint (var,pats) = sep [ppr var, ptext (sLit "`notElem`"), ppr pats]
156
157 ppr_eqn :: (SDoc -> SDoc) -> HsMatchContext Name -> EquationInfo -> SDoc
158 ppr_eqn prefixF kind eqn = prefixF (ppr_shadow_pats kind (eqn_pats eqn))
159 \end{code}
160
161
162 %************************************************************************
163 %*                                                                      *
164                 The main matching function
165 %*                                                                      *
166 %************************************************************************
167
168 The function @match@ is basically the same as in the Wadler chapter,
169 except it is monadised, to carry around the name supply, info about
170 annotations, etc.
171
172 Notes on @match@'s arguments, assuming $m$ equations and $n$ patterns:
173 \begin{enumerate}
174 \item
175 A list of $n$ variable names, those variables presumably bound to the
176 $n$ expressions being matched against the $n$ patterns.  Using the
177 list of $n$ expressions as the first argument showed no benefit and
178 some inelegance.
179
180 \item
181 The second argument, a list giving the ``equation info'' for each of
182 the $m$ equations:
183 \begin{itemize}
184 \item
185 the $n$ patterns for that equation, and
186 \item
187 a list of Core bindings [@(Id, CoreExpr)@ pairs] to be ``stuck on
188 the front'' of the matching code, as in:
189 \begin{verbatim}
190 let <binds>
191 in  <matching-code>
192 \end{verbatim}
193 \item
194 and finally: (ToDo: fill in)
195
196 The right way to think about the ``after-match function'' is that it
197 is an embryonic @CoreExpr@ with a ``hole'' at the end for the
198 final ``else expression''.
199 \end{itemize}
200
201 There is a type synonym, @EquationInfo@, defined in module @DsUtils@.
202
203 An experiment with re-ordering this information about equations (in
204 particular, having the patterns available in column-major order)
205 showed no benefit.
206
207 \item
208 A default expression---what to evaluate if the overall pattern-match
209 fails.  This expression will (almost?) always be
210 a measly expression @Var@, unless we know it will only be used once
211 (as we do in @glue_success_exprs@).
212
213 Leaving out this third argument to @match@ (and slamming in lots of
214 @Var "fail"@s) is a positively {\em bad} idea, because it makes it
215 impossible to share the default expressions.  (Also, it stands no
216 chance of working in our post-upheaval world of @Locals@.)
217 \end{enumerate}
218
219 Note: @match@ is often called via @matchWrapper@ (end of this module),
220 a function that does much of the house-keeping that goes with a call
221 to @match@.
222
223 It is also worth mentioning the {\em typical} way a block of equations
224 is desugared with @match@.  At each stage, it is the first column of
225 patterns that is examined.  The steps carried out are roughly:
226 \begin{enumerate}
227 \item
228 Tidy the patterns in column~1 with @tidyEqnInfo@ (this may add
229 bindings to the second component of the equation-info):
230 \begin{itemize}
231 \item
232 Remove the `as' patterns from column~1.
233 \item
234 Make all constructor patterns in column~1 into @ConPats@, notably
235 @ListPats@ and @TuplePats@.
236 \item
237 Handle any irrefutable (or ``twiddle'') @LazyPats@.
238 \end{itemize}
239 \item
240 Now {\em unmix} the equations into {\em blocks} [w\/ local function
241 @unmix_eqns@], in which the equations in a block all have variable
242 patterns in column~1, or they all have constructor patterns in ...
243 (see ``the mixture rule'' in SLPJ).
244 \item
245 Call @matchEqnBlock@ on each block of equations; it will do the
246 appropriate thing for each kind of column-1 pattern, usually ending up
247 in a recursive call to @match@.
248 \end{enumerate}
249
250 We are a little more paranoid about the ``empty rule'' (SLPJ, p.~87)
251 than the Wadler-chapter code for @match@ (p.~93, first @match@ clause).
252 And gluing the ``success expressions'' together isn't quite so pretty.
253
254 This (more interesting) clause of @match@ uses @tidy_and_unmix_eqns@
255 (a)~to get `as'- and `twiddle'-patterns out of the way (tidying), and
256 (b)~to do ``the mixture rule'' (SLPJ, p.~88) [which really {\em
257 un}mixes the equations], producing a list of equation-info
258 blocks, each block having as its first column of patterns either all
259 constructors, or all variables (or similar beasts), etc.
260
261 @match_unmixed_eqn_blks@ simply takes the place of the @foldr@ in the
262 Wadler-chapter @match@ (p.~93, last clause), and @match_unmixed_blk@
263 corresponds roughly to @matchVarCon@.
264
265 \begin{code}
266 match :: [Id]             -- Variables rep\'ing the exprs we\'re matching with
267       -> Type             -- Type of the case expression
268       -> [EquationInfo]   -- Info about patterns, etc. (type synonym below)
269       -> DsM MatchResult  -- Desugared result!
270
271 match [] ty eqns
272   = ASSERT2( not (null eqns), ppr ty )
273     return (foldr1 combineMatchResults match_results)
274   where
275     match_results = [ ASSERT( null (eqn_pats eqn) ) 
276                       eqn_rhs eqn
277                     | eqn <- eqns ]
278
279 match vars@(v:_) ty eqns
280   = ASSERT( not (null eqns ) )
281     do  {       -- Tidy the first pattern, generating
282                 -- auxiliary bindings if necessary
283           (aux_binds, tidy_eqns) <- mapAndUnzipM (tidyEqnInfo v) eqns
284
285                 -- Group the equations and match each group in turn
286        ; let grouped = groupEquations tidy_eqns
287
288          -- print the view patterns that are commoned up to help debug
289        ; ifDOptM Opt_D_dump_view_pattern_commoning (debug grouped)
290
291         ; match_results <- mapM match_group grouped
292         ; return (adjustMatchResult (foldr1 (.) aux_binds) $
293                   foldr1 combineMatchResults match_results) }
294   where
295     dropGroup :: [(PatGroup,EquationInfo)] -> [EquationInfo]
296     dropGroup = map snd
297
298     match_group :: [(PatGroup,EquationInfo)] -> DsM MatchResult
299     match_group [] = panic "match_group"
300     match_group eqns@((group,_) : _)
301         = case group of
302             PgCon _    -> matchConFamily  vars ty (subGroup [(c,e) | (PgCon c, e) <- eqns])
303             PgLit _    -> matchLiterals   vars ty (subGroup [(l,e) | (PgLit l, e) <- eqns])
304             PgAny      -> matchVariables  vars ty (dropGroup eqns)
305             PgN _      -> matchNPats      vars ty (dropGroup eqns)
306             PgNpK _    -> matchNPlusKPats vars ty (dropGroup eqns)
307             PgBang     -> matchBangs      vars ty (dropGroup eqns)
308             PgCo _     -> matchCoercion   vars ty (dropGroup eqns)
309             PgView _ _ -> matchView       vars ty (dropGroup eqns)
310
311     -- FIXME: we should also warn about view patterns that should be
312     -- commoned up but are not
313
314     -- print some stuff to see what's getting grouped
315     -- use -dppr-debug to see the resolution of overloaded lits
316     debug eqns = 
317         let gs = map (\group -> foldr (\ (p,_) -> \acc -> 
318                                            case p of PgView e _ -> e:acc 
319                                                      _ -> acc) [] group) eqns
320             maybeWarn [] = return ()
321             maybeWarn l = warnDs (vcat l)
322         in 
323           maybeWarn $ (map (\g -> text "Putting these view expressions into the same case:" <+> (ppr g))
324                        (filter (not . null) gs))
325
326 matchVariables :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
327 -- Real true variables, just like in matchVar, SLPJ p 94
328 -- No binding to do: they'll all be wildcards by now (done in tidy)
329 matchVariables (_:vars) ty eqns = match vars ty (shiftEqns eqns)
330 matchVariables [] _ _ = panic "matchVariables"
331
332 matchBangs :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
333 matchBangs (var:vars) ty eqns
334   = do  { match_result <- match (var:vars) ty (map decomposeFirst_Bang eqns)
335         ; return (mkEvalMatchResult var ty match_result) }
336 matchBangs [] _ _ = panic "matchBangs"
337
338 matchCoercion :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
339 -- Apply the coercion to the match variable and then match that
340 matchCoercion (var:vars) ty (eqns@(eqn1:_))
341   = do  { let CoPat co pat _ = firstPat eqn1
342         ; var' <- newUniqueId var (hsPatType pat)
343         ; match_result <- match (var':vars) ty (map decomposeFirst_Coercion eqns)
344         ; co' <- dsHsWrapper co
345         ; let rhs' = co' (Var var)
346         ; return (mkCoLetMatchResult (NonRec var' rhs') match_result) }
347 matchCoercion _ _ _ = panic "matchCoercion"
348
349 matchView :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
350 -- Apply the view function to the match variable and then match that
351 matchView (var:vars) ty (eqns@(eqn1:_))
352   = do  { -- we could pass in the expr from the PgView,
353          -- but this needs to extract the pat anyway 
354          -- to figure out the type of the fresh variable
355          let ViewPat viewExpr (L _ pat) _ = firstPat eqn1
356          -- do the rest of the compilation 
357         ; var' <- newUniqueId var (hsPatType pat)
358         ; match_result <- match (var':vars) ty (map decomposeFirst_View eqns)
359          -- compile the view expressions
360         ; viewExpr' <- dsLExpr viewExpr
361         ; return (mkViewMatchResult var' viewExpr' var match_result) }
362 matchView _ _ _ = panic "matchView"
363
364 -- decompose the first pattern and leave the rest alone
365 decomposeFirstPat :: (Pat Id -> Pat Id) -> EquationInfo -> EquationInfo
366 decomposeFirstPat extractpat (eqn@(EqnInfo { eqn_pats = pat : pats }))
367         = eqn { eqn_pats = extractpat pat : pats}
368 decomposeFirstPat _ _ = panic "decomposeFirstPat"
369
370 decomposeFirst_Coercion, decomposeFirst_Bang, decomposeFirst_View :: EquationInfo -> EquationInfo
371
372 decomposeFirst_Coercion = decomposeFirstPat (\ (CoPat _ pat _) -> pat)
373 decomposeFirst_Bang     = decomposeFirstPat (\ (BangPat pat  ) -> unLoc pat)
374 decomposeFirst_View     = decomposeFirstPat (\ (ViewPat _ pat _) -> unLoc pat)
375
376 \end{code}
377
378 %************************************************************************
379 %*                                                                      *
380                 Tidying patterns
381 %*                                                                      *
382 %************************************************************************
383
384 Tidy up the leftmost pattern in an @EquationInfo@, given the variable @v@
385 which will be scrutinised.  This means:
386 \begin{itemize}
387 \item
388 Replace variable patterns @x@ (@x /= v@) with the pattern @_@,
389 together with the binding @x = v@.
390 \item
391 Replace the `as' pattern @x@@p@ with the pattern p and a binding @x = v@.
392 \item
393 Removing lazy (irrefutable) patterns (you don't want to know...).
394 \item
395 Converting explicit tuple-, list-, and parallel-array-pats into ordinary
396 @ConPats@. 
397 \item
398 Convert the literal pat "" to [].
399 \end{itemize}
400
401 The result of this tidying is that the column of patterns will include
402 {\em only}:
403 \begin{description}
404 \item[@WildPats@:]
405 The @VarPat@ information isn't needed any more after this.
406
407 \item[@ConPats@:]
408 @ListPats@, @TuplePats@, etc., are all converted into @ConPats@.
409
410 \item[@LitPats@ and @NPats@:]
411 @LitPats@/@NPats@ of ``known friendly types'' (Int, Char,
412 Float,  Double, at least) are converted to unboxed form; e.g.,
413 \tr{(NPat (HsInt i) _ _)} is converted to:
414 \begin{verbatim}
415 (ConPat I# _ _ [LitPat (HsIntPrim i)])
416 \end{verbatim}
417 \end{description}
418
419 \begin{code}
420 tidyEqnInfo :: Id -> EquationInfo
421             -> DsM (DsWrapper, EquationInfo)
422         -- DsM'd because of internal call to dsLHsBinds
423         --      and mkSelectorBinds.
424         -- "tidy1" does the interesting stuff, looking at
425         -- one pattern and fiddling the list of bindings.
426         --
427         -- POST CONDITION: head pattern in the EqnInfo is
428         --      WildPat
429         --      ConPat
430         --      NPat
431         --      LitPat
432         --      NPlusKPat
433         -- but no other
434
435 tidyEqnInfo _ (EqnInfo { eqn_pats = [] }) 
436   = panic "tidyEqnInfo"
437
438 tidyEqnInfo v eqn@(EqnInfo { eqn_pats = pat : pats })
439   = do { (wrap, pat') <- tidy1 v pat
440        ; return (wrap, eqn { eqn_pats = do pat' : pats }) }
441
442 tidy1 :: Id                     -- The Id being scrutinised
443       -> Pat Id                 -- The pattern against which it is to be matched
444       -> DsM (DsWrapper,        -- Extra bindings to do before the match
445               Pat Id)           -- Equivalent pattern
446
447 -------------------------------------------------------
448 --      (pat', mr') = tidy1 v pat mr
449 -- tidies the *outer level only* of pat, giving pat'
450 -- It eliminates many pattern forms (as-patterns, variable patterns,
451 -- list patterns, etc) yielding one of:
452 --      WildPat
453 --      ConPatOut
454 --      LitPat
455 --      NPat
456 --      NPlusKPat
457
458 tidy1 v (ParPat pat)      = tidy1 v (unLoc pat) 
459 tidy1 v (SigPatOut pat _) = tidy1 v (unLoc pat) 
460 tidy1 _ (WildPat ty)      = return (idDsWrapper, WildPat ty)
461
462         -- case v of { x -> mr[] }
463         -- = case v of { _ -> let x=v in mr[] }
464 tidy1 v (VarPat var)
465   = return (wrapBind var v, WildPat (idType var)) 
466
467 tidy1 v (VarPatOut var binds)
468   = do  { ds_ev_binds <- dsTcEvBinds binds
469         ; return (wrapBind var v . wrapDsEvBinds ds_ev_binds,
470                   WildPat (idType var)) }
471
472         -- case v of { x@p -> mr[] }
473         -- = case v of { p -> let x=v in mr[] }
474 tidy1 v (AsPat (L _ var) pat)
475   = do  { (wrap, pat') <- tidy1 v (unLoc pat)
476         ; return (wrapBind var v . wrap, pat') }
477
478 {- now, here we handle lazy patterns:
479     tidy1 v ~p bs = (v, v1 = case v of p -> v1 :
480                         v2 = case v of p -> v2 : ... : bs )
481
482     where the v_i's are the binders in the pattern.
483
484     ToDo: in "v_i = ... -> v_i", are the v_i's really the same thing?
485
486     The case expr for v_i is just: match [v] [(p, [], \ x -> Var v_i)] any_expr
487 -}
488
489 tidy1 v (LazyPat pat)
490   = do  { sel_prs <- mkSelectorBinds pat (Var v)
491         ; let sel_binds =  [NonRec b rhs | (b,rhs) <- sel_prs]
492         ; return (mkCoreLets sel_binds, WildPat (idType v)) }
493
494 tidy1 _ (ListPat pats ty)
495   = return (idDsWrapper, unLoc list_ConPat)
496   where
497     list_ty     = mkListTy ty
498     list_ConPat = foldr (\ x y -> mkPrefixConPat consDataCon [x, y] list_ty)
499                         (mkNilPat list_ty)
500                         pats
501
502 -- Introduce fake parallel array constructors to be able to handle parallel
503 -- arrays with the existing machinery for constructor pattern
504 tidy1 _ (PArrPat pats ty)
505   = return (idDsWrapper, unLoc parrConPat)
506   where
507     arity      = length pats
508     parrConPat = mkPrefixConPat (parrFakeCon arity) pats (mkPArrTy ty)
509
510 tidy1 _ (TuplePat pats boxity ty)
511   = return (idDsWrapper, unLoc tuple_ConPat)
512   where
513     arity = length pats
514     tuple_ConPat = mkPrefixConPat (tupleCon boxity arity) pats ty
515
516 -- LitPats: we *might* be able to replace these w/ a simpler form
517 tidy1 _ (LitPat lit)
518   = return (idDsWrapper, tidyLitPat lit)
519
520 -- NPats: we *might* be able to replace these w/ a simpler form
521 tidy1 _ (NPat lit mb_neg eq)
522   = return (idDsWrapper, tidyNPat lit mb_neg eq)
523
524 -- BangPatterns: Pattern matching is already strict in constructors,
525 -- tuples etc, so the last case strips off the bang for thoses patterns.
526 tidy1 v (BangPat (L _ (LazyPat p)))       = tidy1 v (BangPat p)
527 tidy1 v (BangPat (L _ (ParPat p)))        = tidy1 v (BangPat p)
528 tidy1 _ p@(BangPat (L _(VarPat _)))       = return (idDsWrapper, p)
529 tidy1 _ p@(BangPat (L _(VarPatOut _ _)))  = return (idDsWrapper, p)
530 tidy1 _ p@(BangPat (L _ (WildPat _)))     = return (idDsWrapper, p)
531 tidy1 _ p@(BangPat (L _ (CoPat _ _ _)))   = return (idDsWrapper, p)
532 tidy1 _ p@(BangPat (L _ (SigPatIn _ _)))  = return (idDsWrapper, p)
533 tidy1 _ p@(BangPat (L _ (SigPatOut _ _))) = return (idDsWrapper, p)
534 tidy1 v (BangPat (L _ (AsPat (L _ var) pat)))
535   = do  { (wrap, pat') <- tidy1 v (BangPat pat)
536         ; return (wrapBind var v . wrap, pat') }
537 tidy1 v (BangPat (L _ p))                   = tidy1 v p
538
539 -- Everything else goes through unchanged...
540
541 tidy1 _ non_interesting_pat
542   = return (idDsWrapper, non_interesting_pat)
543 \end{code}
544
545 \noindent
546 {\bf Previous @matchTwiddled@ stuff:}
547
548 Now we get to the only interesting part; note: there are choices for
549 translation [from Simon's notes]; translation~1:
550 \begin{verbatim}
551 deTwiddle [s,t] e
552 \end{verbatim}
553 returns
554 \begin{verbatim}
555 [ w = e,
556   s = case w of [s,t] -> s
557   t = case w of [s,t] -> t
558 ]
559 \end{verbatim}
560
561 Here \tr{w} is a fresh variable, and the \tr{w}-binding prevents multiple
562 evaluation of \tr{e}.  An alternative translation (No.~2):
563 \begin{verbatim}
564 [ w = case e of [s,t] -> (s,t)
565   s = case w of (s,t) -> s
566   t = case w of (s,t) -> t
567 ]
568 \end{verbatim}
569
570 %************************************************************************
571 %*                                                                      *
572 \subsubsection[improved-unmixing]{UNIMPLEMENTED idea for improved unmixing}
573 %*                                                                      *
574 %************************************************************************
575
576 We might be able to optimise unmixing when confronted by
577 only-one-constructor-possible, of which tuples are the most notable
578 examples.  Consider:
579 \begin{verbatim}
580 f (a,b,c) ... = ...
581 f d ... (e:f) = ...
582 f (g,h,i) ... = ...
583 f j ...       = ...
584 \end{verbatim}
585 This definition would normally be unmixed into four equation blocks,
586 one per equation.  But it could be unmixed into just one equation
587 block, because if the one equation matches (on the first column),
588 the others certainly will.
589
590 You have to be careful, though; the example
591 \begin{verbatim}
592 f j ...       = ...
593 -------------------
594 f (a,b,c) ... = ...
595 f d ... (e:f) = ...
596 f (g,h,i) ... = ...
597 \end{verbatim}
598 {\em must} be broken into two blocks at the line shown; otherwise, you
599 are forcing unnecessary evaluation.  In any case, the top-left pattern
600 always gives the cue.  You could then unmix blocks into groups of...
601 \begin{description}
602 \item[all variables:]
603 As it is now.
604 \item[constructors or variables (mixed):]
605 Need to make sure the right names get bound for the variable patterns.
606 \item[literals or variables (mixed):]
607 Presumably just a variant on the constructor case (as it is now).
608 \end{description}
609
610 %************************************************************************
611 %*                                                                      *
612 %*  matchWrapper: a convenient way to call @match@                      *
613 %*                                                                      *
614 %************************************************************************
615 \subsection[matchWrapper]{@matchWrapper@: a convenient interface to @match@}
616
617 Calls to @match@ often involve similar (non-trivial) work; that work
618 is collected here, in @matchWrapper@.  This function takes as
619 arguments:
620 \begin{itemize}
621 \item
622 Typchecked @Matches@ (of a function definition, or a case or lambda
623 expression)---the main input;
624 \item
625 An error message to be inserted into any (runtime) pattern-matching
626 failure messages.
627 \end{itemize}
628
629 As results, @matchWrapper@ produces:
630 \begin{itemize}
631 \item
632 A list of variables (@Locals@) that the caller must ``promise'' to
633 bind to appropriate values; and
634 \item
635 a @CoreExpr@, the desugared output (main result).
636 \end{itemize}
637
638 The main actions of @matchWrapper@ include:
639 \begin{enumerate}
640 \item
641 Flatten the @[TypecheckedMatch]@ into a suitable list of
642 @EquationInfo@s.
643 \item
644 Create as many new variables as there are patterns in a pattern-list
645 (in any one of the @EquationInfo@s).
646 \item
647 Create a suitable ``if it fails'' expression---a call to @error@ using
648 the error-string input; the {\em type} of this fail value can be found
649 by examining one of the RHS expressions in one of the @EquationInfo@s.
650 \item
651 Call @match@ with all of this information!
652 \end{enumerate}
653
654 \begin{code}
655 matchWrapper :: HsMatchContext Name     -- For shadowing warning messages
656              -> MatchGroup Id           -- Matches being desugared
657              -> DsM ([Id], CoreExpr)    -- Results
658 \end{code}
659
660  There is one small problem with the Lambda Patterns, when somebody
661  writes something similar to:
662 \begin{verbatim}
663     (\ (x:xs) -> ...)
664 \end{verbatim}
665  he/she don't want a warning about incomplete patterns, that is done with 
666  the flag @opt_WarnSimplePatterns@.
667  This problem also appears in the:
668 \begin{itemize}
669 \item @do@ patterns, but if the @do@ can fail
670       it creates another equation if the match can fail
671       (see @DsExpr.doDo@ function)
672 \item @let@ patterns, are treated by @matchSimply@
673    List Comprension Patterns, are treated by @matchSimply@ also
674 \end{itemize}
675
676 We can't call @matchSimply@ with Lambda patterns,
677 due to the fact that lambda patterns can have more than
678 one pattern, and match simply only accepts one pattern.
679
680 JJQC 30-Nov-1997
681
682 \begin{code}
683 matchWrapper ctxt (MatchGroup matches match_ty)
684   = ASSERT( notNull matches )
685     do  { eqns_info   <- mapM mk_eqn_info matches
686         ; new_vars    <- selectMatchVars arg_pats
687         ; result_expr <- matchEquations ctxt new_vars eqns_info rhs_ty
688         ; return (new_vars, result_expr) }
689   where
690     arg_pats    = map unLoc (hsLMatchPats (head matches))
691     n_pats      = length arg_pats
692     (_, rhs_ty) = splitFunTysN n_pats match_ty
693
694     mk_eqn_info (L _ (Match pats _ grhss))
695       = do { let upats = map unLoc pats
696            ; match_result <- dsGRHSs ctxt upats grhss rhs_ty
697            ; return (EqnInfo { eqn_pats = upats, eqn_rhs  = match_result}) }
698
699
700 matchEquations  :: HsMatchContext Name
701                 -> [Id] -> [EquationInfo] -> Type
702                 -> DsM CoreExpr
703 matchEquations ctxt vars eqns_info rhs_ty
704   = do  { locn <- getSrcSpanDs
705         ; let   ds_ctxt   = DsMatchContext ctxt locn
706                 error_doc = matchContextErrString ctxt
707
708         ; match_result <- matchCheck ds_ctxt vars rhs_ty eqns_info
709
710         ; fail_expr <- mkErrorAppDs pAT_ERROR_ID rhs_ty error_doc
711         ; extractMatchResult match_result fail_expr }
712 \end{code}
713
714 %************************************************************************
715 %*                                                                      *
716 \subsection[matchSimply]{@matchSimply@: match a single expression against a single pattern}
717 %*                                                                      *
718 %************************************************************************
719
720 @mkSimpleMatch@ is a wrapper for @match@ which deals with the
721 situation where we want to match a single expression against a single
722 pattern. It returns an expression.
723
724 \begin{code}
725 matchSimply :: CoreExpr                 -- Scrutinee
726             -> HsMatchContext Name      -- Match kind
727             -> LPat Id                  -- Pattern it should match
728             -> CoreExpr                 -- Return this if it matches
729             -> CoreExpr                 -- Return this if it doesn't
730             -> DsM CoreExpr
731 -- Do not warn about incomplete patterns; see matchSinglePat comments
732 matchSimply scrut hs_ctx pat result_expr fail_expr = do
733     let
734       match_result = cantFailMatchResult result_expr
735       rhs_ty       = exprType fail_expr
736         -- Use exprType of fail_expr, because won't refine in the case of failure!
737     match_result' <- matchSinglePat scrut hs_ctx pat rhs_ty match_result
738     extractMatchResult match_result' fail_expr
739
740
741 matchSinglePat :: CoreExpr -> HsMatchContext Name -> LPat Id
742                -> Type -> MatchResult -> DsM MatchResult
743 -- Do not warn about incomplete patterns
744 -- Used for things like [ e | pat <- stuff ], where 
745 -- incomplete patterns are just fine
746 matchSinglePat (Var var) _ (L _ pat) ty match_result 
747   = match [var] ty [EqnInfo { eqn_pats = [pat], eqn_rhs  = match_result }]
748
749 matchSinglePat scrut hs_ctx pat ty match_result = do
750     var <- selectSimpleMatchVarL pat
751     match_result' <- matchSinglePat (Var var) hs_ctx pat ty match_result
752     return (adjustMatchResult (bindNonRec var scrut) match_result')
753 \end{code}
754
755
756 %************************************************************************
757 %*                                                                      *
758                 Pattern classification
759 %*                                                                      *
760 %************************************************************************
761
762 \begin{code}
763 data PatGroup
764   = PgAny               -- Immediate match: variables, wildcards, 
765                         --                  lazy patterns
766   | PgCon DataCon       -- Constructor patterns (incl list, tuple)
767   | PgLit Literal       -- Literal patterns
768   | PgN   Literal       -- Overloaded literals
769   | PgNpK Literal       -- n+k patterns
770   | PgBang              -- Bang patterns
771   | PgCo Type           -- Coercion patterns; the type is the type
772                         --      of the pattern *inside*
773   | PgView (LHsExpr Id) -- view pattern (e -> p):
774                         -- the LHsExpr is the expression e
775            Type         -- the Type is the type of p (equivalently, the result type of e)
776
777 groupEquations :: [EquationInfo] -> [[(PatGroup, EquationInfo)]]
778 -- If the result is of form [g1, g2, g3], 
779 -- (a) all the (pg,eq) pairs in g1 have the same pg
780 -- (b) none of the gi are empty
781 -- The ordering of equations is unchanged
782 groupEquations eqns
783   = runs same_gp [(patGroup (firstPat eqn), eqn) | eqn <- eqns]
784   where
785     same_gp :: (PatGroup,EquationInfo) -> (PatGroup,EquationInfo) -> Bool
786     (pg1,_) `same_gp` (pg2,_) = pg1 `sameGroup` pg2
787
788 subGroup :: Ord a => [(a, EquationInfo)] -> [[EquationInfo]]
789 -- Input is a particular group.  The result sub-groups the 
790 -- equations by with particular constructor, literal etc they match.
791 -- Each sub-list in the result has the same PatGroup
792 -- See Note [Take care with pattern order]
793 subGroup group 
794     = map reverse $ Map.elems $ foldl accumulate Map.empty group
795   where
796     accumulate pg_map (pg, eqn)
797       = case Map.lookup pg pg_map of
798           Just eqns -> Map.insert pg (eqn:eqns) pg_map
799           Nothing   -> Map.insert pg [eqn]      pg_map
800
801     -- pg_map :: Map a [EquationInfo]
802     -- Equations seen so far in reverse order of appearance
803 \end{code}
804
805 Note [Take care with pattern order]
806 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
807 In the subGroup function we must be very careful about pattern re-ordering,
808 Consider the patterns [ (True, Nothing), (False, x), (True, y) ]
809 Then in bringing together the patterns for True, we must not 
810 swap the Nothing and y!
811
812
813 \begin{code}
814 sameGroup :: PatGroup -> PatGroup -> Bool
815 -- Same group means that a single case expression 
816 -- or test will suffice to match both, *and* the order
817 -- of testing within the group is insignificant.
818 sameGroup PgAny      PgAny      = True
819 sameGroup PgBang     PgBang     = True
820 sameGroup (PgCon _)  (PgCon _)  = True          -- One case expression
821 sameGroup (PgLit _)  (PgLit _)  = True          -- One case expression
822 sameGroup (PgN l1)   (PgN l2)   = l1==l2        -- Order is significant
823 sameGroup (PgNpK l1) (PgNpK l2) = l1==l2        -- See Note [Grouping overloaded literal patterns]
824 sameGroup (PgCo t1)  (PgCo t2)  = t1 `coreEqType` t2
825         -- CoPats are in the same goup only if the type of the
826         -- enclosed pattern is the same. The patterns outside the CoPat
827         -- always have the same type, so this boils down to saying that
828         -- the two coercions are identical.
829 sameGroup (PgView e1 t1) (PgView e2 t2) = viewLExprEq (e1,t1) (e2,t2) 
830        -- ViewPats are in the same gorup iff the expressions
831        -- are "equal"---conservatively, we use syntactic equality
832 sameGroup _          _          = False
833
834 -- An approximation of syntactic equality used for determining when view
835 -- exprs are in the same group.
836 -- This function can always safely return false;
837 -- but doing so will result in the application of the view function being repeated.
838 --
839 -- Currently: compare applications of literals and variables
840 --            and anything else that we can do without involving other
841 --            HsSyn types in the recursion
842 --
843 -- NB we can't assume that the two view expressions have the same type.  Consider
844 --   f (e1 -> True) = ...
845 --   f (e2 -> "hi") = ...
846 viewLExprEq :: (LHsExpr Id,Type) -> (LHsExpr Id,Type) -> Bool
847 viewLExprEq (e1,_) (e2,_) = lexp e1 e2
848   where
849     lexp :: LHsExpr Id -> LHsExpr Id -> Bool
850     lexp e e' = exp (unLoc e) (unLoc e')
851
852     ---------
853     exp :: HsExpr Id -> HsExpr Id -> Bool
854     -- real comparison is on HsExpr's
855     -- strip parens 
856     exp (HsPar (L _ e)) e'   = exp e e'
857     exp e (HsPar (L _ e'))   = exp e e'
858     -- because the expressions do not necessarily have the same type,
859     -- we have to compare the wrappers
860     exp (HsWrap h e) (HsWrap h' e') = wrap h h' && exp e e'
861     exp (HsVar i) (HsVar i') =  i == i' 
862     -- the instance for IPName derives using the id, so this works if the
863     -- above does
864     exp (HsIPVar i) (HsIPVar i') = i == i' 
865     exp (HsOverLit l) (HsOverLit l') = 
866         -- Overloaded lits are equal if they have the same type
867         -- and the data is the same.
868         -- this is coarser than comparing the SyntaxExpr's in l and l',
869         -- which resolve the overloading (e.g., fromInteger 1),
870         -- because these expressions get written as a bunch of different variables
871         -- (presumably to improve sharing)
872         tcEqType (overLitType l) (overLitType l') && l == l'
873     exp (HsApp e1 e2) (HsApp e1' e2') = lexp e1 e1' && lexp e2 e2'
874     -- the fixities have been straightened out by now, so it's safe
875     -- to ignore them?
876     exp (OpApp l o _ ri) (OpApp l' o' _ ri') = 
877         lexp l l' && lexp o o' && lexp ri ri'
878     exp (NegApp e n) (NegApp e' n') = lexp e e' && exp n n'
879     exp (SectionL e1 e2) (SectionL e1' e2') = 
880         lexp e1 e1' && lexp e2 e2'
881     exp (SectionR e1 e2) (SectionR e1' e2') = 
882         lexp e1 e1' && lexp e2 e2'
883     exp (ExplicitTuple es1 _) (ExplicitTuple es2 _) =
884         eq_list tup_arg es1 es2
885     exp (HsIf e e1 e2) (HsIf e' e1' e2') =
886         lexp e e' && lexp e1 e1' && lexp e2 e2'
887
888     -- Enhancement: could implement equality for more expressions
889     --   if it seems useful
890     -- But no need for HsLit, ExplicitList, ExplicitTuple, 
891     -- because they cannot be functions
892     exp _ _  = False
893
894     ---------
895     tup_arg (Present e1) (Present e2) = lexp e1 e2
896     tup_arg (Missing t1) (Missing t2) = tcEqType t1 t2
897     tup_arg _ _ = False
898
899     ---------
900     wrap :: HsWrapper -> HsWrapper -> Bool
901     -- Conservative, in that it demands that wrappers be
902     -- syntactically identical and doesn't look under binders
903     --
904     -- Coarser notions of equality are possible
905     -- (e.g., reassociating compositions,
906     --        equating different ways of writing a coercion)
907     wrap WpHole WpHole = True
908     wrap (WpCompose w1 w2) (WpCompose w1' w2') = wrap w1 w1' && wrap w2 w2'
909     wrap (WpCast c)  (WpCast c')     = tcEqType c c'
910     wrap (WpEvApp et1) (WpEvApp et2) = ev_term et1 et2
911     wrap (WpTyApp t) (WpTyApp t')    = tcEqType t t'
912     -- Enhancement: could implement equality for more wrappers
913     --   if it seems useful (lams and lets)
914     wrap _ _ = False
915
916     ---------
917     ev_term :: EvTerm -> EvTerm -> Bool
918     ev_term (EvId a)       (EvId b)       = a==b
919     ev_term (EvCoercion a) (EvCoercion b) = tcEqType a b
920     ev_term _ _ = False 
921
922     ---------
923     eq_list :: (a->a->Bool) -> [a] -> [a] -> Bool
924     eq_list _  []     []     = True
925     eq_list _  []     (_:_)  = False
926     eq_list _  (_:_)  []     = False
927     eq_list eq (x:xs) (y:ys) = eq x y && eq_list eq xs ys
928
929 patGroup :: Pat Id -> PatGroup
930 patGroup (WildPat {})                 = PgAny
931 patGroup (BangPat {})                 = PgBang  
932 patGroup (ConPatOut { pat_con = dc }) = PgCon (unLoc dc)
933 patGroup (LitPat lit)                 = PgLit (hsLitKey lit)
934 patGroup (NPat olit mb_neg _)         = PgN   (hsOverLitKey olit (isJust mb_neg))
935 patGroup (NPlusKPat _ olit _ _)       = PgNpK (hsOverLitKey olit False)
936 patGroup (CoPat _ p _)                = PgCo  (hsPatType p)     -- Type of innelexp pattern
937 patGroup (ViewPat expr p _)               = PgView expr (hsPatType (unLoc p))
938 patGroup pat = pprPanic "patGroup" (ppr pat)
939 \end{code}
940
941 Note [Grouping overloaded literal patterns]
942 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
943 WATCH OUT!  Consider
944
945         f (n+1) = ...
946         f (n+2) = ...
947         f (n+1) = ...
948
949 We can't group the first and third together, because the second may match 
950 the same thing as the first.  Same goes for *overloaded* literal patterns
951         f 1 True = ...
952         f 2 False = ...
953         f 1 False = ...
954 If the first arg matches '1' but the second does not match 'True', we
955 cannot jump to the third equation!  Because the same argument might
956 match '2'!
957 Hence we don't regard 1 and 2, or (n+1) and (n+2), as part of the same group.