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)
54 type InPat id = LPat id -- No 'Out' constructors
55 type OutPat id = LPat id -- No 'In' constructors
57 type LPat id = Located (Pat id)
60 = ------------ Simple patterns ---------------
61 WildPat PostTcType -- Wild card
62 -- The sole reason for a type on a WildPat is to
63 -- support hsPatType :: Pat Id -> Type
65 | VarPat id -- Variable
66 | VarPatOut id TcEvBinds -- Used only for overloaded Ids; the
67 -- bindings give its overloaded instances
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 ------------ Generics ---------------
136 | TypePat (LHsType id) -- Type pattern for generic definitions
137 -- e.g f{| a+b |} = ...
138 -- These show up only in class declarations,
139 -- and should be a top-level pattern
141 ------------ Pattern type signatures ---------------
142 | SigPatIn (LPat id) -- Pattern with a type signature
145 | SigPatOut (LPat id) -- Pattern with a type signature
148 ------------ Pattern coercions (translation only) ---------------
149 | CoPat HsWrapper -- If co :: t1 ~ t2, p :: t2,
150 -- then (CoPat co p) :: t1
151 (Pat id) -- Why not LPat? Ans: existing locn will do
152 Type -- Type of whole pattern, t1
153 -- During desugaring a (CoPat co pat) turns into a cast with 'co' on
154 -- the scrutinee, followed by a match on 'pat'
155 deriving (Data, Typeable)
158 HsConDetails is use for patterns/expressions *and* for data type declarations
161 data HsConDetails arg rec
162 = PrefixCon [arg] -- C p1 p2 p3
163 | RecCon rec -- C { x = p1, y = p2 }
164 | InfixCon arg arg -- p1 `C` p2
165 deriving (Data, Typeable)
167 type HsConPatDetails id = HsConDetails (LPat id) (HsRecFields id (LPat id))
169 hsConPatArgs :: HsConPatDetails id -> [LPat id]
170 hsConPatArgs (PrefixCon ps) = ps
171 hsConPatArgs (RecCon fs) = map hsRecFieldArg (rec_flds fs)
172 hsConPatArgs (InfixCon p1 p2) = [p1,p2]
175 However HsRecFields is used only for patterns and expressions
176 (not data type declarations)
179 data HsRecFields id arg -- A bunch of record fields
180 -- { x = 3, y = True }
181 -- Used for both expressions and patterns
182 = HsRecFields { rec_flds :: [HsRecField id arg],
183 rec_dotdot :: Maybe Int } -- Note [DotDot fields]
184 deriving (Data, Typeable)
186 -- Note [DotDot fields]
187 -- ~~~~~~~~~~~~~~~~~~~~
188 -- The rec_dotdot field means this:
189 -- Nothing => the normal case
190 -- Just n => the group uses ".." notation,
192 -- In the latter case:
194 -- *before* renamer: rec_flds are exactly the n user-written fields
196 -- *after* renamer: rec_flds includes *all* fields, with
197 -- the first 'n' being the user-written ones
198 -- and the remainder being 'filled in' implicitly
200 data HsRecField id arg = HsRecField {
201 hsRecFieldId :: Located id,
202 hsRecFieldArg :: arg, -- Filled in by renamer
203 hsRecPun :: Bool -- Note [Punning]
204 } deriving (Data, Typeable)
208 -- If you write T { x, y = v+1 }, the HsRecFields will be
209 -- HsRecField x x True ...
210 -- HsRecField y (v+1) False ...
211 -- That is, for "punned" field x is expanded (in the renamer)
212 -- to x=x; but with a punning flag so we can detect it later
213 -- (e.g. when pretty printing)
215 -- If the original field was qualified, we un-qualify it, thus
216 -- T { A.x } means T { A.x = x }
218 hsRecFields :: HsRecFields id arg -> [id]
219 hsRecFields rbinds = map (unLoc . hsRecFieldId) (rec_flds rbinds)
222 %************************************************************************
226 %************************************************************************
229 instance (OutputableBndr name) => Outputable (Pat name) where
232 pprPatBndr :: OutputableBndr name => name -> SDoc
233 pprPatBndr var -- Print with type info if -dppr-debug is on
234 = getPprStyle $ \ sty ->
235 if debugStyle sty then
236 parens (pprBndr LambdaBind var) -- Could pass the site to pprPat
237 -- but is it worth it?
241 pprParendLPat :: (OutputableBndr name) => LPat name -> SDoc
242 pprParendLPat (L _ p) = pprParendPat p
244 pprParendPat :: (OutputableBndr name) => Pat name -> SDoc
245 pprParendPat p | patNeedsParens p = parens (pprPat p)
246 | otherwise = pprPat p
248 patNeedsParens :: Pat name -> Bool
249 patNeedsParens (ConPatIn _ d) = not (null (hsConPatArgs d))
250 patNeedsParens (ConPatOut { pat_args = d }) = not (null (hsConPatArgs d))
251 patNeedsParens (SigPatIn {}) = True
252 patNeedsParens (SigPatOut {}) = True
253 patNeedsParens (ViewPat {}) = True
254 patNeedsParens (CoPat {}) = True
255 patNeedsParens _ = False
257 pprPat :: (OutputableBndr name) => Pat name -> SDoc
258 pprPat (VarPat var) = pprPatBndr var
259 pprPat (VarPatOut var bs) = pprPatBndr var <+> braces (ppr bs)
260 pprPat (WildPat _) = char '_'
261 pprPat (LazyPat pat) = char '~' <> pprParendLPat pat
262 pprPat (BangPat pat) = char '!' <> pprParendLPat pat
263 pprPat (AsPat name pat) = hcat [ppr name, char '@', pprParendLPat pat]
264 pprPat (ViewPat expr pat _) = hcat [pprLExpr expr, text " -> ", ppr pat]
265 pprPat (ParPat pat) = parens (ppr pat)
266 pprPat (ListPat pats _) = brackets (interpp'SP pats)
267 pprPat (PArrPat pats _) = pabrackets (interpp'SP pats)
268 pprPat (TuplePat pats bx _) = tupleParens bx (interpp'SP pats)
270 pprPat (ConPatIn con details) = pprUserCon con details
271 pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts,
272 pat_binds = binds, pat_args = details })
273 = getPprStyle $ \ sty -> -- Tiresome; in TcBinds.tcRhs we print out a
274 if debugStyle sty then -- typechecked Pat in an error message,
275 -- and we want to make sure it prints nicely
276 ppr con <+> sep [ hsep (map pprPatBndr tvs) <+> hsep (map pprPatBndr dicts),
277 ppr binds, pprConArgs details]
278 else pprUserCon con details
280 pprPat (LitPat s) = ppr s
281 pprPat (NPat l Nothing _) = ppr l
282 pprPat (NPat l (Just _) _) = char '-' <> ppr l
283 pprPat (NPlusKPat n k _ _) = hcat [ppr n, char '+', ppr k]
284 pprPat (QuasiQuotePat qq) = ppr qq
285 pprPat (TypePat ty) = ptext (sLit "{|") <> ppr ty <> ptext (sLit "|}")
286 pprPat (CoPat co pat _) = pprHsWrapper (ppr pat) co
287 pprPat (SigPatIn pat ty) = ppr pat <+> dcolon <+> ppr ty
288 pprPat (SigPatOut pat ty) = ppr pat <+> dcolon <+> ppr ty
290 pprUserCon :: (Outputable con, OutputableBndr id) => con -> HsConPatDetails id -> SDoc
291 pprUserCon c (InfixCon p1 p2) = ppr p1 <+> ppr c <+> ppr p2
292 pprUserCon c details = ppr c <+> pprConArgs details
294 pprConArgs :: OutputableBndr id => HsConPatDetails id -> SDoc
295 pprConArgs (PrefixCon pats) = sep (map pprParendLPat pats)
296 pprConArgs (InfixCon p1 p2) = sep [pprParendLPat p1, pprParendLPat p2]
297 pprConArgs (RecCon rpats) = ppr rpats
299 instance (OutputableBndr id, Outputable arg)
300 => Outputable (HsRecFields id arg) where
301 ppr (HsRecFields { rec_flds = flds, rec_dotdot = Nothing })
302 = braces (fsep (punctuate comma (map ppr flds)))
303 ppr (HsRecFields { rec_flds = flds, rec_dotdot = Just n })
304 = braces (fsep (punctuate comma (map ppr (take n flds) ++ [dotdot])))
306 dotdot = ptext (sLit "..") <+> ifPprDebug (ppr (drop n flds))
308 instance (OutputableBndr id, Outputable arg)
309 => Outputable (HsRecField id arg) where
310 ppr (HsRecField { hsRecFieldId = f, hsRecFieldArg = arg,
312 = ppr f <+> (ppUnless pun $ equals <+> ppr arg)
314 -- add parallel array brackets around a document
316 pabrackets :: SDoc -> SDoc
317 pabrackets p = ptext (sLit "[:") <> p <> ptext (sLit ":]")
321 %************************************************************************
325 %************************************************************************
328 mkPrefixConPat :: DataCon -> [OutPat id] -> Type -> OutPat id
329 -- Make a vanilla Prefix constructor pattern
330 mkPrefixConPat dc pats ty
331 = noLoc $ ConPatOut { pat_con = noLoc dc, pat_tvs = [], pat_dicts = [],
332 pat_binds = emptyTcEvBinds, pat_args = PrefixCon pats,
335 mkNilPat :: Type -> OutPat id
336 mkNilPat ty = mkPrefixConPat nilDataCon [] ty
338 mkCharLitPat :: Char -> OutPat id
339 mkCharLitPat c = mkPrefixConPat charDataCon [noLoc $ LitPat (HsCharPrim c)] charTy
343 %************************************************************************
345 %* Predicates for checking things about pattern-lists in EquationInfo *
347 %************************************************************************
349 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
351 Unlike in the Wadler chapter, where patterns are either ``variables''
352 or ``constructors,'' here we distinguish between:
355 Patterns that cannot fail to match: variables, wildcards, and lazy
358 These are the irrefutable patterns; the two other categories
359 are refutable patterns.
362 A non-literal constructor pattern (see next category).
364 \item[literal patterns:]
365 At least the numeric ones may be overloaded.
368 A pattern is in {\em exactly one} of the above three categories; `as'
369 patterns are treated specially, of course.
371 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
373 isBangLPat :: LPat id -> Bool
374 isBangLPat (L _ (BangPat {})) = True
375 isBangLPat (L _ (ParPat p)) = isBangLPat p
378 isBangHsBind :: HsBind id -> Bool
379 -- In this module because HsPat is above HsBinds in the import graph
380 isBangHsBind (PatBind { pat_lhs = p }) = isBangLPat p
381 isBangHsBind _ = False
383 isIrrefutableHsPat :: OutputableBndr id => LPat id -> Bool
384 -- (isIrrefutableHsPat p) is true if matching against p cannot fail,
385 -- in the sense of falling through to the next pattern.
386 -- (NB: this is not quite the same as the (silly) defn
387 -- in 3.17.2 of the Haskell 98 report.)
389 -- isIrrefutableHsPat returns False if it's in doubt; specifically
390 -- on a ConPatIn it doesn't know the size of the constructor family
391 -- But if it returns True, the pattern is definitely irrefutable
392 isIrrefutableHsPat pat
395 go (L _ pat) = go1 pat
397 go1 (WildPat {}) = True
398 go1 (VarPat {}) = True
399 go1 (VarPatOut {}) = True
400 go1 (LazyPat {}) = True
401 go1 (BangPat pat) = go pat
402 go1 (CoPat _ pat _) = go1 pat
403 go1 (ParPat pat) = go pat
404 go1 (AsPat _ pat) = go pat
405 go1 (ViewPat _ pat _) = go pat
406 go1 (SigPatIn pat _) = go pat
407 go1 (SigPatOut pat _) = go pat
408 go1 (TuplePat pats _ _) = all go pats
409 go1 (ListPat {}) = False
410 go1 (PArrPat {}) = False -- ?
412 go1 (ConPatIn {}) = False -- Conservative
413 go1 (ConPatOut{ pat_con = L _ con, pat_args = details })
414 = isProductTyCon (dataConTyCon con)
415 && all go (hsConPatArgs details)
417 go1 (LitPat {}) = False
418 go1 (NPat {}) = False
419 go1 (NPlusKPat {}) = False
421 go1 (QuasiQuotePat {}) = urk pat -- Gotten rid of by renamer, before
422 -- isIrrefutablePat is called
423 go1 (TypePat {}) = urk pat
425 urk pat = pprPanic "isIrrefutableHsPat:" (ppr pat)
427 hsPatNeedsParens :: Pat a -> Bool
428 hsPatNeedsParens (WildPat {}) = False
429 hsPatNeedsParens (VarPat {}) = False
430 hsPatNeedsParens (VarPatOut {}) = True
431 hsPatNeedsParens (LazyPat {}) = False
432 hsPatNeedsParens (BangPat {}) = False
433 hsPatNeedsParens (CoPat {}) = True
434 hsPatNeedsParens (ParPat {}) = False
435 hsPatNeedsParens (AsPat {}) = False
436 hsPatNeedsParens (ViewPat {}) = True
437 hsPatNeedsParens (SigPatIn {}) = True
438 hsPatNeedsParens (SigPatOut {}) = True
439 hsPatNeedsParens (TuplePat {}) = False
440 hsPatNeedsParens (ListPat {}) = False
441 hsPatNeedsParens (PArrPat {}) = False
442 hsPatNeedsParens (ConPatIn _ ds) = conPatNeedsParens ds
443 hsPatNeedsParens (ConPatOut {}) = True
444 hsPatNeedsParens (LitPat {}) = False
445 hsPatNeedsParens (NPat {}) = False
446 hsPatNeedsParens (NPlusKPat {}) = True
447 hsPatNeedsParens (QuasiQuotePat {}) = True
448 hsPatNeedsParens (TypePat {}) = False
450 conPatNeedsParens :: HsConDetails a b -> Bool
451 conPatNeedsParens (PrefixCon args) = not (null args)
452 conPatNeedsParens (InfixCon {}) = False
453 conPatNeedsParens (RecCon {}) = False