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