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