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 | LazyPat (LPat id) -- Lazy pattern
68 | AsPat (Located id) (LPat id) -- As pattern
69 | ParPat (LPat id) -- Parenthesised pattern
70 | BangPat (LPat id) -- Bang pattern
72 ------------ Lists, tuples, arrays ---------------
73 | ListPat [LPat id] -- Syntactic list
74 PostTcType -- The type of the elements
76 | TuplePat [LPat id] -- Tuple
77 Boxity -- UnitPat is TuplePat []
79 -- You might think that the PostTcType was redundant, but it's essential
82 -- f :: (T a, a) -> Int
84 -- When desugaring, we must generate
85 -- f = /\a. \v::a. case v of (t::T a, w::a) ->
86 -- case t of (T1 (x::Int)) ->
87 -- Note the (w::a), NOT (w::Int), because we have not yet
88 -- refined 'a' to Int. So we must know that the second component
89 -- of the tuple is of type 'a' not Int. See selectMatchVar
91 | PArrPat [LPat id] -- Syntactic parallel array
92 PostTcType -- The type of the elements
94 ------------ Constructor patterns ---------------
95 | ConPatIn (Located id)
99 pat_con :: Located DataCon,
100 pat_tvs :: [TyVar], -- Existentially bound type variables (tyvars only)
101 pat_dicts :: [EvVar], -- Ditto *coercion variables* and *dictionaries*
102 -- One reason for putting coercion variable here, I think,
103 -- is to ensure their kinds are zonked
104 pat_binds :: TcEvBinds, -- Bindings involving those dictionaries
105 pat_args :: HsConPatDetails id,
106 pat_ty :: Type -- The type of the pattern
109 ------------ View patterns ---------------
110 | ViewPat (LHsExpr id)
112 PostTcType -- The overall type of the pattern
113 -- (= the argument type of the view function)
116 ------------ Quasiquoted patterns ---------------
117 -- See Note [Quasi-quote overview] in TcSplice
118 | QuasiQuotePat (HsQuasiQuote id)
120 ------------ Literal and n+k patterns ---------------
121 | LitPat HsLit -- Used for *non-overloaded* literal patterns:
122 -- Int#, Char#, Int, Char, String, etc.
124 | NPat (HsOverLit id) -- ALWAYS positive
125 (Maybe (SyntaxExpr id)) -- Just (Name of 'negate') for negative
126 -- patterns, Nothing otherwise
127 (SyntaxExpr id) -- Equality checker, of type t->t->Bool
129 | NPlusKPat (Located id) -- n+k pattern
130 (HsOverLit id) -- It'll always be an HsIntegral
131 (SyntaxExpr id) -- (>=) function, of type t->t->Bool
132 (SyntaxExpr id) -- Name of '-' (see RnEnv.lookupSyntaxName)
134 ------------ Generics ---------------
135 | TypePat (LHsType id) -- Type pattern for generic definitions
136 -- e.g f{| a+b |} = ...
137 -- These show up only in class declarations,
138 -- and should be a top-level pattern
140 ------------ Pattern type signatures ---------------
141 | SigPatIn (LPat id) -- Pattern with a type signature
144 | SigPatOut (LPat id) -- Pattern with a type signature
147 ------------ Pattern coercions (translation only) ---------------
148 | CoPat HsWrapper -- If co :: t1 ~ t2, p :: t2,
149 -- then (CoPat co p) :: t1
150 (Pat id) -- Why not LPat? Ans: existing locn will do
151 Type -- Type of whole pattern, t1
152 -- During desugaring a (CoPat co pat) turns into a cast with 'co' on
153 -- the scrutinee, followed by a match on 'pat'
154 deriving (Data, Typeable)
157 HsConDetails is use for patterns/expressions *and* for data type declarations
160 data HsConDetails arg rec
161 = PrefixCon [arg] -- C p1 p2 p3
162 | RecCon rec -- C { x = p1, y = p2 }
163 | InfixCon arg arg -- p1 `C` p2
164 deriving (Data, Typeable)
166 type HsConPatDetails id = HsConDetails (LPat id) (HsRecFields id (LPat id))
168 hsConPatArgs :: HsConPatDetails id -> [LPat id]
169 hsConPatArgs (PrefixCon ps) = ps
170 hsConPatArgs (RecCon fs) = map hsRecFieldArg (rec_flds fs)
171 hsConPatArgs (InfixCon p1 p2) = [p1,p2]
174 However HsRecFields is used only for patterns and expressions
175 (not data type declarations)
178 data HsRecFields id arg -- A bunch of record fields
179 -- { x = 3, y = True }
180 -- Used for both expressions and patterns
181 = HsRecFields { rec_flds :: [HsRecField id arg],
182 rec_dotdot :: Maybe Int } -- Note [DotDot fields]
183 deriving (Data, Typeable)
185 -- Note [DotDot fields]
186 -- ~~~~~~~~~~~~~~~~~~~~
187 -- The rec_dotdot field means this:
188 -- Nothing => the normal case
189 -- Just n => the group uses ".." notation,
191 -- In the latter case:
193 -- *before* renamer: rec_flds are exactly the n user-written fields
195 -- *after* renamer: rec_flds includes *all* fields, with
196 -- the first 'n' being the user-written ones
197 -- and the remainder being 'filled in' implicitly
199 data HsRecField id arg = HsRecField {
200 hsRecFieldId :: Located id,
201 hsRecFieldArg :: arg, -- Filled in by renamer
202 hsRecPun :: Bool -- Note [Punning]
203 } deriving (Data, Typeable)
207 -- If you write T { x, y = v+1 }, the HsRecFields will be
208 -- HsRecField x x True ...
209 -- HsRecField y (v+1) False ...
210 -- That is, for "punned" field x is expanded (in the renamer)
211 -- to x=x; but with a punning flag so we can detect it later
212 -- (e.g. when pretty printing)
214 -- If the original field was qualified, we un-qualify it, thus
215 -- T { A.x } means T { A.x = x }
217 hsRecFields :: HsRecFields id arg -> [id]
218 hsRecFields rbinds = map (unLoc . hsRecFieldId) (rec_flds rbinds)
221 %************************************************************************
225 %************************************************************************
228 instance (OutputableBndr name) => Outputable (Pat name) where
231 pprPatBndr :: OutputableBndr name => name -> SDoc
232 pprPatBndr var -- Print with type info if -dppr-debug is on
233 = getPprStyle $ \ sty ->
234 if debugStyle sty then
235 parens (pprBndr LambdaBind var) -- Could pass the site to pprPat
236 -- but is it worth it?
240 pprParendLPat :: (OutputableBndr name) => LPat name -> SDoc
241 pprParendLPat (L _ p) = pprParendPat p
243 pprParendPat :: (OutputableBndr name) => Pat name -> SDoc
244 pprParendPat p | patNeedsParens p = parens (pprPat p)
245 | otherwise = pprPat p
247 patNeedsParens :: Pat name -> Bool
248 patNeedsParens (ConPatIn _ d) = not (null (hsConPatArgs d))
249 patNeedsParens (ConPatOut { pat_args = d }) = not (null (hsConPatArgs d))
250 patNeedsParens (SigPatIn {}) = True
251 patNeedsParens (SigPatOut {}) = True
252 patNeedsParens (ViewPat {}) = True
253 patNeedsParens (CoPat {}) = True
254 patNeedsParens _ = False
256 pprPat :: (OutputableBndr name) => Pat name -> SDoc
257 pprPat (VarPat var) = pprPatBndr var
258 pprPat (WildPat _) = char '_'
259 pprPat (LazyPat pat) = char '~' <> pprParendLPat pat
260 pprPat (BangPat pat) = char '!' <> pprParendLPat pat
261 pprPat (AsPat name pat) = hcat [ppr name, char '@', pprParendLPat pat]
262 pprPat (ViewPat expr pat _) = hcat [pprLExpr expr, text " -> ", ppr pat]
263 pprPat (ParPat pat) = parens (ppr pat)
264 pprPat (ListPat pats _) = brackets (interpp'SP pats)
265 pprPat (PArrPat pats _) = pabrackets (interpp'SP pats)
266 pprPat (TuplePat pats bx _) = tupleParens bx (interpp'SP pats)
268 pprPat (ConPatIn con details) = pprUserCon con details
269 pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts,
270 pat_binds = binds, pat_args = details })
271 = getPprStyle $ \ sty -> -- Tiresome; in TcBinds.tcRhs we print out a
272 if debugStyle sty then -- typechecked Pat in an error message,
273 -- and we want to make sure it prints nicely
274 ppr con <+> sep [ hsep (map pprPatBndr tvs) <+> hsep (map pprPatBndr dicts),
275 ppr binds, pprConArgs details]
276 else pprUserCon con details
278 pprPat (LitPat s) = ppr s
279 pprPat (NPat l Nothing _) = ppr l
280 pprPat (NPat l (Just _) _) = char '-' <> ppr l
281 pprPat (NPlusKPat n k _ _) = hcat [ppr n, char '+', ppr k]
282 pprPat (QuasiQuotePat qq) = ppr qq
283 pprPat (TypePat ty) = ptext (sLit "{|") <> ppr ty <> ptext (sLit "|}")
284 pprPat (CoPat co pat _) = pprHsWrapper (ppr pat) co
285 pprPat (SigPatIn pat ty) = ppr pat <+> dcolon <+> ppr ty
286 pprPat (SigPatOut pat ty) = ppr pat <+> dcolon <+> ppr ty
288 pprUserCon :: (Outputable con, OutputableBndr id) => con -> HsConPatDetails id -> SDoc
289 pprUserCon c (InfixCon p1 p2) = ppr p1 <+> ppr c <+> ppr p2
290 pprUserCon c details = ppr c <+> pprConArgs details
292 pprConArgs :: OutputableBndr id => HsConPatDetails id -> SDoc
293 pprConArgs (PrefixCon pats) = sep (map pprParendLPat pats)
294 pprConArgs (InfixCon p1 p2) = sep [pprParendLPat p1, pprParendLPat p2]
295 pprConArgs (RecCon rpats) = ppr rpats
297 instance (OutputableBndr id, Outputable arg)
298 => Outputable (HsRecFields id arg) where
299 ppr (HsRecFields { rec_flds = flds, rec_dotdot = Nothing })
300 = braces (fsep (punctuate comma (map ppr flds)))
301 ppr (HsRecFields { rec_flds = flds, rec_dotdot = Just n })
302 = braces (fsep (punctuate comma (map ppr (take n flds) ++ [dotdot])))
304 dotdot = ptext (sLit "..") <+> ifPprDebug (ppr (drop n flds))
306 instance (OutputableBndr id, Outputable arg)
307 => Outputable (HsRecField id arg) where
308 ppr (HsRecField { hsRecFieldId = f, hsRecFieldArg = arg,
310 = ppr f <+> (ppUnless pun $ equals <+> ppr arg)
312 -- add parallel array brackets around a document
314 pabrackets :: SDoc -> SDoc
315 pabrackets p = ptext (sLit "[:") <> p <> ptext (sLit ":]")
319 %************************************************************************
323 %************************************************************************
326 mkPrefixConPat :: DataCon -> [OutPat id] -> Type -> OutPat id
327 -- Make a vanilla Prefix constructor pattern
328 mkPrefixConPat dc pats ty
329 = noLoc $ ConPatOut { pat_con = noLoc dc, pat_tvs = [], pat_dicts = [],
330 pat_binds = emptyTcEvBinds, pat_args = PrefixCon pats,
333 mkNilPat :: Type -> OutPat id
334 mkNilPat ty = mkPrefixConPat nilDataCon [] ty
336 mkCharLitPat :: Char -> OutPat id
337 mkCharLitPat c = mkPrefixConPat charDataCon [noLoc $ LitPat (HsCharPrim c)] charTy
341 %************************************************************************
343 %* Predicates for checking things about pattern-lists in EquationInfo *
345 %************************************************************************
347 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
349 Unlike in the Wadler chapter, where patterns are either ``variables''
350 or ``constructors,'' here we distinguish between:
353 Patterns that cannot fail to match: variables, wildcards, and lazy
356 These are the irrefutable patterns; the two other categories
357 are refutable patterns.
360 A non-literal constructor pattern (see next category).
362 \item[literal patterns:]
363 At least the numeric ones may be overloaded.
366 A pattern is in {\em exactly one} of the above three categories; `as'
367 patterns are treated specially, of course.
369 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
371 isBangLPat :: LPat id -> Bool
372 isBangLPat (L _ (BangPat {})) = True
373 isBangLPat (L _ (ParPat p)) = isBangLPat p
376 isBangHsBind :: HsBind id -> Bool
377 -- In this module because HsPat is above HsBinds in the import graph
378 isBangHsBind (PatBind { pat_lhs = p }) = isBangLPat p
379 isBangHsBind _ = False
381 isIrrefutableHsPat :: OutputableBndr id => LPat id -> Bool
382 -- (isIrrefutableHsPat p) is true if matching against p cannot fail,
383 -- in the sense of falling through to the next pattern.
384 -- (NB: this is not quite the same as the (silly) defn
385 -- in 3.17.2 of the Haskell 98 report.)
387 -- isIrrefutableHsPat returns False if it's in doubt; specifically
388 -- on a ConPatIn it doesn't know the size of the constructor family
389 -- But if it returns True, the pattern is definitely irrefutable
390 isIrrefutableHsPat pat
393 go (L _ pat) = go1 pat
395 go1 (WildPat {}) = True
396 go1 (VarPat {}) = True
397 go1 (LazyPat {}) = True
398 go1 (BangPat pat) = go pat
399 go1 (CoPat _ pat _) = go1 pat
400 go1 (ParPat pat) = go pat
401 go1 (AsPat _ pat) = go pat
402 go1 (ViewPat _ pat _) = go pat
403 go1 (SigPatIn pat _) = go pat
404 go1 (SigPatOut pat _) = go pat
405 go1 (TuplePat pats _ _) = all go pats
406 go1 (ListPat {}) = False
407 go1 (PArrPat {}) = False -- ?
409 go1 (ConPatIn {}) = False -- Conservative
410 go1 (ConPatOut{ pat_con = L _ con, pat_args = details })
411 = isJust (tyConSingleDataCon_maybe (dataConTyCon con))
412 -- NB: tyConSingleDataCon_maybe, *not* isProductTyCon, because
413 -- the latter is false of existentials. See Trac #4439
414 && all go (hsConPatArgs details)
416 go1 (LitPat {}) = False
417 go1 (NPat {}) = False
418 go1 (NPlusKPat {}) = False
420 go1 (QuasiQuotePat {}) = urk pat -- Gotten rid of by renamer, before
421 -- isIrrefutablePat is called
422 go1 (TypePat {}) = urk pat
424 urk pat = pprPanic "isIrrefutableHsPat:" (ppr pat)
426 hsPatNeedsParens :: Pat a -> Bool
427 hsPatNeedsParens (WildPat {}) = False
428 hsPatNeedsParens (VarPat {}) = False
429 hsPatNeedsParens (LazyPat {}) = False
430 hsPatNeedsParens (BangPat {}) = False
431 hsPatNeedsParens (CoPat {}) = True
432 hsPatNeedsParens (ParPat {}) = False
433 hsPatNeedsParens (AsPat {}) = False
434 hsPatNeedsParens (ViewPat {}) = True
435 hsPatNeedsParens (SigPatIn {}) = True
436 hsPatNeedsParens (SigPatOut {}) = True
437 hsPatNeedsParens (TuplePat {}) = False
438 hsPatNeedsParens (ListPat {}) = False
439 hsPatNeedsParens (PArrPat {}) = False
440 hsPatNeedsParens (ConPatIn _ ds) = conPatNeedsParens ds
441 hsPatNeedsParens (ConPatOut {}) = True
442 hsPatNeedsParens (LitPat {}) = False
443 hsPatNeedsParens (NPat {}) = False
444 hsPatNeedsParens (NPlusKPat {}) = True
445 hsPatNeedsParens (QuasiQuotePat {}) = True
446 hsPatNeedsParens (TypePat {}) = False
448 conPatNeedsParens :: HsConDetails a b -> Bool
449 conPatNeedsParens (PrefixCon args) = not (null args)
450 conPatNeedsParens (InfixCon {}) = False
451 conPatNeedsParens (RecCon {}) = False