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