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