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 -- Used for all overloaded literals,
126 -- including overloaded strings with -XOverloadedStrings
127 (HsOverLit id) -- ALWAYS positive
128 (Maybe (SyntaxExpr id)) -- Just (Name of 'negate') for negative
129 -- patterns, Nothing otherwise
130 (SyntaxExpr id) -- Equality checker, of type t->t->Bool
132 | NPlusKPat (Located id) -- n+k pattern
133 (HsOverLit id) -- It'll always be an HsIntegral
134 (SyntaxExpr id) -- (>=) function, of type t->t->Bool
135 (SyntaxExpr id) -- Name of '-' (see RnEnv.lookupSyntaxName)
137 ------------ Generics ---------------
138 | TypePat (LHsType id) -- Type pattern for generic definitions
139 -- e.g f{| a+b |} = ...
140 -- These show up only in class declarations,
141 -- and should be a top-level pattern
143 ------------ Pattern type signatures ---------------
144 | SigPatIn (LPat id) -- Pattern with a type signature
147 | SigPatOut (LPat id) -- Pattern with a type signature
150 ------------ Pattern coercions (translation only) ---------------
151 | CoPat HsWrapper -- If co :: t1 ~ t2, p :: t2,
152 -- then (CoPat co p) :: t1
153 (Pat id) -- Why not LPat? Ans: existing locn will do
154 Type -- Type of whole pattern, t1
155 -- During desugaring a (CoPat co pat) turns into a cast with 'co' on
156 -- the scrutinee, followed by a match on 'pat'
157 deriving (Data, Typeable)
160 HsConDetails is use for patterns/expressions *and* for data type declarations
163 data HsConDetails arg rec
164 = PrefixCon [arg] -- C p1 p2 p3
165 | RecCon rec -- C { x = p1, y = p2 }
166 | InfixCon arg arg -- p1 `C` p2
167 deriving (Data, Typeable)
169 type HsConPatDetails id = HsConDetails (LPat id) (HsRecFields id (LPat id))
171 hsConPatArgs :: HsConPatDetails id -> [LPat id]
172 hsConPatArgs (PrefixCon ps) = ps
173 hsConPatArgs (RecCon fs) = map hsRecFieldArg (rec_flds fs)
174 hsConPatArgs (InfixCon p1 p2) = [p1,p2]
177 However HsRecFields is used only for patterns and expressions
178 (not data type declarations)
181 data HsRecFields id arg -- A bunch of record fields
182 -- { x = 3, y = True }
183 -- Used for both expressions and patterns
184 = HsRecFields { rec_flds :: [HsRecField id arg],
185 rec_dotdot :: Maybe Int } -- Note [DotDot fields]
186 deriving (Data, Typeable)
188 -- Note [DotDot fields]
189 -- ~~~~~~~~~~~~~~~~~~~~
190 -- The rec_dotdot field means this:
191 -- Nothing => the normal case
192 -- Just n => the group uses ".." notation,
194 -- In the latter case:
196 -- *before* renamer: rec_flds are exactly the n user-written fields
198 -- *after* renamer: rec_flds includes *all* fields, with
199 -- the first 'n' being the user-written ones
200 -- and the remainder being 'filled in' implicitly
202 data HsRecField id arg = HsRecField {
203 hsRecFieldId :: Located id,
204 hsRecFieldArg :: arg, -- Filled in by renamer
205 hsRecPun :: Bool -- Note [Punning]
206 } deriving (Data, Typeable)
210 -- If you write T { x, y = v+1 }, the HsRecFields will be
211 -- HsRecField x x True ...
212 -- HsRecField y (v+1) False ...
213 -- That is, for "punned" field x is expanded (in the renamer)
214 -- to x=x; but with a punning flag so we can detect it later
215 -- (e.g. when pretty printing)
217 -- If the original field was qualified, we un-qualify it, thus
218 -- T { A.x } means T { A.x = x }
220 hsRecFields :: HsRecFields id arg -> [id]
221 hsRecFields rbinds = map (unLoc . hsRecFieldId) (rec_flds rbinds)
224 %************************************************************************
228 %************************************************************************
231 instance (OutputableBndr name) => Outputable (Pat name) where
234 pprPatBndr :: OutputableBndr name => name -> SDoc
235 pprPatBndr var -- Print with type info if -dppr-debug is on
236 = getPprStyle $ \ sty ->
237 if debugStyle sty then
238 parens (pprBndr LambdaBind var) -- Could pass the site to pprPat
239 -- but is it worth it?
243 pprParendLPat :: (OutputableBndr name) => LPat name -> SDoc
244 pprParendLPat (L _ p) = pprParendPat p
246 pprParendPat :: (OutputableBndr name) => Pat name -> SDoc
247 pprParendPat p | patNeedsParens p = parens (pprPat p)
248 | otherwise = pprPat p
250 patNeedsParens :: Pat name -> Bool
251 patNeedsParens (ConPatIn _ d) = not (null (hsConPatArgs d))
252 patNeedsParens (ConPatOut { pat_args = d }) = not (null (hsConPatArgs d))
253 patNeedsParens (SigPatIn {}) = True
254 patNeedsParens (SigPatOut {}) = True
255 patNeedsParens (ViewPat {}) = True
256 patNeedsParens (CoPat {}) = True
257 patNeedsParens _ = False
259 pprPat :: (OutputableBndr name) => Pat name -> SDoc
260 pprPat (VarPat var) = pprPatBndr var
261 pprPat (WildPat _) = char '_'
262 pprPat (LazyPat pat) = char '~' <> pprParendLPat pat
263 pprPat (BangPat pat) = char '!' <> pprParendLPat pat
264 pprPat (AsPat name pat) = hcat [ppr name, char '@', pprParendLPat pat]
265 pprPat (ViewPat expr pat _) = hcat [pprLExpr expr, text " -> ", ppr pat]
266 pprPat (ParPat pat) = parens (ppr pat)
267 pprPat (ListPat pats _) = brackets (interpp'SP pats)
268 pprPat (PArrPat pats _) = pabrackets (interpp'SP pats)
269 pprPat (TuplePat pats bx _) = tupleParens bx (interpp'SP pats)
271 pprPat (ConPatIn con details) = pprUserCon con details
272 pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts,
273 pat_binds = binds, pat_args = details })
274 = getPprStyle $ \ sty -> -- Tiresome; in TcBinds.tcRhs we print out a
275 if debugStyle sty then -- typechecked Pat in an error message,
276 -- and we want to make sure it prints nicely
277 ppr con <+> sep [ hsep (map pprPatBndr tvs) <+> hsep (map pprPatBndr dicts),
278 ppr binds, pprConArgs details]
279 else pprUserCon con details
281 pprPat (LitPat s) = ppr s
282 pprPat (NPat l Nothing _) = ppr l
283 pprPat (NPat l (Just _) _) = char '-' <> ppr l
284 pprPat (NPlusKPat n k _ _) = hcat [ppr n, char '+', ppr k]
285 pprPat (QuasiQuotePat qq) = ppr qq
286 pprPat (TypePat ty) = ptext (sLit "{|") <> ppr ty <> ptext (sLit "|}")
287 pprPat (CoPat co pat _) = pprHsWrapper (ppr pat) co
288 pprPat (SigPatIn pat ty) = ppr pat <+> dcolon <+> ppr ty
289 pprPat (SigPatOut pat ty) = ppr pat <+> dcolon <+> ppr ty
291 pprUserCon :: (Outputable con, OutputableBndr id) => con -> HsConPatDetails id -> SDoc
292 pprUserCon c (InfixCon p1 p2) = ppr p1 <+> ppr c <+> ppr p2
293 pprUserCon c details = ppr c <+> pprConArgs details
295 pprConArgs :: OutputableBndr id => HsConPatDetails id -> SDoc
296 pprConArgs (PrefixCon pats) = sep (map pprParendLPat pats)
297 pprConArgs (InfixCon p1 p2) = sep [pprParendLPat p1, pprParendLPat p2]
298 pprConArgs (RecCon rpats) = ppr rpats
300 instance (OutputableBndr id, Outputable arg)
301 => Outputable (HsRecFields id arg) where
302 ppr (HsRecFields { rec_flds = flds, rec_dotdot = Nothing })
303 = braces (fsep (punctuate comma (map ppr flds)))
304 ppr (HsRecFields { rec_flds = flds, rec_dotdot = Just n })
305 = braces (fsep (punctuate comma (map ppr (take n flds) ++ [dotdot])))
307 dotdot = ptext (sLit "..") <+> ifPprDebug (ppr (drop n flds))
309 instance (OutputableBndr id, Outputable arg)
310 => Outputable (HsRecField id arg) where
311 ppr (HsRecField { hsRecFieldId = f, hsRecFieldArg = arg,
313 = ppr f <+> (ppUnless pun $ equals <+> ppr arg)
315 -- add parallel array brackets around a document
317 pabrackets :: SDoc -> SDoc
318 pabrackets p = ptext (sLit "[:") <> p <> ptext (sLit ":]")
322 %************************************************************************
326 %************************************************************************
329 mkPrefixConPat :: DataCon -> [OutPat id] -> Type -> OutPat id
330 -- Make a vanilla Prefix constructor pattern
331 mkPrefixConPat dc pats ty
332 = noLoc $ ConPatOut { pat_con = noLoc dc, pat_tvs = [], pat_dicts = [],
333 pat_binds = emptyTcEvBinds, pat_args = PrefixCon pats,
336 mkNilPat :: Type -> OutPat id
337 mkNilPat ty = mkPrefixConPat nilDataCon [] ty
339 mkCharLitPat :: Char -> OutPat id
340 mkCharLitPat c = mkPrefixConPat charDataCon [noLoc $ LitPat (HsCharPrim c)] charTy
344 %************************************************************************
346 %* Predicates for checking things about pattern-lists in EquationInfo *
348 %************************************************************************
350 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
352 Unlike in the Wadler chapter, where patterns are either ``variables''
353 or ``constructors,'' here we distinguish between:
356 Patterns that cannot fail to match: variables, wildcards, and lazy
359 These are the irrefutable patterns; the two other categories
360 are refutable patterns.
363 A non-literal constructor pattern (see next category).
365 \item[literal patterns:]
366 At least the numeric ones may be overloaded.
369 A pattern is in {\em exactly one} of the above three categories; `as'
370 patterns are treated specially, of course.
372 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
374 isBangLPat :: LPat id -> Bool
375 isBangLPat (L _ (BangPat {})) = True
376 isBangLPat (L _ (ParPat p)) = isBangLPat p
379 isBangHsBind :: HsBind id -> Bool
380 -- A pattern binding with an outermost bang
381 -- Defined in this module because HsPat is above HsBinds in the import graph
382 isBangHsBind (PatBind { pat_lhs = p }) = isBangLPat p
383 isBangHsBind _ = False
385 isLiftedPatBind :: HsBind id -> Bool
386 -- A pattern binding with a compound pattern, not just a variable
388 -- (# a, b #) no, even if a::Int#
389 -- x no, even if x::Int#
390 -- We want to warn about a missing bang-pattern on the yes's
391 isLiftedPatBind (PatBind { pat_lhs = p }) = isLiftedLPat p
392 isLiftedPatBind _ = False
394 isLiftedLPat :: LPat id -> Bool
395 isLiftedLPat (L _ (ParPat p)) = isLiftedLPat p
396 isLiftedLPat (L _ (BangPat p)) = isLiftedLPat p
397 isLiftedLPat (L _ (AsPat _ p)) = isLiftedLPat p
398 isLiftedLPat (L _ (TuplePat _ Unboxed _)) = False
399 isLiftedLPat (L _ (VarPat {})) = False
400 isLiftedLPat (L _ (WildPat {})) = False
401 isLiftedLPat _ = True
403 isIrrefutableHsPat :: OutputableBndr id => LPat id -> Bool
404 -- (isIrrefutableHsPat p) is true if matching against p cannot fail,
405 -- in the sense of falling through to the next pattern.
406 -- (NB: this is not quite the same as the (silly) defn
407 -- in 3.17.2 of the Haskell 98 report.)
409 -- isIrrefutableHsPat returns False if it's in doubt; specifically
410 -- on a ConPatIn it doesn't know the size of the constructor family
411 -- But if it returns True, the pattern is definitely irrefutable
412 isIrrefutableHsPat pat
415 go (L _ pat) = go1 pat
417 go1 (WildPat {}) = True
418 go1 (VarPat {}) = True
419 go1 (LazyPat {}) = True
420 go1 (BangPat pat) = go pat
421 go1 (CoPat _ pat _) = go1 pat
422 go1 (ParPat pat) = go pat
423 go1 (AsPat _ pat) = go pat
424 go1 (ViewPat _ pat _) = go pat
425 go1 (SigPatIn pat _) = go pat
426 go1 (SigPatOut pat _) = go pat
427 go1 (TuplePat pats _ _) = all go pats
428 go1 (ListPat {}) = False
429 go1 (PArrPat {}) = False -- ?
431 go1 (ConPatIn {}) = False -- Conservative
432 go1 (ConPatOut{ pat_con = L _ con, pat_args = details })
433 = isJust (tyConSingleDataCon_maybe (dataConTyCon con))
434 -- NB: tyConSingleDataCon_maybe, *not* isProductTyCon, because
435 -- the latter is false of existentials. See Trac #4439
436 && all go (hsConPatArgs details)
438 go1 (LitPat {}) = False
439 go1 (NPat {}) = False
440 go1 (NPlusKPat {}) = False
442 go1 (QuasiQuotePat {}) = urk pat -- Gotten rid of by renamer, before
443 -- isIrrefutablePat is called
444 go1 (TypePat {}) = urk pat
446 urk pat = pprPanic "isIrrefutableHsPat:" (ppr pat)
448 hsPatNeedsParens :: Pat a -> Bool
449 hsPatNeedsParens (WildPat {}) = False
450 hsPatNeedsParens (VarPat {}) = False
451 hsPatNeedsParens (LazyPat {}) = False
452 hsPatNeedsParens (BangPat {}) = False
453 hsPatNeedsParens (CoPat {}) = True
454 hsPatNeedsParens (ParPat {}) = False
455 hsPatNeedsParens (AsPat {}) = False
456 hsPatNeedsParens (ViewPat {}) = True
457 hsPatNeedsParens (SigPatIn {}) = True
458 hsPatNeedsParens (SigPatOut {}) = True
459 hsPatNeedsParens (TuplePat {}) = False
460 hsPatNeedsParens (ListPat {}) = False
461 hsPatNeedsParens (PArrPat {}) = False
462 hsPatNeedsParens (ConPatIn _ ds) = conPatNeedsParens ds
463 hsPatNeedsParens (ConPatOut {}) = True
464 hsPatNeedsParens (LitPat {}) = False
465 hsPatNeedsParens (NPat {}) = False
466 hsPatNeedsParens (NPlusKPat {}) = True
467 hsPatNeedsParens (QuasiQuotePat {}) = True
468 hsPatNeedsParens (TypePat {}) = False
470 conPatNeedsParens :: HsConDetails a b -> Bool
471 conPatNeedsParens (PrefixCon args) = not (null args)
472 conPatNeedsParens (InfixCon {}) = False
473 conPatNeedsParens (RecCon {}) = False