Do not use defaulting in ambiguity check
[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, dsSyntaxExpr)
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( when, 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 NoReason (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'
273 (mkCoreAppDs (text "matchView") viewExpr' (Var var))
274 match_result) }
275 matchView _ _ _ = panic "matchView"
276
277 matchOverloadedList :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
278 matchOverloadedList (var:vars) ty (eqns@(eqn1:_))
279 -- Since overloaded list patterns are treated as view patterns,
280 -- the code is roughly the same as for matchView
281 = do { let ListPat _ elt_ty (Just (_,e)) = firstPat eqn1
282 ; var' <- newUniqueId var (mkListTy elt_ty) -- we construct the overall type by hand
283 ; match_result <- match (var':vars) ty $
284 map (decomposeFirstPat getOLPat) eqns -- getOLPat builds the pattern inside as a non-overloaded version of the overloaded list pattern
285 ; e' <- dsSyntaxExpr e [Var var]
286 ; return (mkViewMatchResult var' e' match_result) }
287 matchOverloadedList _ _ _ = panic "matchOverloadedList"
288
289 -- decompose the first pattern and leave the rest alone
290 decomposeFirstPat :: (Pat Id -> Pat Id) -> EquationInfo -> EquationInfo
291 decomposeFirstPat extractpat (eqn@(EqnInfo { eqn_pats = pat : pats }))
292 = eqn { eqn_pats = extractpat pat : pats}
293 decomposeFirstPat _ _ = panic "decomposeFirstPat"
294
295 getCoPat, getBangPat, getViewPat, getOLPat :: Pat Id -> Pat Id
296 getCoPat (CoPat _ pat _) = pat
297 getCoPat _ = panic "getCoPat"
298 getBangPat (BangPat pat ) = unLoc pat
299 getBangPat _ = panic "getBangPat"
300 getViewPat (ViewPat _ pat _) = unLoc pat
301 getViewPat _ = panic "getViewPat"
302 getOLPat (ListPat pats ty (Just _)) = ListPat pats ty Nothing
303 getOLPat _ = panic "getOLPat"
304
305 {-
306 Note [Empty case alternatives]
307 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
308 The list of EquationInfo can be empty, arising from
309 case x of {} or \case {}
310 In that situation we desugar to
311 case x of { _ -> error "pattern match failure" }
312 The *desugarer* isn't certain whether there really should be no
313 alternatives, so it adds a default case, as it always does. A later
314 pass may remove it if it's inaccessible. (See also Note [Empty case
315 alternatives] in CoreSyn.)
316
317 We do *not* desugar simply to
318 error "empty case"
319 or some such, because 'x' might be bound to (error "hello"), in which
320 case we want to see that "hello" exception, not (error "empty case").
321 See also Note [Case elimination: lifted case] in Simplify.
322
323
324 ************************************************************************
325 * *
326 Tidying patterns
327 * *
328 ************************************************************************
329
330 Tidy up the leftmost pattern in an @EquationInfo@, given the variable @v@
331 which will be scrutinised. This means:
332 \begin{itemize}
333 \item
334 Replace variable patterns @x@ (@x /= v@) with the pattern @_@,
335 together with the binding @x = v@.
336 \item
337 Replace the `as' pattern @x@@p@ with the pattern p and a binding @x = v@.
338 \item
339 Removing lazy (irrefutable) patterns (you don't want to know...).
340 \item
341 Converting explicit tuple-, list-, and parallel-array-pats into ordinary
342 @ConPats@.
343 \item
344 Convert the literal pat "" to [].
345 \end{itemize}
346
347 The result of this tidying is that the column of patterns will include
348 {\em only}:
349 \begin{description}
350 \item[@WildPats@:]
351 The @VarPat@ information isn't needed any more after this.
352
353 \item[@ConPats@:]
354 @ListPats@, @TuplePats@, etc., are all converted into @ConPats@.
355
356 \item[@LitPats@ and @NPats@:]
357 @LitPats@/@NPats@ of ``known friendly types'' (Int, Char,
358 Float, Double, at least) are converted to unboxed form; e.g.,
359 \tr{(NPat (HsInt i) _ _)} is converted to:
360 \begin{verbatim}
361 (ConPat I# _ _ [LitPat (HsIntPrim i)])
362 \end{verbatim}
363 \end{description}
364 -}
365
366 tidyEqnInfo :: Id -> EquationInfo
367 -> DsM (DsWrapper, EquationInfo)
368 -- DsM'd because of internal call to dsLHsBinds
369 -- and mkSelectorBinds.
370 -- "tidy1" does the interesting stuff, looking at
371 -- one pattern and fiddling the list of bindings.
372 --
373 -- POST CONDITION: head pattern in the EqnInfo is
374 -- WildPat
375 -- ConPat
376 -- NPat
377 -- LitPat
378 -- NPlusKPat
379 -- but no other
380
381 tidyEqnInfo _ (EqnInfo { eqn_pats = [] })
382 = panic "tidyEqnInfo"
383
384 tidyEqnInfo v eqn@(EqnInfo { eqn_pats = pat : pats })
385 = do { (wrap, pat') <- tidy1 v pat
386 ; return (wrap, eqn { eqn_pats = do pat' : pats }) }
387
388 tidy1 :: Id -- The Id being scrutinised
389 -> Pat Id -- The pattern against which it is to be matched
390 -> DsM (DsWrapper, -- Extra bindings to do before the match
391 Pat Id) -- Equivalent pattern
392
393 -------------------------------------------------------
394 -- (pat', mr') = tidy1 v pat mr
395 -- tidies the *outer level only* of pat, giving pat'
396 -- It eliminates many pattern forms (as-patterns, variable patterns,
397 -- list patterns, etc) yielding one of:
398 -- WildPat
399 -- ConPatOut
400 -- LitPat
401 -- NPat
402 -- NPlusKPat
403
404 tidy1 v (ParPat pat) = tidy1 v (unLoc pat)
405 tidy1 v (SigPatOut pat _) = tidy1 v (unLoc pat)
406 tidy1 _ (WildPat ty) = return (idDsWrapper, WildPat ty)
407 tidy1 v (BangPat (L l p)) = tidy_bang_pat v l p
408
409 -- case v of { x -> mr[] }
410 -- = case v of { _ -> let x=v in mr[] }
411 tidy1 v (VarPat (L _ var))
412 = return (wrapBind var v, WildPat (idType var))
413
414 -- case v of { x@p -> mr[] }
415 -- = case v of { p -> let x=v in mr[] }
416 tidy1 v (AsPat (L _ var) pat)
417 = do { (wrap, pat') <- tidy1 v (unLoc pat)
418 ; return (wrapBind var v . wrap, pat') }
419
420 {- now, here we handle lazy patterns:
421 tidy1 v ~p bs = (v, v1 = case v of p -> v1 :
422 v2 = case v of p -> v2 : ... : bs )
423
424 where the v_i's are the binders in the pattern.
425
426 ToDo: in "v_i = ... -> v_i", are the v_i's really the same thing?
427
428 The case expr for v_i is just: match [v] [(p, [], \ x -> Var v_i)] any_expr
429 -}
430
431 tidy1 v (LazyPat pat)
432 = do { (_,sel_prs) <- mkSelectorBinds [] pat (Var v)
433 ; let sel_binds = [NonRec b rhs | (b,rhs) <- sel_prs]
434 ; return (mkCoreLets sel_binds, WildPat (idType v)) }
435
436 tidy1 _ (ListPat pats ty Nothing)
437 = return (idDsWrapper, unLoc list_ConPat)
438 where
439 list_ConPat = foldr (\ x y -> mkPrefixConPat consDataCon [x, y] [ty])
440 (mkNilPat ty)
441 pats
442
443 -- Introduce fake parallel array constructors to be able to handle parallel
444 -- arrays with the existing machinery for constructor pattern
445 tidy1 _ (PArrPat pats ty)
446 = return (idDsWrapper, unLoc parrConPat)
447 where
448 arity = length pats
449 parrConPat = mkPrefixConPat (parrFakeCon arity) pats [ty]
450
451 tidy1 _ (TuplePat pats boxity tys)
452 = return (idDsWrapper, unLoc tuple_ConPat)
453 where
454 arity = length pats
455 tuple_ConPat = mkPrefixConPat (tupleDataCon boxity arity) pats tys
456
457 -- LitPats: we *might* be able to replace these w/ a simpler form
458 tidy1 _ (LitPat lit)
459 = return (idDsWrapper, tidyLitPat lit)
460
461 -- NPats: we *might* be able to replace these w/ a simpler form
462 tidy1 _ (NPat (L _ lit) mb_neg eq ty)
463 = return (idDsWrapper, tidyNPat tidyLitPat lit mb_neg eq ty)
464
465 -- Everything else goes through unchanged...
466
467 tidy1 _ non_interesting_pat
468 = return (idDsWrapper, non_interesting_pat)
469
470 --------------------
471 tidy_bang_pat :: Id -> SrcSpan -> Pat Id -> DsM (DsWrapper, Pat Id)
472
473 -- Discard par/sig under a bang
474 tidy_bang_pat v _ (ParPat (L l p)) = tidy_bang_pat v l p
475 tidy_bang_pat v _ (SigPatOut (L l p) _) = tidy_bang_pat v l p
476
477 -- Push the bang-pattern inwards, in the hope that
478 -- it may disappear next time
479 tidy_bang_pat v l (AsPat v' p) = tidy1 v (AsPat v' (L l (BangPat p)))
480 tidy_bang_pat v l (CoPat w p t) = tidy1 v (CoPat w (BangPat (L l p)) t)
481
482 -- Discard bang around strict pattern
483 tidy_bang_pat v _ p@(LitPat {}) = tidy1 v p
484 tidy_bang_pat v _ p@(ListPat {}) = tidy1 v p
485 tidy_bang_pat v _ p@(TuplePat {}) = tidy1 v p
486 tidy_bang_pat v _ p@(PArrPat {}) = tidy1 v p
487
488 -- Data/newtype constructors
489 tidy_bang_pat v l p@(ConPatOut { pat_con = L _ (RealDataCon dc), pat_args = args })
490 | isNewTyCon (dataConTyCon dc) -- Newtypes: push bang inwards (Trac #9844)
491 = tidy1 v (p { pat_args = push_bang_into_newtype_arg l args })
492 | otherwise -- Data types: discard the bang
493 = tidy1 v p
494
495 -------------------
496 -- Default case, leave the bang there:
497 -- VarPat,
498 -- LazyPat,
499 -- WildPat,
500 -- ViewPat,
501 -- pattern synonyms (ConPatOut with PatSynCon)
502 -- NPat,
503 -- NPlusKPat
504 --
505 -- For LazyPat, remember that it's semantically like a VarPat
506 -- i.e. !(~p) is not like ~p, or p! (Trac #8952)
507 --
508 -- NB: SigPatIn, ConPatIn should not happen
509
510 tidy_bang_pat _ l p = return (idDsWrapper, BangPat (L l p))
511
512 -------------------
513 push_bang_into_newtype_arg :: SrcSpan -> HsConPatDetails Id -> HsConPatDetails Id
514 -- See Note [Bang patterns and newtypes]
515 -- We are transforming !(N p) into (N !p)
516 push_bang_into_newtype_arg l (PrefixCon (arg:args))
517 = ASSERT( null args)
518 PrefixCon [L l (BangPat arg)]
519 push_bang_into_newtype_arg l (RecCon rf)
520 | HsRecFields { rec_flds = L lf fld : flds } <- rf
521 , HsRecField { hsRecFieldArg = arg } <- fld
522 = ASSERT( null flds)
523 RecCon (rf { rec_flds = [L lf (fld { hsRecFieldArg = L l (BangPat arg) })] })
524 push_bang_into_newtype_arg _ cd
525 = pprPanic "push_bang_into_newtype_arg" (pprConArgs cd)
526
527 {-
528 Note [Bang patterns and newtypes]
529 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
530 For the pattern !(Just pat) we can discard the bang, because
531 the pattern is strict anyway. But for !(N pat), where
532 newtype NT = N Int
533 we definitely can't discard the bang. Trac #9844.
534
535 So what we do is to push the bang inwards, in the hope that it will
536 get discarded there. So we transform
537 !(N pat) into (N !pat)
538
539
540 \noindent
541 {\bf Previous @matchTwiddled@ stuff:}
542
543 Now we get to the only interesting part; note: there are choices for
544 translation [from Simon's notes]; translation~1:
545 \begin{verbatim}
546 deTwiddle [s,t] e
547 \end{verbatim}
548 returns
549 \begin{verbatim}
550 [ w = e,
551 s = case w of [s,t] -> s
552 t = case w of [s,t] -> t
553 ]
554 \end{verbatim}
555
556 Here \tr{w} is a fresh variable, and the \tr{w}-binding prevents multiple
557 evaluation of \tr{e}. An alternative translation (No.~2):
558 \begin{verbatim}
559 [ w = case e of [s,t] -> (s,t)
560 s = case w of (s,t) -> s
561 t = case w of (s,t) -> t
562 ]
563 \end{verbatim}
564
565 ************************************************************************
566 * *
567 \subsubsection[improved-unmixing]{UNIMPLEMENTED idea for improved unmixing}
568 * *
569 ************************************************************************
570
571 We might be able to optimise unmixing when confronted by
572 only-one-constructor-possible, of which tuples are the most notable
573 examples. Consider:
574 \begin{verbatim}
575 f (a,b,c) ... = ...
576 f d ... (e:f) = ...
577 f (g,h,i) ... = ...
578 f j ... = ...
579 \end{verbatim}
580 This definition would normally be unmixed into four equation blocks,
581 one per equation. But it could be unmixed into just one equation
582 block, because if the one equation matches (on the first column),
583 the others certainly will.
584
585 You have to be careful, though; the example
586 \begin{verbatim}
587 f j ... = ...
588 -------------------
589 f (a,b,c) ... = ...
590 f d ... (e:f) = ...
591 f (g,h,i) ... = ...
592 \end{verbatim}
593 {\em must} be broken into two blocks at the line shown; otherwise, you
594 are forcing unnecessary evaluation. In any case, the top-left pattern
595 always gives the cue. You could then unmix blocks into groups of...
596 \begin{description}
597 \item[all variables:]
598 As it is now.
599 \item[constructors or variables (mixed):]
600 Need to make sure the right names get bound for the variable patterns.
601 \item[literals or variables (mixed):]
602 Presumably just a variant on the constructor case (as it is now).
603 \end{description}
604
605 ************************************************************************
606 * *
607 * matchWrapper: a convenient way to call @match@ *
608 * *
609 ************************************************************************
610 \subsection[matchWrapper]{@matchWrapper@: a convenient interface to @match@}
611
612 Calls to @match@ often involve similar (non-trivial) work; that work
613 is collected here, in @matchWrapper@. This function takes as
614 arguments:
615 \begin{itemize}
616 \item
617 Typchecked @Matches@ (of a function definition, or a case or lambda
618 expression)---the main input;
619 \item
620 An error message to be inserted into any (runtime) pattern-matching
621 failure messages.
622 \end{itemize}
623
624 As results, @matchWrapper@ produces:
625 \begin{itemize}
626 \item
627 A list of variables (@Locals@) that the caller must ``promise'' to
628 bind to appropriate values; and
629 \item
630 a @CoreExpr@, the desugared output (main result).
631 \end{itemize}
632
633 The main actions of @matchWrapper@ include:
634 \begin{enumerate}
635 \item
636 Flatten the @[TypecheckedMatch]@ into a suitable list of
637 @EquationInfo@s.
638 \item
639 Create as many new variables as there are patterns in a pattern-list
640 (in any one of the @EquationInfo@s).
641 \item
642 Create a suitable ``if it fails'' expression---a call to @error@ using
643 the error-string input; the {\em type} of this fail value can be found
644 by examining one of the RHS expressions in one of the @EquationInfo@s.
645 \item
646 Call @match@ with all of this information!
647 \end{enumerate}
648 -}
649
650 matchWrapper :: HsMatchContext Name -- For shadowing warning messages
651 -> Maybe (LHsExpr Id) -- The scrutinee, if we check a case expr
652 -> MatchGroup Id (LHsExpr Id) -- Matches being desugared
653 -> DsM ([Id], CoreExpr) -- Results
654
655 {-
656 There is one small problem with the Lambda Patterns, when somebody
657 writes something similar to:
658 \begin{verbatim}
659 (\ (x:xs) -> ...)
660 \end{verbatim}
661 he/she don't want a warning about incomplete patterns, that is done with
662 the flag @opt_WarnSimplePatterns@.
663 This problem also appears in the:
664 \begin{itemize}
665 \item @do@ patterns, but if the @do@ can fail
666 it creates another equation if the match can fail
667 (see @DsExpr.doDo@ function)
668 \item @let@ patterns, are treated by @matchSimply@
669 List Comprension Patterns, are treated by @matchSimply@ also
670 \end{itemize}
671
672 We can't call @matchSimply@ with Lambda patterns,
673 due to the fact that lambda patterns can have more than
674 one pattern, and match simply only accepts one pattern.
675
676 JJQC 30-Nov-1997
677 -}
678
679 matchWrapper ctxt mb_scr (MG { mg_alts = L _ matches
680 , mg_arg_tys = arg_tys
681 , mg_res_ty = rhs_ty
682 , mg_origin = origin })
683 = do { dflags <- getDynFlags
684 ; locn <- getSrcSpanDs
685
686 ; new_vars <- case matches of
687 [] -> mapM newSysLocalDs arg_tys
688 (m:_) -> selectMatchVars (map unLoc (hsLMatchPats m))
689
690 ; eqns_info <- mapM (mk_eqn_info new_vars) matches
691
692 -- pattern match check warnings
693 ; unless (isGenerated origin) $
694 when (isAnyPmCheckEnabled dflags (DsMatchContext ctxt locn)) $
695 addTmCsDs (genCaseTmCs1 mb_scr new_vars) $
696 -- See Note [Type and Term Equality Propagation]
697 checkMatches dflags (DsMatchContext ctxt locn) new_vars matches
698
699 ; result_expr <- handleWarnings $
700 matchEquations ctxt new_vars eqns_info rhs_ty
701 ; return (new_vars, result_expr) }
702 where
703 mk_eqn_info vars (L _ (Match _ pats _ grhss))
704 = do { dflags <- getDynFlags
705 ; let upats = map (unLoc . decideBangHood dflags) pats
706 dicts = toTcTypeBag (collectEvVarsPats upats) -- Only TcTyVars
707 ; tm_cs <- genCaseTmCs2 mb_scr upats vars
708 ; match_result <- addDictsDs dicts $ -- See Note [Type and Term Equality Propagation]
709 addTmCsDs tm_cs $ -- See Note [Type and Term Equality Propagation]
710 dsGRHSs ctxt upats grhss rhs_ty
711 ; return (EqnInfo { eqn_pats = upats, eqn_rhs = match_result}) }
712
713 handleWarnings = if isGenerated origin
714 then discardWarningsDs
715 else id
716
717
718 matchEquations :: HsMatchContext Name
719 -> [Id] -> [EquationInfo] -> Type
720 -> DsM CoreExpr
721 matchEquations ctxt vars eqns_info rhs_ty
722 = do { let error_doc = matchContextErrString ctxt
723
724 ; match_result <- match vars rhs_ty eqns_info
725
726 ; fail_expr <- mkErrorAppDs pAT_ERROR_ID rhs_ty error_doc
727 ; extractMatchResult match_result fail_expr }
728
729 {-
730 ************************************************************************
731 * *
732 \subsection[matchSimply]{@matchSimply@: match a single expression against a single pattern}
733 * *
734 ************************************************************************
735
736 @mkSimpleMatch@ is a wrapper for @match@ which deals with the
737 situation where we want to match a single expression against a single
738 pattern. It returns an expression.
739 -}
740
741 matchSimply :: CoreExpr -- Scrutinee
742 -> HsMatchContext Name -- Match kind
743 -> LPat Id -- Pattern it should match
744 -> CoreExpr -- Return this if it matches
745 -> CoreExpr -- Return this if it doesn't
746 -> DsM CoreExpr
747 -- Do not warn about incomplete patterns; see matchSinglePat comments
748 matchSimply scrut hs_ctx pat result_expr fail_expr = do
749 let
750 match_result = cantFailMatchResult result_expr
751 rhs_ty = exprType fail_expr
752 -- Use exprType of fail_expr, because won't refine in the case of failure!
753 match_result' <- matchSinglePat scrut hs_ctx pat rhs_ty match_result
754 extractMatchResult match_result' fail_expr
755
756 matchSinglePat :: CoreExpr -> HsMatchContext Name -> LPat Id
757 -> Type -> MatchResult -> DsM MatchResult
758 -- Do not warn about incomplete patterns
759 -- Used for things like [ e | pat <- stuff ], where
760 -- incomplete patterns are just fine
761 matchSinglePat (Var var) ctx pat ty match_result
762 = do { dflags <- getDynFlags
763 ; locn <- getSrcSpanDs
764 -- Pattern match check warnings
765 ; checkSingle dflags (DsMatchContext ctx locn) var (unLoc pat)
766
767 ; let eqn_info = EqnInfo { eqn_pats = [unLoc (decideBangHood dflags pat)]
768 , eqn_rhs = match_result }
769 ; match [var] ty [eqn_info] }
770
771 matchSinglePat scrut hs_ctx pat ty match_result
772 = do { var <- selectSimpleMatchVarL pat
773 ; match_result' <- matchSinglePat (Var var) hs_ctx pat ty match_result
774 ; return (adjustMatchResult (bindNonRec var scrut) match_result') }
775
776
777 {-
778 ************************************************************************
779 * *
780 Pattern classification
781 * *
782 ************************************************************************
783 -}
784
785 data PatGroup
786 = PgAny -- Immediate match: variables, wildcards,
787 -- lazy patterns
788 | PgCon DataCon -- Constructor patterns (incl list, tuple)
789 | PgSyn PatSyn [Type] -- See Note [Pattern synonym groups]
790 | PgLit Literal -- Literal patterns
791 | PgN Literal -- Overloaded literals
792 | PgNpK Literal -- n+k patterns
793 | PgBang -- Bang patterns
794 | PgCo Type -- Coercion patterns; the type is the type
795 -- of the pattern *inside*
796 | PgView (LHsExpr Id) -- view pattern (e -> p):
797 -- the LHsExpr is the expression e
798 Type -- the Type is the type of p (equivalently, the result type of e)
799 | PgOverloadedList
800
801 groupEquations :: DynFlags -> [EquationInfo] -> [[(PatGroup, EquationInfo)]]
802 -- If the result is of form [g1, g2, g3],
803 -- (a) all the (pg,eq) pairs in g1 have the same pg
804 -- (b) none of the gi are empty
805 -- The ordering of equations is unchanged
806 groupEquations dflags eqns
807 = runs same_gp [(patGroup dflags (firstPat eqn), eqn) | eqn <- eqns]
808 where
809 same_gp :: (PatGroup,EquationInfo) -> (PatGroup,EquationInfo) -> Bool
810 (pg1,_) `same_gp` (pg2,_) = pg1 `sameGroup` pg2
811
812 subGroup :: Ord a => [(a, EquationInfo)] -> [[EquationInfo]]
813 -- Input is a particular group. The result sub-groups the
814 -- equations by with particular constructor, literal etc they match.
815 -- Each sub-list in the result has the same PatGroup
816 -- See Note [Take care with pattern order]
817 subGroup group
818 = map reverse $ Map.elems $ foldl accumulate Map.empty group
819 where
820 accumulate pg_map (pg, eqn)
821 = case Map.lookup pg pg_map of
822 Just eqns -> Map.insert pg (eqn:eqns) pg_map
823 Nothing -> Map.insert pg [eqn] pg_map
824
825 -- pg_map :: Map a [EquationInfo]
826 -- Equations seen so far in reverse order of appearance
827
828 {- Note [Pattern synonym groups]
829 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
830 If we see
831 f (P a) = e1
832 f (P b) = e2
833 ...
834 where P is a pattern synonym, can we put (P a -> e1) and (P b -> e2) in the
835 same group? We can if P is a constructor, but /not/ if P is a pattern synonym.
836 Consider (Trac #11224)
837 -- readMaybe :: Read a => String -> Maybe a
838 pattern PRead :: Read a => () => a -> String
839 pattern PRead a <- (readMaybe -> Just a)
840
841 f (PRead (x::Int)) = e1
842 f (PRead (y::Bool)) = e2
843 This is all fine: we match the string by trying to read an Int; if that
844 fails we try to read a Bool. But clearly we can't combine the two into a single
845 match.
846
847 Conclusion: we can combine when we invoke PRead /at the same type/. Hence
848 in PgSyn we record the instantiaing types, and use them in sameGroup.
849
850 Note [Take care with pattern order]
851 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
852 In the subGroup function we must be very careful about pattern re-ordering,
853 Consider the patterns [ (True, Nothing), (False, x), (True, y) ]
854 Then in bringing together the patterns for True, we must not
855 swap the Nothing and y!
856 -}
857
858 sameGroup :: PatGroup -> PatGroup -> Bool
859 -- Same group means that a single case expression
860 -- or test will suffice to match both, *and* the order
861 -- of testing within the group is insignificant.
862 sameGroup PgAny PgAny = True
863 sameGroup PgBang PgBang = True
864 sameGroup (PgCon _) (PgCon _) = True -- One case expression
865 sameGroup (PgSyn p1 t1) (PgSyn p2 t2) = p1==p2 && eqTypes t1 t2
866 -- eqTypes: See Note [Pattern synonym groups]
867 sameGroup (PgLit _) (PgLit _) = True -- One case expression
868 sameGroup (PgN l1) (PgN l2) = l1==l2 -- Order is significant
869 sameGroup (PgNpK l1) (PgNpK l2) = l1==l2 -- See Note [Grouping overloaded literal patterns]
870 sameGroup (PgCo t1) (PgCo t2) = t1 `eqType` t2
871 -- CoPats are in the same goup only if the type of the
872 -- enclosed pattern is the same. The patterns outside the CoPat
873 -- always have the same type, so this boils down to saying that
874 -- the two coercions are identical.
875 sameGroup (PgView e1 t1) (PgView e2 t2) = viewLExprEq (e1,t1) (e2,t2)
876 -- ViewPats are in the same group iff the expressions
877 -- are "equal"---conservatively, we use syntactic equality
878 sameGroup _ _ = False
879
880 -- An approximation of syntactic equality used for determining when view
881 -- exprs are in the same group.
882 -- This function can always safely return false;
883 -- but doing so will result in the application of the view function being repeated.
884 --
885 -- Currently: compare applications of literals and variables
886 -- and anything else that we can do without involving other
887 -- HsSyn types in the recursion
888 --
889 -- NB we can't assume that the two view expressions have the same type. Consider
890 -- f (e1 -> True) = ...
891 -- f (e2 -> "hi") = ...
892 viewLExprEq :: (LHsExpr Id,Type) -> (LHsExpr Id,Type) -> Bool
893 viewLExprEq (e1,_) (e2,_) = lexp e1 e2
894 where
895 lexp :: LHsExpr Id -> LHsExpr Id -> Bool
896 lexp e e' = exp (unLoc e) (unLoc e')
897
898 ---------
899 exp :: HsExpr Id -> HsExpr Id -> Bool
900 -- real comparison is on HsExpr's
901 -- strip parens
902 exp (HsPar (L _ e)) e' = exp e e'
903 exp e (HsPar (L _ e')) = exp e e'
904 -- because the expressions do not necessarily have the same type,
905 -- we have to compare the wrappers
906 exp (HsWrap h e) (HsWrap h' e') = wrap h h' && exp e e'
907 exp (HsVar i) (HsVar i') = i == i'
908 -- the instance for IPName derives using the id, so this works if the
909 -- above does
910 exp (HsIPVar i) (HsIPVar i') = i == i'
911 exp (HsOverLabel l) (HsOverLabel l') = l == l'
912 exp (HsOverLit l) (HsOverLit l') =
913 -- Overloaded lits are equal if they have the same type
914 -- and the data is the same.
915 -- this is coarser than comparing the SyntaxExpr's in l and l',
916 -- which resolve the overloading (e.g., fromInteger 1),
917 -- because these expressions get written as a bunch of different variables
918 -- (presumably to improve sharing)
919 eqType (overLitType l) (overLitType l') && l == l'
920 exp (HsApp e1 e2) (HsApp e1' e2') = lexp e1 e1' && lexp e2 e2'
921 -- the fixities have been straightened out by now, so it's safe
922 -- to ignore them?
923 exp (OpApp l o _ ri) (OpApp l' o' _ ri') =
924 lexp l l' && lexp o o' && lexp ri ri'
925 exp (NegApp e n) (NegApp e' n') = lexp e e' && syn_exp n n'
926 exp (SectionL e1 e2) (SectionL e1' e2') =
927 lexp e1 e1' && lexp e2 e2'
928 exp (SectionR e1 e2) (SectionR e1' e2') =
929 lexp e1 e1' && lexp e2 e2'
930 exp (ExplicitTuple es1 _) (ExplicitTuple es2 _) =
931 eq_list tup_arg es1 es2
932 exp (HsIf _ e e1 e2) (HsIf _ e' e1' e2') =
933 lexp e e' && lexp e1 e1' && lexp e2 e2'
934
935 -- Enhancement: could implement equality for more expressions
936 -- if it seems useful
937 -- But no need for HsLit, ExplicitList, ExplicitTuple,
938 -- because they cannot be functions
939 exp _ _ = False
940
941 ---------
942 syn_exp :: SyntaxExpr Id -> SyntaxExpr Id -> Bool
943 syn_exp (SyntaxExpr { syn_expr = expr1
944 , syn_arg_wraps = arg_wraps1
945 , syn_res_wrap = res_wrap1 })
946 (SyntaxExpr { syn_expr = expr2
947 , syn_arg_wraps = arg_wraps2
948 , syn_res_wrap = res_wrap2 })
949 = exp expr1 expr2 &&
950 and (zipWithEqual "viewLExprEq" wrap arg_wraps1 arg_wraps2) &&
951 wrap res_wrap1 res_wrap2
952
953 ---------
954 tup_arg (L _ (Present e1)) (L _ (Present e2)) = lexp e1 e2
955 tup_arg (L _ (Missing t1)) (L _ (Missing t2)) = eqType t1 t2
956 tup_arg _ _ = False
957
958 ---------
959 wrap :: HsWrapper -> HsWrapper -> Bool
960 -- Conservative, in that it demands that wrappers be
961 -- syntactically identical and doesn't look under binders
962 --
963 -- Coarser notions of equality are possible
964 -- (e.g., reassociating compositions,
965 -- equating different ways of writing a coercion)
966 wrap WpHole WpHole = True
967 wrap (WpCompose w1 w2) (WpCompose w1' w2') = wrap w1 w1' && wrap w2 w2'
968 wrap (WpFun w1 w2 _) (WpFun w1' w2' _) = wrap w1 w1' && wrap w2 w2'
969 wrap (WpCast co) (WpCast co') = co `eqCoercion` co'
970 wrap (WpEvApp et1) (WpEvApp et2) = et1 `ev_term` et2
971 wrap (WpTyApp t) (WpTyApp t') = eqType t t'
972 -- Enhancement: could implement equality for more wrappers
973 -- if it seems useful (lams and lets)
974 wrap _ _ = False
975
976 ---------
977 ev_term :: EvTerm -> EvTerm -> Bool
978 ev_term (EvId a) (EvId b) = a==b
979 ev_term (EvCoercion a) (EvCoercion b) = a `eqCoercion` b
980 ev_term _ _ = False
981
982 ---------
983 eq_list :: (a->a->Bool) -> [a] -> [a] -> Bool
984 eq_list _ [] [] = True
985 eq_list _ [] (_:_) = False
986 eq_list _ (_:_) [] = False
987 eq_list eq (x:xs) (y:ys) = eq x y && eq_list eq xs ys
988
989 patGroup :: DynFlags -> Pat Id -> PatGroup
990 patGroup _ (ConPatOut { pat_con = L _ con
991 , pat_arg_tys = tys })
992 | RealDataCon dcon <- con = PgCon dcon
993 | PatSynCon psyn <- con = PgSyn psyn tys
994 patGroup _ (WildPat {}) = PgAny
995 patGroup _ (BangPat {}) = PgBang
996 patGroup _ (NPat (L _ olit) mb_neg _ _) = PgN (hsOverLitKey olit (isJust mb_neg))
997 patGroup _ (NPlusKPat _ (L _ olit) _ _ _ _)= PgNpK (hsOverLitKey olit False)
998 patGroup _ (CoPat _ p _) = PgCo (hsPatType p) -- Type of innelexp pattern
999 patGroup _ (ViewPat expr p _) = PgView expr (hsPatType (unLoc p))
1000 patGroup _ (ListPat _ _ (Just _)) = PgOverloadedList
1001 patGroup dflags (LitPat lit) = PgLit (hsLitKey dflags lit)
1002 patGroup _ pat = pprPanic "patGroup" (ppr pat)
1003
1004 {-
1005 Note [Grouping overloaded literal patterns]
1006 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1007 WATCH OUT! Consider
1008
1009 f (n+1) = ...
1010 f (n+2) = ...
1011 f (n+1) = ...
1012
1013 We can't group the first and third together, because the second may match
1014 the same thing as the first. Same goes for *overloaded* literal patterns
1015 f 1 True = ...
1016 f 2 False = ...
1017 f 1 False = ...
1018 If the first arg matches '1' but the second does not match 'True', we
1019 cannot jump to the third equation! Because the same argument might
1020 match '2'!
1021 Hence we don't regard 1 and 2, or (n+1) and (n+2), as part of the same group.
1022 -}