Major Overhaul of Pattern Match Checking (Fixes #595)
[ghc.git] / compiler / hsSyn / HsPat.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5 \section[PatSyntax]{Abstract Haskell syntax---patterns}
6 -}
7
8 {-# LANGUAGE DeriveDataTypeable #-}
9 {-# LANGUAGE DeriveDataTypeable #-}
10 {-# LANGUAGE StandaloneDeriving #-}
11 {-# LANGUAGE FlexibleContexts #-}
12 {-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
13 -- in module PlaceHolder
14 {-# LANGUAGE ConstraintKinds #-}
15 {-# LANGUAGE TypeFamilies #-}
16
17 module HsPat (
18 Pat(..), InPat, OutPat, LPat,
19
20 HsConDetails(..),
21 HsConPatDetails, hsConPatArgs,
22 HsRecFields(..), HsRecField'(..), LHsRecField',
23 HsRecField, LHsRecField,
24 HsRecUpdField, LHsRecUpdField,
25 hsRecFields, hsRecFieldSel, hsRecFieldId, hsRecFieldsArgs,
26 hsRecUpdFieldId, hsRecUpdFieldOcc, hsRecUpdFieldRdr,
27
28 mkPrefixConPat, mkCharLitPat, mkNilPat,
29
30 isUnliftedHsBind, looksLazyPatBind,
31 isUnliftedLPat, isBangedLPat, isBangedPatBind,
32 hsPatNeedsParens,
33 isIrrefutableHsPat,
34
35 collectEvVarsPats,
36
37 pprParendLPat, pprConArgs
38 ) where
39
40 import {-# SOURCE #-} HsExpr (SyntaxExpr, LHsExpr, HsSplice, pprLExpr, pprSplice)
41
42 -- friends:
43 import HsBinds
44 import HsLit
45 import PlaceHolder -- ( PostRn,PostTc,DataId )
46 import HsTypes
47 import TcEvidence
48 import BasicTypes
49 -- others:
50 import PprCore ( {- instance OutputableBndr TyVar -} )
51 import TysWiredIn
52 import Var
53 import RdrName ( RdrName )
54 import ConLike
55 import DataCon
56 import TyCon
57 import Outputable
58 import Type
59 import SrcLoc
60 import FastString
61 import Bag -- collect ev vars from pats
62 import Maybes
63 -- libraries:
64 import Data.Data hiding (TyCon,Fixity)
65
66 type InPat id = LPat id -- No 'Out' constructors
67 type OutPat id = LPat id -- No 'In' constructors
68
69 type LPat id = Located (Pat id)
70
71 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnBang'
72
73 -- For details on above see note [Api annotations] in ApiAnnotation
74 data Pat id
75 = ------------ Simple patterns ---------------
76 WildPat (PostTc id Type) -- Wild card
77 -- The sole reason for a type on a WildPat is to
78 -- support hsPatType :: Pat Id -> Type
79
80 | VarPat (Located id) -- Variable
81 -- See Note [Located RdrNames] in HsExpr
82 | LazyPat (LPat id) -- Lazy pattern
83 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde'
84
85 -- For details on above see note [Api annotations] in ApiAnnotation
86
87 | AsPat (Located id) (LPat id) -- As pattern
88 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt'
89
90 -- For details on above see note [Api annotations] in ApiAnnotation
91
92 | ParPat (LPat id) -- Parenthesised pattern
93 -- See Note [Parens in HsSyn] in HsExpr
94 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
95 -- 'ApiAnnotation.AnnClose' @')'@
96
97 -- For details on above see note [Api annotations] in ApiAnnotation
98 | BangPat (LPat id) -- Bang pattern
99 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnBang'
100
101 -- For details on above see note [Api annotations] in ApiAnnotation
102
103 ------------ Lists, tuples, arrays ---------------
104 | ListPat [LPat id] -- Syntactic list
105 (PostTc id Type) -- The type of the elements
106 (Maybe (PostTc id Type, SyntaxExpr id)) -- For rebindable syntax
107 -- For OverloadedLists a Just (ty,fn) gives
108 -- overall type of the pattern, and the toList
109 -- function to convert the scrutinee to a list value
110 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
111 -- 'ApiAnnotation.AnnClose' @']'@
112
113 -- For details on above see note [Api annotations] in ApiAnnotation
114
115 | TuplePat [LPat id] -- Tuple sub-patterns
116 Boxity -- UnitPat is TuplePat []
117 [PostTc id Type] -- [] before typechecker, filled in afterwards
118 -- with the types of the tuple components
119 -- You might think that the PostTc id Type was redundant, because we can
120 -- get the pattern type by getting the types of the sub-patterns.
121 -- But it's essential
122 -- data T a where
123 -- T1 :: Int -> T Int
124 -- f :: (T a, a) -> Int
125 -- f (T1 x, z) = z
126 -- When desugaring, we must generate
127 -- f = /\a. \v::a. case v of (t::T a, w::a) ->
128 -- case t of (T1 (x::Int)) ->
129 -- Note the (w::a), NOT (w::Int), because we have not yet
130 -- refined 'a' to Int. So we must know that the second component
131 -- of the tuple is of type 'a' not Int. See selectMatchVar
132 -- (June 14: I'm not sure this comment is right; the sub-patterns
133 -- will be wrapped in CoPats, no?)
134 -- ^ - 'ApiAnnotation.AnnKeywordId' :
135 -- 'ApiAnnotation.AnnOpen' @'('@ or @'(#'@,
136 -- 'ApiAnnotation.AnnClose' @')'@ or @'#)'@
137
138 -- For details on above see note [Api annotations] in ApiAnnotation
139 | PArrPat [LPat id] -- Syntactic parallel array
140 (PostTc id Type) -- The type of the elements
141 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
142 -- 'ApiAnnotation.AnnClose' @':]'@
143
144 -- For details on above see note [Api annotations] in ApiAnnotation
145 ------------ Constructor patterns ---------------
146 | ConPatIn (Located id)
147 (HsConPatDetails id)
148
149 | ConPatOut {
150 pat_con :: Located ConLike,
151 pat_arg_tys :: [Type], -- The universal arg types, 1-1 with the universal
152 -- tyvars of the constructor/pattern synonym
153 -- Use (conLikeResTy pat_con pat_arg_tys) to get
154 -- the type of the pattern
155
156 pat_tvs :: [TyVar], -- Existentially bound type variables (tyvars only)
157 pat_dicts :: [EvVar], -- Ditto *coercion variables* and *dictionaries*
158 -- One reason for putting coercion variable here, I think,
159 -- is to ensure their kinds are zonked
160 pat_binds :: TcEvBinds, -- Bindings involving those dictionaries
161 pat_args :: HsConPatDetails id,
162 pat_wrap :: HsWrapper -- Extra wrapper to pass to the matcher
163 -- Only relevant for pattern-synonyms;
164 -- ignored for data cons
165 }
166
167 ------------ View patterns ---------------
168 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow'
169
170 -- For details on above see note [Api annotations] in ApiAnnotation
171 | ViewPat (LHsExpr id)
172 (LPat id)
173 (PostTc id Type) -- The overall type of the pattern
174 -- (= the argument type of the view function)
175 -- for hsPatType.
176
177 ------------ Pattern splices ---------------
178 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'$('@
179 -- 'ApiAnnotation.AnnClose' @')'@
180
181 -- For details on above see note [Api annotations] in ApiAnnotation
182 | SplicePat (HsSplice id) -- Includes quasi-quotes
183
184 ------------ Literal and n+k patterns ---------------
185 | LitPat HsLit -- Used for *non-overloaded* literal patterns:
186 -- Int#, Char#, Int, Char, String, etc.
187
188 | NPat -- Used for all overloaded literals,
189 -- including overloaded strings with -XOverloadedStrings
190 (Located (HsOverLit id)) -- ALWAYS positive
191 (Maybe (SyntaxExpr id)) -- Just (Name of 'negate') for negative
192 -- patterns, Nothing otherwise
193 (SyntaxExpr id) -- Equality checker, of type t->t->Bool
194
195 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVal' @'+'@
196
197 -- For details on above see note [Api annotations] in ApiAnnotation
198 | NPlusKPat (Located id) -- n+k pattern
199 (Located (HsOverLit id)) -- It'll always be an HsIntegral
200 (SyntaxExpr id) -- (>=) function, of type t->t->Bool
201 (SyntaxExpr id) -- Name of '-' (see RnEnv.lookupSyntaxName)
202
203 ------------ Pattern type signatures ---------------
204 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
205
206 -- For details on above see note [Api annotations] in ApiAnnotation
207 | SigPatIn (LPat id) -- Pattern with a type signature
208 (LHsSigWcType id) -- Signature can bind both
209 -- kind and type vars
210
211 | SigPatOut (LPat id) -- Pattern with a type signature
212 Type
213
214 ------------ Pattern coercions (translation only) ---------------
215 | CoPat HsWrapper -- If co :: t1 ~ t2, p :: t2,
216 -- then (CoPat co p) :: t1
217 (Pat id) -- Why not LPat? Ans: existing locn will do
218 Type -- Type of whole pattern, t1
219 -- During desugaring a (CoPat co pat) turns into a cast with 'co' on
220 -- the scrutinee, followed by a match on 'pat'
221 deriving (Typeable)
222 deriving instance (DataId id) => Data (Pat id)
223
224 -- HsConDetails is use for patterns/expressions *and* for data type declarations
225
226 data HsConDetails arg rec
227 = PrefixCon [arg] -- C p1 p2 p3
228 | RecCon rec -- C { x = p1, y = p2 }
229 | InfixCon arg arg -- p1 `C` p2
230 deriving (Data, Typeable)
231
232 type HsConPatDetails id = HsConDetails (LPat id) (HsRecFields id (LPat id))
233
234 hsConPatArgs :: HsConPatDetails id -> [LPat id]
235 hsConPatArgs (PrefixCon ps) = ps
236 hsConPatArgs (RecCon fs) = map (hsRecFieldArg . unLoc) (rec_flds fs)
237 hsConPatArgs (InfixCon p1 p2) = [p1,p2]
238
239 {-
240 However HsRecFields is used only for patterns and expressions
241 (not data type declarations)
242 -}
243
244 data HsRecFields id arg -- A bunch of record fields
245 -- { x = 3, y = True }
246 -- Used for both expressions and patterns
247 = HsRecFields { rec_flds :: [LHsRecField id arg],
248 rec_dotdot :: Maybe Int } -- Note [DotDot fields]
249 deriving (Typeable)
250 deriving instance (DataId id, Data arg) => Data (HsRecFields id arg)
251
252 -- Note [DotDot fields]
253 -- ~~~~~~~~~~~~~~~~~~~~
254 -- The rec_dotdot field means this:
255 -- Nothing => the normal case
256 -- Just n => the group uses ".." notation,
257 --
258 -- In the latter case:
259 --
260 -- *before* renamer: rec_flds are exactly the n user-written fields
261 --
262 -- *after* renamer: rec_flds includes *all* fields, with
263 -- the first 'n' being the user-written ones
264 -- and the remainder being 'filled in' implicitly
265
266 type LHsRecField' id arg = Located (HsRecField' id arg)
267 type LHsRecField id arg = Located (HsRecField id arg)
268 type LHsRecUpdField id = Located (HsRecUpdField id)
269
270 type HsRecField id arg = HsRecField' (FieldOcc id) arg
271 type HsRecUpdField id = HsRecField' (AmbiguousFieldOcc id) (LHsExpr id)
272
273 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnEqual',
274 --
275 -- For details on above see note [Api annotations] in ApiAnnotation
276 data HsRecField' id arg = HsRecField {
277 hsRecFieldLbl :: Located id,
278 hsRecFieldArg :: arg, -- ^ Filled in by renamer when punning
279 hsRecPun :: Bool -- ^ Note [Punning]
280 } deriving (Data, Typeable)
281
282
283 -- Note [Punning]
284 -- ~~~~~~~~~~~~~~
285 -- If you write T { x, y = v+1 }, the HsRecFields will be
286 -- HsRecField x x True ...
287 -- HsRecField y (v+1) False ...
288 -- That is, for "punned" field x is expanded (in the renamer)
289 -- to x=x; but with a punning flag so we can detect it later
290 -- (e.g. when pretty printing)
291 --
292 -- If the original field was qualified, we un-qualify it, thus
293 -- T { A.x } means T { A.x = x }
294
295
296 -- Note [HsRecField and HsRecUpdField]
297 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
298
299 -- A HsRecField (used for record construction and pattern matching)
300 -- contains an unambiguous occurrence of a field (i.e. a FieldOcc).
301 -- We can't just store the Name, because thanks to
302 -- DuplicateRecordFields this may not correspond to the label the user
303 -- wrote.
304 --
305 -- A HsRecUpdField (used for record update) contains a potentially
306 -- ambiguous occurrence of a field (an AmbiguousFieldOcc). The
307 -- renamer will fill in the selector function if it can, but if the
308 -- selector is ambiguous the renamer will defer to the typechecker.
309 -- After the typechecker, a unique selector will have been determined.
310 --
311 -- The renamer produces an Unambiguous result if it can, rather than
312 -- just doing the lookup in the typechecker, so that completely
313 -- unambiguous updates can be represented by 'DsMeta.repUpdFields'.
314 --
315 -- For example, suppose we have:
316 --
317 -- data S = MkS { x :: Int }
318 -- data T = MkT { x :: Int }
319 --
320 -- f z = (z { x = 3 }) :: S
321 --
322 -- The parsed HsRecUpdField corresponding to the record update will have:
323 --
324 -- hsRecFieldLbl = Unambiguous "x" PlaceHolder :: AmbiguousFieldOcc RdrName
325 --
326 -- After the renamer, this will become:
327 --
328 -- hsRecFieldLbl = Ambiguous "x" PlaceHolder :: AmbiguousFieldOcc Name
329 --
330 -- (note that the Unambiguous constructor is not type-correct here).
331 -- The typechecker will determine the particular selector:
332 --
333 -- hsRecFieldLbl = Unambiguous "x" $sel:x:MkS :: AmbiguousFieldOcc Id
334 --
335 -- See also Note [Disambiguating record fields] in TcExpr.
336
337 hsRecFields :: HsRecFields id arg -> [PostRn id id]
338 hsRecFields rbinds = map (unLoc . hsRecFieldSel . unLoc) (rec_flds rbinds)
339
340 -- Probably won't typecheck at once, things have changed :/
341 hsRecFieldsArgs :: HsRecFields id arg -> [arg]
342 hsRecFieldsArgs rbinds = map (hsRecFieldArg . unLoc) (rec_flds rbinds)
343
344 hsRecFieldSel :: HsRecField name arg -> Located (PostRn name name)
345 hsRecFieldSel = fmap selectorFieldOcc . hsRecFieldLbl
346
347 hsRecFieldId :: HsRecField Id arg -> Located Id
348 hsRecFieldId = hsRecFieldSel
349
350 hsRecUpdFieldRdr :: HsRecUpdField id -> Located RdrName
351 hsRecUpdFieldRdr = fmap rdrNameAmbiguousFieldOcc . hsRecFieldLbl
352
353 hsRecUpdFieldId :: HsRecField' (AmbiguousFieldOcc Id) arg -> Located Id
354 hsRecUpdFieldId = fmap selectorFieldOcc . hsRecUpdFieldOcc
355
356 hsRecUpdFieldOcc :: HsRecField' (AmbiguousFieldOcc Id) arg -> LFieldOcc Id
357 hsRecUpdFieldOcc = fmap unambiguousFieldOcc . hsRecFieldLbl
358
359
360 {-
361 ************************************************************************
362 * *
363 * Printing patterns
364 * *
365 ************************************************************************
366 -}
367
368 instance (OutputableBndr name) => Outputable (Pat name) where
369 ppr = pprPat
370
371 pprPatBndr :: OutputableBndr name => name -> SDoc
372 pprPatBndr var -- Print with type info if -dppr-debug is on
373 = getPprStyle $ \ sty ->
374 if debugStyle sty then
375 parens (pprBndr LambdaBind var) -- Could pass the site to pprPat
376 -- but is it worth it?
377 else
378 pprPrefixOcc var
379
380 pprParendLPat :: (OutputableBndr name) => LPat name -> SDoc
381 pprParendLPat (L _ p) = pprParendPat p
382
383 pprParendPat :: (OutputableBndr name) => Pat name -> SDoc
384 pprParendPat p = getPprStyle $ \ sty ->
385 if need_parens sty p
386 then parens (pprPat p)
387 else pprPat p
388 where
389 need_parens sty p
390 | CoPat {} <- p -- In debug style we print the cast
391 , debugStyle sty = True -- (see pprHsWrapper) so parens are needed
392 | otherwise = hsPatNeedsParens p
393 -- But otherwise the CoPat is discarded, so it
394 -- is the pattern inside that matters. Sigh.
395
396 pprPat :: (OutputableBndr name) => Pat name -> SDoc
397 pprPat (VarPat (L _ var)) = pprPatBndr var
398 pprPat (WildPat _) = char '_'
399 pprPat (LazyPat pat) = char '~' <> pprParendLPat pat
400 pprPat (BangPat pat) = char '!' <> pprParendLPat pat
401 pprPat (AsPat name pat) = hcat [pprPrefixOcc (unLoc name), char '@', pprParendLPat pat]
402 pprPat (ViewPat expr pat _) = hcat [pprLExpr expr, text " -> ", ppr pat]
403 pprPat (ParPat pat) = parens (ppr pat)
404 pprPat (LitPat s) = ppr s
405 pprPat (NPat l Nothing _) = ppr l
406 pprPat (NPat l (Just _) _) = char '-' <> ppr l
407 pprPat (NPlusKPat n k _ _) = hcat [ppr n, char '+', ppr k]
408 pprPat (SplicePat splice) = pprSplice splice
409 pprPat (CoPat co pat _) = pprHsWrapper (ppr pat) co
410 pprPat (SigPatIn pat ty) = ppr pat <+> dcolon <+> ppr ty
411 pprPat (SigPatOut pat ty) = ppr pat <+> dcolon <+> ppr ty
412 pprPat (ListPat pats _ _) = brackets (interpp'SP pats)
413 pprPat (PArrPat pats _) = paBrackets (interpp'SP pats)
414 pprPat (TuplePat pats bx _) = tupleParens (boxityTupleSort bx) (pprWithCommas ppr pats)
415 pprPat (ConPatIn con details) = pprUserCon (unLoc con) details
416 pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts,
417 pat_binds = binds, pat_args = details })
418 = getPprStyle $ \ sty -> -- Tiresome; in TcBinds.tcRhs we print out a
419 if debugStyle sty then -- typechecked Pat in an error message,
420 -- and we want to make sure it prints nicely
421 ppr con
422 <> braces (sep [ hsep (map pprPatBndr (tvs ++ dicts))
423 , ppr binds])
424 <+> pprConArgs details
425 else pprUserCon (unLoc con) details
426
427
428 pprUserCon :: (OutputableBndr con, OutputableBndr id) => con -> HsConPatDetails id -> SDoc
429 pprUserCon c (InfixCon p1 p2) = ppr p1 <+> pprInfixOcc c <+> ppr p2
430 pprUserCon c details = pprPrefixOcc c <+> pprConArgs details
431
432 pprConArgs :: OutputableBndr id => HsConPatDetails id -> SDoc
433 pprConArgs (PrefixCon pats) = sep (map pprParendLPat pats)
434 pprConArgs (InfixCon p1 p2) = sep [pprParendLPat p1, pprParendLPat p2]
435 pprConArgs (RecCon rpats) = ppr rpats
436
437 instance (Outputable arg)
438 => Outputable (HsRecFields id arg) where
439 ppr (HsRecFields { rec_flds = flds, rec_dotdot = Nothing })
440 = braces (fsep (punctuate comma (map ppr flds)))
441 ppr (HsRecFields { rec_flds = flds, rec_dotdot = Just n })
442 = braces (fsep (punctuate comma (map ppr (take n flds) ++ [dotdot])))
443 where
444 dotdot = ptext (sLit "..") <+> ifPprDebug (ppr (drop n flds))
445
446 instance (Outputable id, Outputable arg)
447 => Outputable (HsRecField' id arg) where
448 ppr (HsRecField { hsRecFieldLbl = f, hsRecFieldArg = arg,
449 hsRecPun = pun })
450 = ppr f <+> (ppUnless pun $ equals <+> ppr arg)
451
452
453 {-
454 ************************************************************************
455 * *
456 * Building patterns
457 * *
458 ************************************************************************
459 -}
460
461 mkPrefixConPat :: DataCon -> [OutPat id] -> [Type] -> OutPat id
462 -- Make a vanilla Prefix constructor pattern
463 mkPrefixConPat dc pats tys
464 = noLoc $ ConPatOut { pat_con = noLoc (RealDataCon dc), pat_tvs = [], pat_dicts = [],
465 pat_binds = emptyTcEvBinds, pat_args = PrefixCon pats,
466 pat_arg_tys = tys, pat_wrap = idHsWrapper }
467
468 mkNilPat :: Type -> OutPat id
469 mkNilPat ty = mkPrefixConPat nilDataCon [] [ty]
470
471 mkCharLitPat :: String -> Char -> OutPat id
472 mkCharLitPat src c = mkPrefixConPat charDataCon
473 [noLoc $ LitPat (HsCharPrim src c)] []
474
475 {-
476 ************************************************************************
477 * *
478 * Predicates for checking things about pattern-lists in EquationInfo *
479 * *
480 ************************************************************************
481
482 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
483
484 Unlike in the Wadler chapter, where patterns are either ``variables''
485 or ``constructors,'' here we distinguish between:
486 \begin{description}
487 \item[unfailable:]
488 Patterns that cannot fail to match: variables, wildcards, and lazy
489 patterns.
490
491 These are the irrefutable patterns; the two other categories
492 are refutable patterns.
493
494 \item[constructor:]
495 A non-literal constructor pattern (see next category).
496
497 \item[literal patterns:]
498 At least the numeric ones may be overloaded.
499 \end{description}
500
501 A pattern is in {\em exactly one} of the above three categories; `as'
502 patterns are treated specially, of course.
503
504 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
505 -}
506
507 isUnliftedLPat :: LPat id -> Bool
508 isUnliftedLPat (L _ (ParPat p)) = isUnliftedLPat p
509 isUnliftedLPat (L _ (TuplePat _ Unboxed _)) = True
510 isUnliftedLPat _ = False
511
512 isUnliftedHsBind :: HsBind id -> Bool
513 -- A pattern binding with an outermost bang or unboxed tuple must be matched strictly
514 -- Defined in this module because HsPat is above HsBinds in the import graph
515 isUnliftedHsBind (PatBind { pat_lhs = p }) = isUnliftedLPat p
516 isUnliftedHsBind _ = False
517
518 isBangedPatBind :: HsBind id -> Bool
519 isBangedPatBind (PatBind {pat_lhs = pat}) = isBangedLPat pat
520 isBangedPatBind _ = False
521
522 isBangedLPat :: LPat id -> Bool
523 isBangedLPat (L _ (ParPat p)) = isBangedLPat p
524 isBangedLPat (L _ (BangPat {})) = True
525 isBangedLPat _ = False
526
527 looksLazyPatBind :: HsBind id -> Bool
528 -- Returns True of anything *except*
529 -- a StrictHsBind (as above) or
530 -- a VarPat
531 -- In particular, returns True of a pattern binding with a compound pattern, like (I# x)
532 looksLazyPatBind (PatBind { pat_lhs = p }) = looksLazyLPat p
533 looksLazyPatBind _ = False
534
535 looksLazyLPat :: LPat id -> Bool
536 looksLazyLPat (L _ (ParPat p)) = looksLazyLPat p
537 looksLazyLPat (L _ (AsPat _ p)) = looksLazyLPat p
538 looksLazyLPat (L _ (BangPat {})) = False
539 looksLazyLPat (L _ (TuplePat _ Unboxed _)) = False
540 looksLazyLPat (L _ (VarPat {})) = False
541 looksLazyLPat (L _ (WildPat {})) = False
542 looksLazyLPat _ = True
543
544 isIrrefutableHsPat :: OutputableBndr id => LPat id -> Bool
545 -- (isIrrefutableHsPat p) is true if matching against p cannot fail,
546 -- in the sense of falling through to the next pattern.
547 -- (NB: this is not quite the same as the (silly) defn
548 -- in 3.17.2 of the Haskell 98 report.)
549 --
550 -- WARNING: isIrrefutableHsPat returns False if it's in doubt.
551 -- Specifically on a ConPatIn, which is what it sees for a
552 -- (LPat Name) in the renamer, it doesn't know the size of the
553 -- constructor family, so it returns False. Result: only
554 -- tuple patterns are considered irrefuable at the renamer stage.
555 --
556 -- But if it returns True, the pattern is definitely irrefutable
557 isIrrefutableHsPat pat
558 = go pat
559 where
560 go (L _ pat) = go1 pat
561
562 go1 (WildPat {}) = True
563 go1 (VarPat {}) = True
564 go1 (LazyPat {}) = True
565 go1 (BangPat pat) = go pat
566 go1 (CoPat _ pat _) = go1 pat
567 go1 (ParPat pat) = go pat
568 go1 (AsPat _ pat) = go pat
569 go1 (ViewPat _ pat _) = go pat
570 go1 (SigPatIn pat _) = go pat
571 go1 (SigPatOut pat _) = go pat
572 go1 (TuplePat pats _ _) = all go pats
573 go1 (ListPat {}) = False
574 go1 (PArrPat {}) = False -- ?
575
576 go1 (ConPatIn {}) = False -- Conservative
577 go1 (ConPatOut{ pat_con = L _ (RealDataCon con), pat_args = details })
578 = isJust (tyConSingleDataCon_maybe (dataConTyCon con))
579 -- NB: tyConSingleDataCon_maybe, *not* isProductTyCon, because
580 -- the latter is false of existentials. See Trac #4439
581 && all go (hsConPatArgs details)
582 go1 (ConPatOut{ pat_con = L _ (PatSynCon _pat) })
583 = False -- Conservative
584
585 go1 (LitPat {}) = False
586 go1 (NPat {}) = False
587 go1 (NPlusKPat {}) = False
588
589 -- Both should be gotten rid of by renamer before
590 -- isIrrefutablePat is called
591 go1 (SplicePat {}) = urk pat
592
593 urk pat = pprPanic "isIrrefutableHsPat:" (ppr pat)
594
595 hsPatNeedsParens :: Pat a -> Bool
596 hsPatNeedsParens (NPlusKPat {}) = True
597 hsPatNeedsParens (SplicePat {}) = False
598 hsPatNeedsParens (ConPatIn _ ds) = conPatNeedsParens ds
599 hsPatNeedsParens p@(ConPatOut {}) = conPatNeedsParens (pat_args p)
600 hsPatNeedsParens (SigPatIn {}) = True
601 hsPatNeedsParens (SigPatOut {}) = True
602 hsPatNeedsParens (ViewPat {}) = True
603 hsPatNeedsParens (CoPat _ p _) = hsPatNeedsParens p
604 hsPatNeedsParens (WildPat {}) = False
605 hsPatNeedsParens (VarPat {}) = False
606 hsPatNeedsParens (LazyPat {}) = False
607 hsPatNeedsParens (BangPat {}) = False
608 hsPatNeedsParens (ParPat {}) = False
609 hsPatNeedsParens (AsPat {}) = False
610 hsPatNeedsParens (TuplePat {}) = False
611 hsPatNeedsParens (ListPat {}) = False
612 hsPatNeedsParens (PArrPat {}) = False
613 hsPatNeedsParens (LitPat {}) = False
614 hsPatNeedsParens (NPat {}) = False
615
616 conPatNeedsParens :: HsConDetails a b -> Bool
617 conPatNeedsParens (PrefixCon args) = not (null args)
618 conPatNeedsParens (InfixCon {}) = True
619 conPatNeedsParens (RecCon {}) = True
620
621 {-
622 % Collect all EvVars from all constructor patterns
623 -}
624
625 -- May need to add more cases
626 collectEvVarsPats :: [Pat id] -> Bag EvVar
627 collectEvVarsPats = unionManyBags . map collectEvVarsPat
628
629 collectEvVarsLPat :: LPat id -> Bag EvVar
630 collectEvVarsLPat (L _ pat) = collectEvVarsPat pat
631
632 collectEvVarsPat :: Pat id -> Bag EvVar
633 collectEvVarsPat pat =
634 case pat of
635 LazyPat p -> collectEvVarsLPat p
636 AsPat _ p -> collectEvVarsLPat p
637 ParPat p -> collectEvVarsLPat p
638 BangPat p -> collectEvVarsLPat p
639 ListPat ps _ _ -> unionManyBags $ map collectEvVarsLPat ps
640 TuplePat ps _ _ -> unionManyBags $ map collectEvVarsLPat ps
641 PArrPat ps _ -> unionManyBags $ map collectEvVarsLPat ps
642 ConPatOut {pat_dicts = dicts, pat_args = args}
643 -> unionBags (listToBag dicts)
644 $ unionManyBags
645 $ map collectEvVarsLPat
646 $ hsConPatArgs args
647 SigPatOut p _ -> collectEvVarsLPat p
648 CoPat _ p _ -> collectEvVarsPat p
649 ConPatIn _ _ -> panic "foldMapPatBag: ConPatIn"
650 SigPatIn _ _ -> panic "foldMapPatBag: SigPatIn"
651 _other_pat -> emptyBag