Refactor the typechecker to use ExpTypes.
[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 (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 False [] 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) $ do
694
695 when (isAnyPmCheckEnabled dflags (DsMatchContext ctxt locn)) $ do
696
697 -- Count the number of guards that can fail
698 guards <- computeNoGuards matches
699
700 let simplify = not (gopt Opt_FullGuardReasoning dflags)
701 && (guards > maximum_failing_guards)
702
703 -- See Note [Type and Term Equality Propagation]
704 addTmCsDs (genCaseTmCs1 mb_scr new_vars) $
705 dsPmWarn dflags (DsMatchContext ctxt locn) $
706 checkMatches simplify new_vars matches
707
708 when (not (gopt Opt_FullGuardReasoning dflags)
709 && wopt Opt_WarnTooManyGuards dflags
710 && guards > maximum_failing_guards)
711 (warnManyGuards (DsMatchContext ctxt locn))
712
713 ; result_expr <- handleWarnings $
714 matchEquations ctxt new_vars eqns_info rhs_ty
715 ; return (new_vars, result_expr) }
716 where
717 mk_eqn_info vars (L _ (Match _ pats _ grhss))
718 = do { dflags <- getDynFlags
719 ; let upats = map (getMaybeStrictPat dflags) pats
720 dicts = toTcTypeBag (collectEvVarsPats upats) -- Only TcTyVars
721 ; tm_cs <- genCaseTmCs2 mb_scr upats vars
722 ; match_result <- addDictsDs dicts $ -- See Note [Type and Term Equality Propagation]
723 addTmCsDs tm_cs $ -- See Note [Type and Term Equality Propagation]
724 dsGRHSs ctxt upats grhss rhs_ty
725 ; return (EqnInfo { eqn_pats = upats, eqn_rhs = match_result}) }
726
727 handleWarnings = if isGenerated origin
728 then discardWarningsDs
729 else id
730
731
732 matchEquations :: HsMatchContext Name
733 -> [Id] -> [EquationInfo] -> Type
734 -> DsM CoreExpr
735 matchEquations ctxt vars eqns_info rhs_ty
736 = do { let error_doc = matchContextErrString ctxt
737
738 ; match_result <- match vars rhs_ty eqns_info
739
740 ; fail_expr <- mkErrorAppDs pAT_ERROR_ID rhs_ty error_doc
741 ; extractMatchResult match_result fail_expr }
742
743 {-
744 ************************************************************************
745 * *
746 \subsection[matchSimply]{@matchSimply@: match a single expression against a single pattern}
747 * *
748 ************************************************************************
749
750 @mkSimpleMatch@ is a wrapper for @match@ which deals with the
751 situation where we want to match a single expression against a single
752 pattern. It returns an expression.
753 -}
754
755 matchSimply :: CoreExpr -- Scrutinee
756 -> HsMatchContext Name -- Match kind
757 -> LPat Id -- Pattern it should match
758 -> CoreExpr -- Return this if it matches
759 -> CoreExpr -- Return this if it doesn't
760 -> DsM CoreExpr
761 -- Do not warn about incomplete patterns; see matchSinglePat comments
762 matchSimply scrut hs_ctx pat result_expr fail_expr = do
763 let
764 match_result = cantFailMatchResult result_expr
765 rhs_ty = exprType fail_expr
766 -- Use exprType of fail_expr, because won't refine in the case of failure!
767 match_result' <- matchSinglePat scrut hs_ctx pat rhs_ty match_result
768 extractMatchResult match_result' fail_expr
769
770 matchSinglePat :: CoreExpr -> HsMatchContext Name -> LPat Id
771 -> Type -> MatchResult -> DsM MatchResult
772 -- Do not warn about incomplete patterns
773 -- Used for things like [ e | pat <- stuff ], where
774 -- incomplete patterns are just fine
775 matchSinglePat (Var var) ctx pat ty match_result
776 = do { dflags <- getDynFlags
777 ; locn <- getSrcSpanDs
778 ; let pat' = getMaybeStrictPat dflags pat
779 -- pattern match check warnings
780 ; dsPmWarn dflags (DsMatchContext ctx locn) (checkSingle var pat')
781
782 ; match [var] ty
783 [EqnInfo { eqn_pats = [pat'], eqn_rhs = match_result }] }
784
785 matchSinglePat scrut hs_ctx pat ty match_result
786 = do { var <- selectSimpleMatchVarL pat
787 ; match_result' <- matchSinglePat (Var var) hs_ctx pat ty match_result
788 ; return (adjustMatchResult (bindNonRec var scrut) match_result') }
789
790 getMaybeStrictPat :: DynFlags -> LPat Id -> Pat Id
791 getMaybeStrictPat dflags pat =
792 let (is_strict, pat') = getUnBangedLPat dflags pat
793 in if is_strict then BangPat pat' else unLoc pat'
794
795
796 {-
797 ************************************************************************
798 * *
799 Pattern classification
800 * *
801 ************************************************************************
802 -}
803
804 data PatGroup
805 = PgAny -- Immediate match: variables, wildcards,
806 -- lazy patterns
807 | PgCon DataCon -- Constructor patterns (incl list, tuple)
808 | PgSyn PatSyn [Type] -- See Note [Pattern synonym groups]
809 | PgLit Literal -- Literal patterns
810 | PgN Literal -- Overloaded literals
811 | PgNpK Literal -- n+k patterns
812 | PgBang -- Bang patterns
813 | PgCo Type -- Coercion patterns; the type is the type
814 -- of the pattern *inside*
815 | PgView (LHsExpr Id) -- view pattern (e -> p):
816 -- the LHsExpr is the expression e
817 Type -- the Type is the type of p (equivalently, the result type of e)
818 | PgOverloadedList
819
820 groupEquations :: DynFlags -> [EquationInfo] -> [[(PatGroup, EquationInfo)]]
821 -- If the result is of form [g1, g2, g3],
822 -- (a) all the (pg,eq) pairs in g1 have the same pg
823 -- (b) none of the gi are empty
824 -- The ordering of equations is unchanged
825 groupEquations dflags eqns
826 = runs same_gp [(patGroup dflags (firstPat eqn), eqn) | eqn <- eqns]
827 where
828 same_gp :: (PatGroup,EquationInfo) -> (PatGroup,EquationInfo) -> Bool
829 (pg1,_) `same_gp` (pg2,_) = pg1 `sameGroup` pg2
830
831 subGroup :: Ord a => [(a, EquationInfo)] -> [[EquationInfo]]
832 -- Input is a particular group. The result sub-groups the
833 -- equations by with particular constructor, literal etc they match.
834 -- Each sub-list in the result has the same PatGroup
835 -- See Note [Take care with pattern order]
836 subGroup group
837 = map reverse $ Map.elems $ foldl accumulate Map.empty group
838 where
839 accumulate pg_map (pg, eqn)
840 = case Map.lookup pg pg_map of
841 Just eqns -> Map.insert pg (eqn:eqns) pg_map
842 Nothing -> Map.insert pg [eqn] pg_map
843
844 -- pg_map :: Map a [EquationInfo]
845 -- Equations seen so far in reverse order of appearance
846
847 {- Note [Pattern synonym groups]
848 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
849 If we see
850 f (P a) = e1
851 f (P b) = e2
852 ...
853 where P is a pattern synonym, can we put (P a -> e1) and (P b -> e2) in the
854 same group? We can if P is a constructor, but /not/ if P is a pattern synonym.
855 Consider (Trac #11224)
856 -- readMaybe :: Read a => String -> Maybe a
857 pattern PRead :: Read a => () => a -> String
858 pattern PRead a <- (readMaybe -> Just a)
859
860 f (PRead (x::Int)) = e1
861 f (PRead (y::Bool)) = e2
862 This is all fine: we match the string by trying to read an Int; if that
863 fails we try to read a Bool. But clearly we can't combine the two into a single
864 match.
865
866 Conclusion: we can combine when we invoke PRead /at the same type/. Hence
867 in PgSyn we record the instantiaing types, and use them in sameGroup.
868
869 Note [Take care with pattern order]
870 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
871 In the subGroup function we must be very careful about pattern re-ordering,
872 Consider the patterns [ (True, Nothing), (False, x), (True, y) ]
873 Then in bringing together the patterns for True, we must not
874 swap the Nothing and y!
875 -}
876
877 sameGroup :: PatGroup -> PatGroup -> Bool
878 -- Same group means that a single case expression
879 -- or test will suffice to match both, *and* the order
880 -- of testing within the group is insignificant.
881 sameGroup PgAny PgAny = True
882 sameGroup PgBang PgBang = True
883 sameGroup (PgCon _) (PgCon _) = True -- One case expression
884 sameGroup (PgSyn p1 t1) (PgSyn p2 t2) = p1==p2 && eqTypes t1 t2
885 -- eqTypes: See Note [Pattern synonym groups]
886 sameGroup (PgLit _) (PgLit _) = True -- One case expression
887 sameGroup (PgN l1) (PgN l2) = l1==l2 -- Order is significant
888 sameGroup (PgNpK l1) (PgNpK l2) = l1==l2 -- See Note [Grouping overloaded literal patterns]
889 sameGroup (PgCo t1) (PgCo t2) = t1 `eqType` t2
890 -- CoPats are in the same goup only if the type of the
891 -- enclosed pattern is the same. The patterns outside the CoPat
892 -- always have the same type, so this boils down to saying that
893 -- the two coercions are identical.
894 sameGroup (PgView e1 t1) (PgView e2 t2) = viewLExprEq (e1,t1) (e2,t2)
895 -- ViewPats are in the same group iff the expressions
896 -- are "equal"---conservatively, we use syntactic equality
897 sameGroup _ _ = False
898
899 -- An approximation of syntactic equality used for determining when view
900 -- exprs are in the same group.
901 -- This function can always safely return false;
902 -- but doing so will result in the application of the view function being repeated.
903 --
904 -- Currently: compare applications of literals and variables
905 -- and anything else that we can do without involving other
906 -- HsSyn types in the recursion
907 --
908 -- NB we can't assume that the two view expressions have the same type. Consider
909 -- f (e1 -> True) = ...
910 -- f (e2 -> "hi") = ...
911 viewLExprEq :: (LHsExpr Id,Type) -> (LHsExpr Id,Type) -> Bool
912 viewLExprEq (e1,_) (e2,_) = lexp e1 e2
913 where
914 lexp :: LHsExpr Id -> LHsExpr Id -> Bool
915 lexp e e' = exp (unLoc e) (unLoc e')
916
917 ---------
918 exp :: HsExpr Id -> HsExpr Id -> Bool
919 -- real comparison is on HsExpr's
920 -- strip parens
921 exp (HsPar (L _ e)) e' = exp e e'
922 exp e (HsPar (L _ e')) = exp e e'
923 -- because the expressions do not necessarily have the same type,
924 -- we have to compare the wrappers
925 exp (HsWrap h e) (HsWrap h' e') = wrap h h' && exp e e'
926 exp (HsVar i) (HsVar i') = i == i'
927 -- the instance for IPName derives using the id, so this works if the
928 -- above does
929 exp (HsIPVar i) (HsIPVar i') = i == i'
930 exp (HsOverLabel l) (HsOverLabel l') = l == l'
931 exp (HsOverLit l) (HsOverLit l') =
932 -- Overloaded lits are equal if they have the same type
933 -- and the data is the same.
934 -- this is coarser than comparing the SyntaxExpr's in l and l',
935 -- which resolve the overloading (e.g., fromInteger 1),
936 -- because these expressions get written as a bunch of different variables
937 -- (presumably to improve sharing)
938 eqType (overLitType l) (overLitType l') && l == l'
939 exp (HsApp e1 e2) (HsApp e1' e2') = lexp e1 e1' && lexp e2 e2'
940 -- the fixities have been straightened out by now, so it's safe
941 -- to ignore them?
942 exp (OpApp l o _ ri) (OpApp l' o' _ ri') =
943 lexp l l' && lexp o o' && lexp ri ri'
944 exp (NegApp e n) (NegApp e' n') = lexp e e' && syn_exp n n'
945 exp (SectionL e1 e2) (SectionL e1' e2') =
946 lexp e1 e1' && lexp e2 e2'
947 exp (SectionR e1 e2) (SectionR e1' e2') =
948 lexp e1 e1' && lexp e2 e2'
949 exp (ExplicitTuple es1 _) (ExplicitTuple es2 _) =
950 eq_list tup_arg es1 es2
951 exp (HsIf _ e e1 e2) (HsIf _ e' e1' e2') =
952 lexp e e' && lexp e1 e1' && lexp e2 e2'
953
954 -- Enhancement: could implement equality for more expressions
955 -- if it seems useful
956 -- But no need for HsLit, ExplicitList, ExplicitTuple,
957 -- because they cannot be functions
958 exp _ _ = False
959
960 ---------
961 syn_exp :: SyntaxExpr Id -> SyntaxExpr Id -> Bool
962 syn_exp (SyntaxExpr { syn_expr = expr1
963 , syn_arg_wraps = arg_wraps1
964 , syn_res_wrap = res_wrap1 })
965 (SyntaxExpr { syn_expr = expr2
966 , syn_arg_wraps = arg_wraps2
967 , syn_res_wrap = res_wrap2 })
968 = exp expr1 expr2 &&
969 and (zipWithEqual "viewLExprEq" wrap arg_wraps1 arg_wraps2) &&
970 wrap res_wrap1 res_wrap2
971
972 ---------
973 tup_arg (L _ (Present e1)) (L _ (Present e2)) = lexp e1 e2
974 tup_arg (L _ (Missing t1)) (L _ (Missing t2)) = eqType t1 t2
975 tup_arg _ _ = False
976
977 ---------
978 wrap :: HsWrapper -> HsWrapper -> Bool
979 -- Conservative, in that it demands that wrappers be
980 -- syntactically identical and doesn't look under binders
981 --
982 -- Coarser notions of equality are possible
983 -- (e.g., reassociating compositions,
984 -- equating different ways of writing a coercion)
985 wrap WpHole WpHole = True
986 wrap (WpCompose w1 w2) (WpCompose w1' w2') = wrap w1 w1' && wrap w2 w2'
987 wrap (WpFun w1 w2 _) (WpFun w1' w2' _) = wrap w1 w1' && wrap w2 w2'
988 wrap (WpCast co) (WpCast co') = co `eqCoercion` co'
989 wrap (WpEvApp et1) (WpEvApp et2) = et1 `ev_term` et2
990 wrap (WpTyApp t) (WpTyApp t') = eqType t t'
991 -- Enhancement: could implement equality for more wrappers
992 -- if it seems useful (lams and lets)
993 wrap _ _ = False
994
995 ---------
996 ev_term :: EvTerm -> EvTerm -> Bool
997 ev_term (EvId a) (EvId b) = a==b
998 ev_term (EvCoercion a) (EvCoercion b) = a `eqCoercion` b
999 ev_term _ _ = False
1000
1001 ---------
1002 eq_list :: (a->a->Bool) -> [a] -> [a] -> Bool
1003 eq_list _ [] [] = True
1004 eq_list _ [] (_:_) = False
1005 eq_list _ (_:_) [] = False
1006 eq_list eq (x:xs) (y:ys) = eq x y && eq_list eq xs ys
1007
1008 patGroup :: DynFlags -> Pat Id -> PatGroup
1009 patGroup _ (ConPatOut { pat_con = L _ con
1010 , pat_arg_tys = tys })
1011 | RealDataCon dcon <- con = PgCon dcon
1012 | PatSynCon psyn <- con = PgSyn psyn tys
1013 patGroup _ (WildPat {}) = PgAny
1014 patGroup _ (BangPat {}) = PgBang
1015 patGroup _ (NPat (L _ olit) mb_neg _ _) = PgN (hsOverLitKey olit (isJust mb_neg))
1016 patGroup _ (NPlusKPat _ (L _ olit) _ _ _ _)= PgNpK (hsOverLitKey olit False)
1017 patGroup _ (CoPat _ p _) = PgCo (hsPatType p) -- Type of innelexp pattern
1018 patGroup _ (ViewPat expr p _) = PgView expr (hsPatType (unLoc p))
1019 patGroup _ (ListPat _ _ (Just _)) = PgOverloadedList
1020 patGroup dflags (LitPat lit) = PgLit (hsLitKey dflags lit)
1021 patGroup _ pat = pprPanic "patGroup" (ppr pat)
1022
1023 {-
1024 Note [Grouping overloaded literal patterns]
1025 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1026 WATCH OUT! Consider
1027
1028 f (n+1) = ...
1029 f (n+2) = ...
1030 f (n+1) = ...
1031
1032 We can't group the first and third together, because the second may match
1033 the same thing as the first. Same goes for *overloaded* literal patterns
1034 f 1 True = ...
1035 f 2 False = ...
1036 f 1 False = ...
1037 If the first arg matches '1' but the second does not match 'True', we
1038 cannot jump to the third equation! Because the same argument might
1039 match '2'!
1040 Hence we don't regard 1 and 2, or (n+1) and (n+2), as part of the same group.
1041 -}