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