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