2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5 \section[PatSyntax]{Abstract Haskell syntax---patterns}
8 {-# OPTIONS -fno-warn-incomplete-patterns #-}
9 -- The above warning supression flag is a temporary kludge.
10 -- While working on this module you are encouraged to remove it and fix
11 -- any warnings in the module. See
12 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 {-# LANGUAGE DeriveDataTypeable #-}
17 Pat(..), InPat, OutPat, LPat,
20 HsConPatDetails, hsConPatArgs,
21 HsRecFields(..), HsRecField(..), hsRecFields,
23 mkPrefixConPat, mkCharLitPat, mkNilPat,
25 isBangHsBind, isLiftedPatBind,
26 isBangLPat, hsPatNeedsParens,
32 import {-# SOURCE #-} HsExpr (SyntaxExpr, LHsExpr, pprLExpr)
40 import PprCore ( {- instance OutputableBndr TyVar -} )
50 import Data.Data hiding (TyCon)
56 type InPat id = LPat id -- No 'Out' constructors
57 type OutPat id = LPat id -- No 'In' constructors
59 type LPat id = Located (Pat id)
62 = ------------ Simple patterns ---------------
63 WildPat PostTcType -- Wild card
64 -- The sole reason for a type on a WildPat is to
65 -- support hsPatType :: Pat Id -> Type
67 | VarPat id -- Variable
68 | LazyPat (LPat id) -- Lazy pattern
69 | AsPat (Located id) (LPat id) -- As pattern
70 | ParPat (LPat id) -- Parenthesised pattern
71 | BangPat (LPat id) -- Bang pattern
73 ------------ Lists, tuples, arrays ---------------
74 | ListPat [LPat id] -- Syntactic list
75 PostTcType -- The type of the elements
77 | TuplePat [LPat id] -- Tuple
78 Boxity -- UnitPat is TuplePat []
80 -- You might think that the PostTcType was redundant, but it's essential
83 -- f :: (T a, a) -> Int
85 -- When desugaring, we must generate
86 -- f = /\a. \v::a. case v of (t::T a, w::a) ->
87 -- case t of (T1 (x::Int)) ->
88 -- Note the (w::a), NOT (w::Int), because we have not yet
89 -- refined 'a' to Int. So we must know that the second component
90 -- of the tuple is of type 'a' not Int. See selectMatchVar
92 | PArrPat [LPat id] -- Syntactic parallel array
93 PostTcType -- The type of the elements
95 ------------ Constructor patterns ---------------
96 | ConPatIn (Located id)
100 pat_con :: Located DataCon,
101 pat_tvs :: [TyVar], -- Existentially bound type variables (tyvars only)
102 pat_dicts :: [EvVar], -- Ditto *coercion variables* and *dictionaries*
103 -- One reason for putting coercion variable here, I think,
104 -- is to ensure their kinds are zonked
105 pat_binds :: TcEvBinds, -- Bindings involving those dictionaries
106 pat_args :: HsConPatDetails id,
107 pat_ty :: Type -- The type of the pattern
110 ------------ View patterns ---------------
111 | ViewPat (LHsExpr id)
113 PostTcType -- The overall type of the pattern
114 -- (= the argument type of the view function)
117 ------------ Quasiquoted patterns ---------------
118 -- See Note [Quasi-quote overview] in TcSplice
119 | QuasiQuotePat (HsQuasiQuote id)
121 ------------ Literal and n+k patterns ---------------
122 | LitPat HsLit -- Used for *non-overloaded* literal patterns:
123 -- Int#, Char#, Int, Char, String, etc.
125 | NPat (HsOverLit id) -- ALWAYS positive
126 (Maybe (SyntaxExpr id)) -- Just (Name of 'negate') for negative
127 -- patterns, Nothing otherwise
128 (SyntaxExpr id) -- Equality checker, of type t->t->Bool
130 | NPlusKPat (Located id) -- n+k pattern
131 (HsOverLit id) -- It'll always be an HsIntegral
132 (SyntaxExpr id) -- (>=) function, of type t->t->Bool
133 (SyntaxExpr id) -- Name of '-' (see RnEnv.lookupSyntaxName)
135 ------------ Pattern type signatures ---------------
136 | SigPatIn (LPat id) -- Pattern with a type signature
139 | SigPatOut (LPat id) -- Pattern with a type signature
142 ------------ Pattern coercions (translation only) ---------------
143 | CoPat HsWrapper -- If co :: t1 ~ t2, p :: t2,
144 -- then (CoPat co p) :: t1
145 (Pat id) -- Why not LPat? Ans: existing locn will do
146 Type -- Type of whole pattern, t1
147 -- During desugaring a (CoPat co pat) turns into a cast with 'co' on
148 -- the scrutinee, followed by a match on 'pat'
149 deriving (Data, Typeable)
152 HsConDetails is use for patterns/expressions *and* for data type declarations
155 data HsConDetails arg rec
156 = PrefixCon [arg] -- C p1 p2 p3
157 | RecCon rec -- C { x = p1, y = p2 }
158 | InfixCon arg arg -- p1 `C` p2
159 deriving (Data, Typeable)
161 type HsConPatDetails id = HsConDetails (LPat id) (HsRecFields id (LPat id))
163 hsConPatArgs :: HsConPatDetails id -> [LPat id]
164 hsConPatArgs (PrefixCon ps) = ps
165 hsConPatArgs (RecCon fs) = map hsRecFieldArg (rec_flds fs)
166 hsConPatArgs (InfixCon p1 p2) = [p1,p2]
169 However HsRecFields is used only for patterns and expressions
170 (not data type declarations)
173 data HsRecFields id arg -- A bunch of record fields
174 -- { x = 3, y = True }
175 -- Used for both expressions and patterns
176 = HsRecFields { rec_flds :: [HsRecField id arg],
177 rec_dotdot :: Maybe Int } -- Note [DotDot fields]
178 deriving (Data, Typeable)
180 -- Note [DotDot fields]
181 -- ~~~~~~~~~~~~~~~~~~~~
182 -- The rec_dotdot field means this:
183 -- Nothing => the normal case
184 -- Just n => the group uses ".." notation,
186 -- In the latter case:
188 -- *before* renamer: rec_flds are exactly the n user-written fields
190 -- *after* renamer: rec_flds includes *all* fields, with
191 -- the first 'n' being the user-written ones
192 -- and the remainder being 'filled in' implicitly
194 data HsRecField id arg = HsRecField {
195 hsRecFieldId :: Located id,
196 hsRecFieldArg :: arg, -- Filled in by renamer
197 hsRecPun :: Bool -- Note [Punning]
198 } deriving (Data, Typeable)
202 -- If you write T { x, y = v+1 }, the HsRecFields will be
203 -- HsRecField x x True ...
204 -- HsRecField y (v+1) False ...
205 -- That is, for "punned" field x is expanded (in the renamer)
206 -- to x=x; but with a punning flag so we can detect it later
207 -- (e.g. when pretty printing)
209 -- If the original field was qualified, we un-qualify it, thus
210 -- T { A.x } means T { A.x = x }
212 hsRecFields :: HsRecFields id arg -> [id]
213 hsRecFields rbinds = map (unLoc . hsRecFieldId) (rec_flds rbinds)
216 %************************************************************************
220 %************************************************************************
223 instance (OutputableBndr name) => Outputable (Pat name) where
226 pprPatBndr :: OutputableBndr name => name -> SDoc
227 pprPatBndr var -- Print with type info if -dppr-debug is on
228 = getPprStyle $ \ sty ->
229 if debugStyle sty then
230 parens (pprBndr LambdaBind var) -- Could pass the site to pprPat
231 -- but is it worth it?
235 pprParendLPat :: (OutputableBndr name) => LPat name -> SDoc
236 pprParendLPat (L _ p) = pprParendPat p
238 pprParendPat :: (OutputableBndr name) => Pat name -> SDoc
239 pprParendPat p | patNeedsParens p = parens (pprPat p)
240 | otherwise = pprPat p
242 patNeedsParens :: Pat name -> Bool
243 patNeedsParens (ConPatIn _ d) = not (null (hsConPatArgs d))
244 patNeedsParens (ConPatOut { pat_args = d }) = not (null (hsConPatArgs d))
245 patNeedsParens (SigPatIn {}) = True
246 patNeedsParens (SigPatOut {}) = True
247 patNeedsParens (ViewPat {}) = True
248 patNeedsParens (CoPat {}) = True
249 patNeedsParens _ = False
251 pprPat :: (OutputableBndr name) => Pat name -> SDoc
252 pprPat (VarPat var) = pprPatBndr var
253 pprPat (WildPat _) = char '_'
254 pprPat (LazyPat pat) = char '~' <> pprParendLPat pat
255 pprPat (BangPat pat) = char '!' <> pprParendLPat pat
256 pprPat (AsPat name pat) = hcat [ppr name, char '@', pprParendLPat pat]
257 pprPat (ViewPat expr pat _) = hcat [pprLExpr expr, text " -> ", ppr pat]
258 pprPat (ParPat pat) = parens (ppr pat)
259 pprPat (ListPat pats _) = brackets (interpp'SP pats)
260 pprPat (PArrPat pats _) = pabrackets (interpp'SP pats)
261 pprPat (TuplePat pats bx _) = tupleParens bx (interpp'SP pats)
263 pprPat (ConPatIn con details) = pprUserCon con details
264 pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts,
265 pat_binds = binds, pat_args = details })
266 = getPprStyle $ \ sty -> -- Tiresome; in TcBinds.tcRhs we print out a
267 if debugStyle sty then -- typechecked Pat in an error message,
268 -- and we want to make sure it prints nicely
269 ppr con <+> sep [ hsep (map pprPatBndr tvs) <+> hsep (map pprPatBndr dicts),
270 ppr binds, pprConArgs details]
271 else pprUserCon con details
273 pprPat (LitPat s) = ppr s
274 pprPat (NPat l Nothing _) = ppr l
275 pprPat (NPat l (Just _) _) = char '-' <> ppr l
276 pprPat (NPlusKPat n k _ _) = hcat [ppr n, char '+', ppr k]
277 pprPat (QuasiQuotePat qq) = ppr qq
278 pprPat (CoPat co pat _) = pprHsWrapper (ppr pat) co
279 pprPat (SigPatIn pat ty) = ppr pat <+> dcolon <+> ppr ty
280 pprPat (SigPatOut pat ty) = ppr pat <+> dcolon <+> ppr ty
282 pprUserCon :: (Outputable con, OutputableBndr id) => con -> HsConPatDetails id -> SDoc
283 pprUserCon c (InfixCon p1 p2) = ppr p1 <+> ppr c <+> ppr p2
284 pprUserCon c details = ppr c <+> pprConArgs details
286 pprConArgs :: OutputableBndr id => HsConPatDetails id -> SDoc
287 pprConArgs (PrefixCon pats) = sep (map pprParendLPat pats)
288 pprConArgs (InfixCon p1 p2) = sep [pprParendLPat p1, pprParendLPat p2]
289 pprConArgs (RecCon rpats) = ppr rpats
291 instance (OutputableBndr id, Outputable arg)
292 => Outputable (HsRecFields id arg) where
293 ppr (HsRecFields { rec_flds = flds, rec_dotdot = Nothing })
294 = braces (fsep (punctuate comma (map ppr flds)))
295 ppr (HsRecFields { rec_flds = flds, rec_dotdot = Just n })
296 = braces (fsep (punctuate comma (map ppr (take n flds) ++ [dotdot])))
298 dotdot = ptext (sLit "..") <+> ifPprDebug (ppr (drop n flds))
300 instance (OutputableBndr id, Outputable arg)
301 => Outputable (HsRecField id arg) where
302 ppr (HsRecField { hsRecFieldId = f, hsRecFieldArg = arg,
304 = ppr f <+> (ppUnless pun $ equals <+> ppr arg)
306 -- add parallel array brackets around a document
308 pabrackets :: SDoc -> SDoc
309 pabrackets p = ptext (sLit "[:") <> p <> ptext (sLit ":]")
313 %************************************************************************
317 %************************************************************************
320 mkPrefixConPat :: DataCon -> [OutPat id] -> Type -> OutPat id
321 -- Make a vanilla Prefix constructor pattern
322 mkPrefixConPat dc pats ty
323 = noLoc $ ConPatOut { pat_con = noLoc dc, pat_tvs = [], pat_dicts = [],
324 pat_binds = emptyTcEvBinds, pat_args = PrefixCon pats,
327 mkNilPat :: Type -> OutPat id
328 mkNilPat ty = mkPrefixConPat nilDataCon [] ty
330 mkCharLitPat :: Char -> OutPat id
331 mkCharLitPat c = mkPrefixConPat charDataCon [noLoc $ LitPat (HsCharPrim c)] charTy
335 %************************************************************************
337 %* Predicates for checking things about pattern-lists in EquationInfo *
339 %************************************************************************
341 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
343 Unlike in the Wadler chapter, where patterns are either ``variables''
344 or ``constructors,'' here we distinguish between:
347 Patterns that cannot fail to match: variables, wildcards, and lazy
350 These are the irrefutable patterns; the two other categories
351 are refutable patterns.
354 A non-literal constructor pattern (see next category).
356 \item[literal patterns:]
357 At least the numeric ones may be overloaded.
360 A pattern is in {\em exactly one} of the above three categories; `as'
361 patterns are treated specially, of course.
363 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
365 isBangLPat :: LPat id -> Bool
366 isBangLPat (L _ (BangPat {})) = True
367 isBangLPat (L _ (ParPat p)) = isBangLPat p
370 isBangHsBind :: HsBind id -> Bool
371 -- A pattern binding with an outermost bang
372 -- Defined in this module because HsPat is above HsBinds in the import graph
373 isBangHsBind (PatBind { pat_lhs = p }) = isBangLPat p
374 isBangHsBind _ = False
376 isLiftedPatBind :: HsBind id -> Bool
377 -- A pattern binding with a compound pattern, not just a variable
379 -- (# a, b #) no, even if a::Int#
380 -- x no, even if x::Int#
381 -- We want to warn about a missing bang-pattern on the yes's
382 isLiftedPatBind (PatBind { pat_lhs = p }) = isLiftedLPat p
383 isLiftedPatBind _ = False
385 isLiftedLPat :: LPat id -> Bool
386 isLiftedLPat (L _ (ParPat p)) = isLiftedLPat p
387 isLiftedLPat (L _ (BangPat p)) = isLiftedLPat p
388 isLiftedLPat (L _ (AsPat _ p)) = isLiftedLPat p
389 isLiftedLPat (L _ (TuplePat _ Unboxed _)) = False
390 isLiftedLPat (L _ (VarPat {})) = False
391 isLiftedLPat (L _ (WildPat {})) = False
392 isLiftedLPat _ = True
394 isIrrefutableHsPat :: OutputableBndr id => LPat id -> Bool
395 -- (isIrrefutableHsPat p) is true if matching against p cannot fail,
396 -- in the sense of falling through to the next pattern.
397 -- (NB: this is not quite the same as the (silly) defn
398 -- in 3.17.2 of the Haskell 98 report.)
400 -- isIrrefutableHsPat returns False if it's in doubt; specifically
401 -- on a ConPatIn it doesn't know the size of the constructor family
402 -- But if it returns True, the pattern is definitely irrefutable
403 isIrrefutableHsPat pat
406 go (L _ pat) = go1 pat
408 go1 (WildPat {}) = True
409 go1 (VarPat {}) = True
410 go1 (LazyPat {}) = True
411 go1 (BangPat pat) = go pat
412 go1 (CoPat _ pat _) = go1 pat
413 go1 (ParPat pat) = go pat
414 go1 (AsPat _ pat) = go pat
415 go1 (ViewPat _ pat _) = go pat
416 go1 (SigPatIn pat _) = go pat
417 go1 (SigPatOut pat _) = go pat
418 go1 (TuplePat pats _ _) = all go pats
419 go1 (ListPat {}) = False
420 go1 (PArrPat {}) = False -- ?
422 go1 (ConPatIn {}) = False -- Conservative
423 go1 (ConPatOut{ pat_con = L _ con, pat_args = details })
424 = isJust (tyConSingleDataCon_maybe (dataConTyCon con))
425 -- NB: tyConSingleDataCon_maybe, *not* isProductTyCon, because
426 -- the latter is false of existentials. See Trac #4439
427 && all go (hsConPatArgs details)
429 go1 (LitPat {}) = False
430 go1 (NPat {}) = False
431 go1 (NPlusKPat {}) = False
433 go1 (QuasiQuotePat {}) = urk pat -- Gotten rid of by renamer, before
434 -- isIrrefutablePat is called
436 urk pat = pprPanic "isIrrefutableHsPat:" (ppr pat)
438 hsPatNeedsParens :: Pat a -> Bool
439 hsPatNeedsParens (WildPat {}) = False
440 hsPatNeedsParens (VarPat {}) = False
441 hsPatNeedsParens (LazyPat {}) = False
442 hsPatNeedsParens (BangPat {}) = False
443 hsPatNeedsParens (CoPat {}) = True
444 hsPatNeedsParens (ParPat {}) = False
445 hsPatNeedsParens (AsPat {}) = False
446 hsPatNeedsParens (ViewPat {}) = True
447 hsPatNeedsParens (SigPatIn {}) = True
448 hsPatNeedsParens (SigPatOut {}) = True
449 hsPatNeedsParens (TuplePat {}) = False
450 hsPatNeedsParens (ListPat {}) = False
451 hsPatNeedsParens (PArrPat {}) = False
452 hsPatNeedsParens (ConPatIn _ ds) = conPatNeedsParens ds
453 hsPatNeedsParens (ConPatOut {}) = True
454 hsPatNeedsParens (LitPat {}) = False
455 hsPatNeedsParens (NPat {}) = False
456 hsPatNeedsParens (NPlusKPat {}) = True
457 hsPatNeedsParens (QuasiQuotePat {}) = True
459 conPatNeedsParens :: HsConDetails a b -> Bool
460 conPatNeedsParens (PrefixCon args) = not (null args)
461 conPatNeedsParens (InfixCon {}) = False
462 conPatNeedsParens (RecCon {}) = False