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, isBangLPat, hsPatNeedsParens,
31 import {-# SOURCE #-} HsExpr (SyntaxExpr, LHsExpr, pprLExpr)
39 import PprCore ( {- instance OutputableBndr TyVar -} )
49 import Data.Data hiding (TyCon)
55 type InPat id = LPat id -- No 'Out' constructors
56 type OutPat id = LPat id -- No 'In' constructors
58 type LPat id = Located (Pat id)
61 = ------------ Simple patterns ---------------
62 WildPat PostTcType -- Wild card
63 -- The sole reason for a type on a WildPat is to
64 -- support hsPatType :: Pat Id -> Type
66 | VarPat id -- Variable
67 | VarPatOut id TcEvBinds -- Used only for overloaded Ids; the
68 -- bindings give its overloaded instances
69 | LazyPat (LPat id) -- Lazy pattern
70 | AsPat (Located id) (LPat id) -- As pattern
71 | ParPat (LPat id) -- Parenthesised pattern
72 | BangPat (LPat id) -- Bang pattern
74 ------------ Lists, tuples, arrays ---------------
75 | ListPat [LPat id] -- Syntactic list
76 PostTcType -- The type of the elements
78 | TuplePat [LPat id] -- Tuple
79 Boxity -- UnitPat is TuplePat []
81 -- You might think that the PostTcType was redundant, but it's essential
84 -- f :: (T a, a) -> Int
86 -- When desugaring, we must generate
87 -- f = /\a. \v::a. case v of (t::T a, w::a) ->
88 -- case t of (T1 (x::Int)) ->
89 -- Note the (w::a), NOT (w::Int), because we have not yet
90 -- refined 'a' to Int. So we must know that the second component
91 -- of the tuple is of type 'a' not Int. See selectMatchVar
93 | PArrPat [LPat id] -- Syntactic parallel array
94 PostTcType -- The type of the elements
96 ------------ Constructor patterns ---------------
97 | ConPatIn (Located id)
101 pat_con :: Located DataCon,
102 pat_tvs :: [TyVar], -- Existentially bound type variables (tyvars only)
103 pat_dicts :: [EvVar], -- Ditto *coercion variables* and *dictionaries*
104 -- One reason for putting coercion variable here, I think,
105 -- is to ensure their kinds are zonked
106 pat_binds :: TcEvBinds, -- Bindings involving those dictionaries
107 pat_args :: HsConPatDetails id,
108 pat_ty :: Type -- The type of the pattern
111 ------------ View patterns ---------------
112 | ViewPat (LHsExpr id)
114 PostTcType -- The overall type of the pattern
115 -- (= the argument type of the view function)
118 ------------ Quasiquoted patterns ---------------
119 -- See Note [Quasi-quote overview] in TcSplice
120 | QuasiQuotePat (HsQuasiQuote id)
122 ------------ Literal and n+k patterns ---------------
123 | LitPat HsLit -- Used for *non-overloaded* literal patterns:
124 -- Int#, Char#, Int, Char, String, etc.
126 | NPat (HsOverLit id) -- ALWAYS positive
127 (Maybe (SyntaxExpr id)) -- Just (Name of 'negate') for negative
128 -- patterns, Nothing otherwise
129 (SyntaxExpr id) -- Equality checker, of type t->t->Bool
131 | NPlusKPat (Located id) -- n+k pattern
132 (HsOverLit id) -- It'll always be an HsIntegral
133 (SyntaxExpr id) -- (>=) function, of type t->t->Bool
134 (SyntaxExpr id) -- Name of '-' (see RnEnv.lookupSyntaxName)
136 ------------ Generics ---------------
137 | TypePat (LHsType id) -- Type pattern for generic definitions
138 -- e.g f{| a+b |} = ...
139 -- These show up only in class declarations,
140 -- and should be a top-level pattern
142 ------------ Pattern type signatures ---------------
143 | SigPatIn (LPat id) -- Pattern with a type signature
146 | SigPatOut (LPat id) -- Pattern with a type signature
149 ------------ Pattern coercions (translation only) ---------------
150 | CoPat HsWrapper -- If co :: t1 ~ t2, p :: t2,
151 -- then (CoPat co p) :: t1
152 (Pat id) -- Why not LPat? Ans: existing locn will do
153 Type -- Type of whole pattern, t1
154 -- During desugaring a (CoPat co pat) turns into a cast with 'co' on
155 -- the scrutinee, followed by a match on 'pat'
156 deriving (Data, Typeable)
159 HsConDetails is use for patterns/expressions *and* for data type declarations
162 data HsConDetails arg rec
163 = PrefixCon [arg] -- C p1 p2 p3
164 | RecCon rec -- C { x = p1, y = p2 }
165 | InfixCon arg arg -- p1 `C` p2
166 deriving (Data, Typeable)
168 type HsConPatDetails id = HsConDetails (LPat id) (HsRecFields id (LPat id))
170 hsConPatArgs :: HsConPatDetails id -> [LPat id]
171 hsConPatArgs (PrefixCon ps) = ps
172 hsConPatArgs (RecCon fs) = map hsRecFieldArg (rec_flds fs)
173 hsConPatArgs (InfixCon p1 p2) = [p1,p2]
176 However HsRecFields is used only for patterns and expressions
177 (not data type declarations)
180 data HsRecFields id arg -- A bunch of record fields
181 -- { x = 3, y = True }
182 -- Used for both expressions and patterns
183 = HsRecFields { rec_flds :: [HsRecField id arg],
184 rec_dotdot :: Maybe Int } -- Note [DotDot fields]
185 deriving (Data, Typeable)
187 -- Note [DotDot fields]
188 -- ~~~~~~~~~~~~~~~~~~~~
189 -- The rec_dotdot field means this:
190 -- Nothing => the normal case
191 -- Just n => the group uses ".." notation,
193 -- In the latter case:
195 -- *before* renamer: rec_flds are exactly the n user-written fields
197 -- *after* renamer: rec_flds includes *all* fields, with
198 -- the first 'n' being the user-written ones
199 -- and the remainder being 'filled in' implicitly
201 data HsRecField id arg = HsRecField {
202 hsRecFieldId :: Located id,
203 hsRecFieldArg :: arg, -- Filled in by renamer
204 hsRecPun :: Bool -- Note [Punning]
205 } deriving (Data, Typeable)
209 -- If you write T { x, y = v+1 }, the HsRecFields will be
210 -- HsRecField x x True ...
211 -- HsRecField y (v+1) False ...
212 -- That is, for "punned" field x is expanded (in the renamer)
213 -- to x=x; but with a punning flag so we can detect it later
214 -- (e.g. when pretty printing)
216 -- If the original field was qualified, we un-qualify it, thus
217 -- T { A.x } means T { A.x = x }
219 hsRecFields :: HsRecFields id arg -> [id]
220 hsRecFields rbinds = map (unLoc . hsRecFieldId) (rec_flds rbinds)
223 %************************************************************************
227 %************************************************************************
230 instance (OutputableBndr name) => Outputable (Pat name) where
233 pprPatBndr :: OutputableBndr name => name -> SDoc
234 pprPatBndr var -- Print with type info if -dppr-debug is on
235 = getPprStyle $ \ sty ->
236 if debugStyle sty then
237 parens (pprBndr LambdaBind var) -- Could pass the site to pprPat
238 -- but is it worth it?
242 pprParendLPat :: (OutputableBndr name) => LPat name -> SDoc
243 pprParendLPat (L _ p) = pprParendPat p
245 pprParendPat :: (OutputableBndr name) => Pat name -> SDoc
246 pprParendPat p | patNeedsParens p = parens (pprPat p)
247 | otherwise = pprPat p
249 patNeedsParens :: Pat name -> Bool
250 patNeedsParens (ConPatIn _ d) = not (null (hsConPatArgs d))
251 patNeedsParens (ConPatOut { pat_args = d }) = not (null (hsConPatArgs d))
252 patNeedsParens (SigPatIn {}) = True
253 patNeedsParens (SigPatOut {}) = True
254 patNeedsParens (ViewPat {}) = True
255 patNeedsParens (CoPat {}) = True
256 patNeedsParens _ = False
258 pprPat :: (OutputableBndr name) => Pat name -> SDoc
259 pprPat (VarPat var) = pprPatBndr var
260 pprPat (VarPatOut var bs) = pprPatBndr var <+> braces (ppr bs)
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 -- In this module because HsPat is above HsBinds in the import graph
381 isBangHsBind (PatBind { pat_lhs = p }) = isBangLPat p
382 isBangHsBind _ = False
384 isIrrefutableHsPat :: OutputableBndr id => LPat id -> Bool
385 -- (isIrrefutableHsPat p) is true if matching against p cannot fail,
386 -- in the sense of falling through to the next pattern.
387 -- (NB: this is not quite the same as the (silly) defn
388 -- in 3.17.2 of the Haskell 98 report.)
390 -- isIrrefutableHsPat returns False if it's in doubt; specifically
391 -- on a ConPatIn it doesn't know the size of the constructor family
392 -- But if it returns True, the pattern is definitely irrefutable
393 isIrrefutableHsPat pat
396 go (L _ pat) = go1 pat
398 go1 (WildPat {}) = True
399 go1 (VarPat {}) = True
400 go1 (VarPatOut {}) = True
401 go1 (LazyPat {}) = True
402 go1 (BangPat pat) = go pat
403 go1 (CoPat _ pat _) = go1 pat
404 go1 (ParPat pat) = go pat
405 go1 (AsPat _ pat) = go pat
406 go1 (ViewPat _ pat _) = go pat
407 go1 (SigPatIn pat _) = go pat
408 go1 (SigPatOut pat _) = go pat
409 go1 (TuplePat pats _ _) = all go pats
410 go1 (ListPat {}) = False
411 go1 (PArrPat {}) = False -- ?
413 go1 (ConPatIn {}) = False -- Conservative
414 go1 (ConPatOut{ pat_con = L _ con, pat_args = details })
415 = isJust (tyConSingleDataCon_maybe (dataConTyCon con))
416 -- NB: tyConSingleDataCon_maybe, *not* isProductTyCon, because
417 -- the latter is false of existentials. See Trac #4439
418 && all go (hsConPatArgs details)
420 go1 (LitPat {}) = False
421 go1 (NPat {}) = False
422 go1 (NPlusKPat {}) = False
424 go1 (QuasiQuotePat {}) = urk pat -- Gotten rid of by renamer, before
425 -- isIrrefutablePat is called
426 go1 (TypePat {}) = urk pat
428 urk pat = pprPanic "isIrrefutableHsPat:" (ppr pat)
430 hsPatNeedsParens :: Pat a -> Bool
431 hsPatNeedsParens (WildPat {}) = False
432 hsPatNeedsParens (VarPat {}) = False
433 hsPatNeedsParens (VarPatOut {}) = True
434 hsPatNeedsParens (LazyPat {}) = False
435 hsPatNeedsParens (BangPat {}) = False
436 hsPatNeedsParens (CoPat {}) = True
437 hsPatNeedsParens (ParPat {}) = False
438 hsPatNeedsParens (AsPat {}) = False
439 hsPatNeedsParens (ViewPat {}) = True
440 hsPatNeedsParens (SigPatIn {}) = True
441 hsPatNeedsParens (SigPatOut {}) = True
442 hsPatNeedsParens (TuplePat {}) = False
443 hsPatNeedsParens (ListPat {}) = False
444 hsPatNeedsParens (PArrPat {}) = False
445 hsPatNeedsParens (ConPatIn _ ds) = conPatNeedsParens ds
446 hsPatNeedsParens (ConPatOut {}) = True
447 hsPatNeedsParens (LitPat {}) = False
448 hsPatNeedsParens (NPat {}) = False
449 hsPatNeedsParens (NPlusKPat {}) = True
450 hsPatNeedsParens (QuasiQuotePat {}) = True
451 hsPatNeedsParens (TypePat {}) = False
453 conPatNeedsParens :: HsConDetails a b -> Bool
454 conPatNeedsParens (PrefixCon args) = not (null args)
455 conPatNeedsParens (InfixCon {}) = False
456 conPatNeedsParens (RecCon {}) = False