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 ------------ Pattern type signatures ---------------
138 | SigPatIn (LPat id) -- Pattern with a type signature
141 | SigPatOut (LPat id) -- Pattern with a type signature
144 ------------ Pattern coercions (translation only) ---------------
145 | CoPat HsWrapper -- If co :: t1 ~ t2, p :: t2,
146 -- then (CoPat co p) :: t1
147 (Pat id) -- Why not LPat? Ans: existing locn will do
148 Type -- Type of whole pattern, t1
149 -- During desugaring a (CoPat co pat) turns into a cast with 'co' on
150 -- the scrutinee, followed by a match on 'pat'
151 deriving (Data, Typeable)
154 HsConDetails is use for patterns/expressions *and* for data type declarations
157 data HsConDetails arg rec
158 = PrefixCon [arg] -- C p1 p2 p3
159 | RecCon rec -- C { x = p1, y = p2 }
160 | InfixCon arg arg -- p1 `C` p2
161 deriving (Data, Typeable)
163 type HsConPatDetails id = HsConDetails (LPat id) (HsRecFields id (LPat id))
165 hsConPatArgs :: HsConPatDetails id -> [LPat id]
166 hsConPatArgs (PrefixCon ps) = ps
167 hsConPatArgs (RecCon fs) = map hsRecFieldArg (rec_flds fs)
168 hsConPatArgs (InfixCon p1 p2) = [p1,p2]
171 However HsRecFields is used only for patterns and expressions
172 (not data type declarations)
175 data HsRecFields id arg -- A bunch of record fields
176 -- { x = 3, y = True }
177 -- Used for both expressions and patterns
178 = HsRecFields { rec_flds :: [HsRecField id arg],
179 rec_dotdot :: Maybe Int } -- Note [DotDot fields]
180 deriving (Data, Typeable)
182 -- Note [DotDot fields]
183 -- ~~~~~~~~~~~~~~~~~~~~
184 -- The rec_dotdot field means this:
185 -- Nothing => the normal case
186 -- Just n => the group uses ".." notation,
188 -- In the latter case:
190 -- *before* renamer: rec_flds are exactly the n user-written fields
192 -- *after* renamer: rec_flds includes *all* fields, with
193 -- the first 'n' being the user-written ones
194 -- and the remainder being 'filled in' implicitly
196 data HsRecField id arg = HsRecField {
197 hsRecFieldId :: Located id,
198 hsRecFieldArg :: arg, -- Filled in by renamer
199 hsRecPun :: Bool -- Note [Punning]
200 } deriving (Data, Typeable)
204 -- If you write T { x, y = v+1 }, the HsRecFields will be
205 -- HsRecField x x True ...
206 -- HsRecField y (v+1) False ...
207 -- That is, for "punned" field x is expanded (in the renamer)
208 -- to x=x; but with a punning flag so we can detect it later
209 -- (e.g. when pretty printing)
211 -- If the original field was qualified, we un-qualify it, thus
212 -- T { A.x } means T { A.x = x }
214 hsRecFields :: HsRecFields id arg -> [id]
215 hsRecFields rbinds = map (unLoc . hsRecFieldId) (rec_flds rbinds)
218 %************************************************************************
222 %************************************************************************
225 instance (OutputableBndr name) => Outputable (Pat name) where
228 pprPatBndr :: OutputableBndr name => name -> SDoc
229 pprPatBndr var -- Print with type info if -dppr-debug is on
230 = getPprStyle $ \ sty ->
231 if debugStyle sty then
232 parens (pprBndr LambdaBind var) -- Could pass the site to pprPat
233 -- but is it worth it?
237 pprParendLPat :: (OutputableBndr name) => LPat name -> SDoc
238 pprParendLPat (L _ p) = pprParendPat p
240 pprParendPat :: (OutputableBndr name) => Pat name -> SDoc
241 pprParendPat p | patNeedsParens p = parens (pprPat p)
242 | otherwise = pprPat p
244 patNeedsParens :: Pat name -> Bool
245 patNeedsParens (ConPatIn _ d) = not (null (hsConPatArgs d))
246 patNeedsParens (ConPatOut { pat_args = d }) = not (null (hsConPatArgs d))
247 patNeedsParens (SigPatIn {}) = True
248 patNeedsParens (SigPatOut {}) = True
249 patNeedsParens (ViewPat {}) = True
250 patNeedsParens (CoPat {}) = True
251 patNeedsParens _ = False
253 pprPat :: (OutputableBndr name) => Pat name -> SDoc
254 pprPat (VarPat var) = pprPatBndr var
255 pprPat (WildPat _) = char '_'
256 pprPat (LazyPat pat) = char '~' <> pprParendLPat pat
257 pprPat (BangPat pat) = char '!' <> pprParendLPat pat
258 pprPat (AsPat name pat) = hcat [ppr name, char '@', pprParendLPat pat]
259 pprPat (ViewPat expr pat _) = hcat [pprLExpr expr, text " -> ", ppr pat]
260 pprPat (ParPat pat) = parens (ppr pat)
261 pprPat (ListPat pats _) = brackets (interpp'SP pats)
262 pprPat (PArrPat pats _) = pabrackets (interpp'SP pats)
263 pprPat (TuplePat pats bx _) = tupleParens bx (interpp'SP pats)
265 pprPat (ConPatIn con details) = pprUserCon con details
266 pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts,
267 pat_binds = binds, pat_args = details })
268 = getPprStyle $ \ sty -> -- Tiresome; in TcBinds.tcRhs we print out a
269 if debugStyle sty then -- typechecked Pat in an error message,
270 -- and we want to make sure it prints nicely
271 ppr con <+> sep [ hsep (map pprPatBndr tvs) <+> hsep (map pprPatBndr dicts),
272 ppr binds, pprConArgs details]
273 else pprUserCon con details
275 pprPat (LitPat s) = ppr s
276 pprPat (NPat l Nothing _) = ppr l
277 pprPat (NPat l (Just _) _) = char '-' <> ppr l
278 pprPat (NPlusKPat n k _ _) = hcat [ppr n, char '+', ppr k]
279 pprPat (QuasiQuotePat qq) = ppr qq
280 pprPat (CoPat co pat _) = pprHsWrapper (ppr pat) co
281 pprPat (SigPatIn pat ty) = ppr pat <+> dcolon <+> ppr ty
282 pprPat (SigPatOut pat ty) = ppr pat <+> dcolon <+> ppr ty
284 pprUserCon :: (Outputable con, OutputableBndr id) => con -> HsConPatDetails id -> SDoc
285 pprUserCon c (InfixCon p1 p2) = ppr p1 <+> ppr c <+> ppr p2
286 pprUserCon c details = ppr c <+> pprConArgs details
288 pprConArgs :: OutputableBndr id => HsConPatDetails id -> SDoc
289 pprConArgs (PrefixCon pats) = sep (map pprParendLPat pats)
290 pprConArgs (InfixCon p1 p2) = sep [pprParendLPat p1, pprParendLPat p2]
291 pprConArgs (RecCon rpats) = ppr rpats
293 instance (OutputableBndr id, Outputable arg)
294 => Outputable (HsRecFields id arg) where
295 ppr (HsRecFields { rec_flds = flds, rec_dotdot = Nothing })
296 = braces (fsep (punctuate comma (map ppr flds)))
297 ppr (HsRecFields { rec_flds = flds, rec_dotdot = Just n })
298 = braces (fsep (punctuate comma (map ppr (take n flds) ++ [dotdot])))
300 dotdot = ptext (sLit "..") <+> ifPprDebug (ppr (drop n flds))
302 instance (OutputableBndr id, Outputable arg)
303 => Outputable (HsRecField id arg) where
304 ppr (HsRecField { hsRecFieldId = f, hsRecFieldArg = arg,
306 = ppr f <+> (ppUnless pun $ equals <+> ppr arg)
308 -- add parallel array brackets around a document
310 pabrackets :: SDoc -> SDoc
311 pabrackets p = ptext (sLit "[:") <> p <> ptext (sLit ":]")
315 %************************************************************************
319 %************************************************************************
322 mkPrefixConPat :: DataCon -> [OutPat id] -> Type -> OutPat id
323 -- Make a vanilla Prefix constructor pattern
324 mkPrefixConPat dc pats ty
325 = noLoc $ ConPatOut { pat_con = noLoc dc, pat_tvs = [], pat_dicts = [],
326 pat_binds = emptyTcEvBinds, pat_args = PrefixCon pats,
329 mkNilPat :: Type -> OutPat id
330 mkNilPat ty = mkPrefixConPat nilDataCon [] ty
332 mkCharLitPat :: Char -> OutPat id
333 mkCharLitPat c = mkPrefixConPat charDataCon [noLoc $ LitPat (HsCharPrim c)] charTy
337 %************************************************************************
339 %* Predicates for checking things about pattern-lists in EquationInfo *
341 %************************************************************************
343 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
345 Unlike in the Wadler chapter, where patterns are either ``variables''
346 or ``constructors,'' here we distinguish between:
349 Patterns that cannot fail to match: variables, wildcards, and lazy
352 These are the irrefutable patterns; the two other categories
353 are refutable patterns.
356 A non-literal constructor pattern (see next category).
358 \item[literal patterns:]
359 At least the numeric ones may be overloaded.
362 A pattern is in {\em exactly one} of the above three categories; `as'
363 patterns are treated specially, of course.
365 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
367 isBangLPat :: LPat id -> Bool
368 isBangLPat (L _ (BangPat {})) = True
369 isBangLPat (L _ (ParPat p)) = isBangLPat p
372 isBangHsBind :: HsBind id -> Bool
373 -- A pattern binding with an outermost bang
374 -- Defined in this module because HsPat is above HsBinds in the import graph
375 isBangHsBind (PatBind { pat_lhs = p }) = isBangLPat p
376 isBangHsBind _ = False
378 isLiftedPatBind :: HsBind id -> Bool
379 -- A pattern binding with a compound pattern, not just a variable
381 -- (# a, b #) no, even if a::Int#
382 -- x no, even if x::Int#
383 -- We want to warn about a missing bang-pattern on the yes's
384 isLiftedPatBind (PatBind { pat_lhs = p }) = isLiftedLPat p
385 isLiftedPatBind _ = False
387 isLiftedLPat :: LPat id -> Bool
388 isLiftedLPat (L _ (ParPat p)) = isLiftedLPat p
389 isLiftedLPat (L _ (BangPat p)) = isLiftedLPat p
390 isLiftedLPat (L _ (AsPat _ p)) = isLiftedLPat p
391 isLiftedLPat (L _ (TuplePat _ Unboxed _)) = False
392 isLiftedLPat (L _ (VarPat {})) = False
393 isLiftedLPat (L _ (WildPat {})) = False
394 isLiftedLPat _ = True
396 isIrrefutableHsPat :: OutputableBndr id => LPat id -> Bool
397 -- (isIrrefutableHsPat p) is true if matching against p cannot fail,
398 -- in the sense of falling through to the next pattern.
399 -- (NB: this is not quite the same as the (silly) defn
400 -- in 3.17.2 of the Haskell 98 report.)
402 -- isIrrefutableHsPat returns False if it's in doubt; specifically
403 -- on a ConPatIn it doesn't know the size of the constructor family
404 -- But if it returns True, the pattern is definitely irrefutable
405 isIrrefutableHsPat pat
408 go (L _ pat) = go1 pat
410 go1 (WildPat {}) = True
411 go1 (VarPat {}) = True
412 go1 (LazyPat {}) = True
413 go1 (BangPat pat) = go pat
414 go1 (CoPat _ pat _) = go1 pat
415 go1 (ParPat pat) = go pat
416 go1 (AsPat _ pat) = go pat
417 go1 (ViewPat _ pat _) = go pat
418 go1 (SigPatIn pat _) = go pat
419 go1 (SigPatOut pat _) = go pat
420 go1 (TuplePat pats _ _) = all go pats
421 go1 (ListPat {}) = False
422 go1 (PArrPat {}) = False -- ?
424 go1 (ConPatIn {}) = False -- Conservative
425 go1 (ConPatOut{ pat_con = L _ con, pat_args = details })
426 = isJust (tyConSingleDataCon_maybe (dataConTyCon con))
427 -- NB: tyConSingleDataCon_maybe, *not* isProductTyCon, because
428 -- the latter is false of existentials. See Trac #4439
429 && all go (hsConPatArgs details)
431 go1 (LitPat {}) = False
432 go1 (NPat {}) = False
433 go1 (NPlusKPat {}) = False
435 go1 (QuasiQuotePat {}) = urk pat -- Gotten rid of by renamer, before
436 -- isIrrefutablePat is called
438 urk pat = pprPanic "isIrrefutableHsPat:" (ppr pat)
440 hsPatNeedsParens :: Pat a -> Bool
441 hsPatNeedsParens (WildPat {}) = False
442 hsPatNeedsParens (VarPat {}) = False
443 hsPatNeedsParens (LazyPat {}) = False
444 hsPatNeedsParens (BangPat {}) = False
445 hsPatNeedsParens (CoPat {}) = True
446 hsPatNeedsParens (ParPat {}) = False
447 hsPatNeedsParens (AsPat {}) = False
448 hsPatNeedsParens (ViewPat {}) = True
449 hsPatNeedsParens (SigPatIn {}) = True
450 hsPatNeedsParens (SigPatOut {}) = True
451 hsPatNeedsParens (TuplePat {}) = False
452 hsPatNeedsParens (ListPat {}) = False
453 hsPatNeedsParens (PArrPat {}) = False
454 hsPatNeedsParens (ConPatIn _ ds) = conPatNeedsParens ds
455 hsPatNeedsParens (ConPatOut {}) = True
456 hsPatNeedsParens (LitPat {}) = False
457 hsPatNeedsParens (NPat {}) = False
458 hsPatNeedsParens (NPlusKPat {}) = True
459 hsPatNeedsParens (QuasiQuotePat {}) = True
461 conPatNeedsParens :: HsConDetails a b -> Bool
462 conPatNeedsParens (PrefixCon args) = not (null args)
463 conPatNeedsParens (InfixCon {}) = False
464 conPatNeedsParens (RecCon {}) = False