2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5 \section[PatSyntax]{Abstract Haskell syntax---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
16 Pat(..), InPat, OutPat, LPat,
19 HsConPatDetails, hsConPatArgs,
20 HsRecFields(..), HsRecField(..), hsRecFields,
24 mkPrefixConPat, mkCharLitPat, mkNilPat, mkCoPat, mkCoPatCoI,
27 patsAreAllCons, isConPat, isSigPat, isWildPat,
28 patsAreAllLits, isLitPat, isIrrefutableHsPat
31 #include "HsVersions.h"
33 import {-# SOURCE #-} HsExpr (SyntaxExpr, LHsExpr, pprLExpr)
43 import PprCore ( {- instance OutputableBndr TyVar -} )
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 | VarPatOut id (DictBinds id) -- Used only for overloaded Ids; the
69 -- bindings give its overloaded instances
70 | LazyPat (LPat id) -- Lazy pattern
71 | AsPat (Located id) (LPat id) -- As pattern
72 | ParPat (LPat id) -- Parenthesised pattern
73 | BangPat (LPat id) -- Bang pattern
75 ------------ Lists, tuples, arrays ---------------
76 | ListPat [LPat id] -- Syntactic list
77 PostTcType -- The type of the elements
79 | TuplePat [LPat id] -- Tuple
80 Boxity -- UnitPat is TuplePat []
82 -- You might think that the PostTcType was redundant, but it's essential
85 -- f :: (T a, a) -> Int
87 -- When desugaring, we must generate
88 -- f = /\a. \v::a. case v of (t::T a, w::a) ->
89 -- case t of (T1 (x::Int)) ->
90 -- Note the (w::a), NOT (w::Int), because we have not yet
91 -- refined 'a' to Int. So we must know that the second component
92 -- of the tuple is of type 'a' not Int. See selectMatchVar
94 | PArrPat [LPat id] -- Syntactic parallel array
95 PostTcType -- The type of the elements
97 ------------ Constructor patterns ---------------
98 | ConPatIn (Located id)
102 pat_con :: Located DataCon,
103 pat_tvs :: [TyVar], -- Existentially bound type variables (tyvars only)
104 pat_dicts :: [id], -- Ditto *coercion variables* and *dictionaries*
105 -- One reason for putting coercion variable here, I think,
106 -- is to ensure their kinds are zonked
107 pat_binds :: DictBinds id, -- Bindings involving those dictionaries
108 pat_args :: HsConPatDetails id,
109 pat_ty :: Type -- The type of the pattern
112 ------------ View patterns ---------------
113 | ViewPat (LHsExpr id)
115 PostTcType -- The overall type of the pattern
116 -- (= the argument type of the view function)
119 ------------ Quasiquoted patterns ---------------
120 -- See Note [Quasi-quote overview] in TcSplice
121 | QuasiQuotePat (HsQuasiQuote id)
123 ------------ Literal and n+k patterns ---------------
124 | LitPat HsLit -- Used for *non-overloaded* literal patterns:
125 -- Int#, Char#, Int, Char, String, etc.
127 | NPat (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'
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
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 expressiona and patterns
182 = HsRecFields { rec_flds :: [HsRecField id arg],
183 rec_dotdot :: Maybe Int }
184 -- Nothing => the normal case
185 -- Just n => the group uses ".." notation,
186 -- and the first n elts of rec_flds
187 -- were the user-written ones
188 -- (In the latter case, the remaining elts of
189 -- rec_flds are the non-user-written ones)
191 data HsRecField id arg = HsRecField {
192 hsRecFieldId :: Located id,
193 hsRecFieldArg :: arg,
194 hsRecPun :: Bool -- Note [Punning]
199 -- If you write T { x, y = v+1 }, the HsRecFields will be
200 -- HsRecField x x True ...
201 -- HsRecField y (v+1) False ...
202 -- That is, for "punned" field x is immediately expanded to x=x
203 -- but with a punning flag so we can detect it later
204 -- (e.g. when pretty printing)
206 hsRecFields :: HsRecFields id arg -> [id]
207 hsRecFields rbinds = map (unLoc . hsRecFieldId) (rec_flds rbinds)
211 data HsQuasiQuote id = HsQuasiQuote
219 %************************************************************************
223 %************************************************************************
226 instance (OutputableBndr name) => Outputable (Pat name) where
229 pprPatBndr :: OutputableBndr name => name -> SDoc
230 pprPatBndr var -- Print with type info if -dppr-debug is on
231 = getPprStyle $ \ sty ->
232 if debugStyle sty then
233 parens (pprBndr LambdaBind var) -- Could pass the site to pprPat
234 -- but is it worth it?
238 pprPat :: (OutputableBndr name) => Pat name -> SDoc
239 pprPat (VarPat var) = pprPatBndr var
240 pprPat (VarPatOut var bs) = parens (pprPatBndr var <+> braces (ppr bs))
241 pprPat (WildPat _) = char '_'
242 pprPat (LazyPat pat) = char '~' <> ppr pat
243 pprPat (BangPat pat) = char '!' <> ppr pat
244 pprPat (AsPat name pat) = parens (hcat [ppr name, char '@', ppr pat])
245 pprPat (ViewPat expr pat _) = parens (hcat [pprLExpr expr, text " -> ", ppr pat])
246 pprPat (ParPat pat) = parens (ppr pat)
247 pprPat (ListPat pats _) = brackets (interpp'SP pats)
248 pprPat (PArrPat pats _) = pabrackets (interpp'SP pats)
249 pprPat (TuplePat pats bx _) = tupleParens bx (interpp'SP pats)
251 pprPat (ConPatIn con details) = pprUserCon con details
252 pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts,
253 pat_binds = binds, pat_args = details })
254 = getPprStyle $ \ sty -> -- Tiresome; in TcBinds.tcRhs we print out a
255 if debugStyle sty then -- typechecked Pat in an error message,
256 -- and we want to make sure it prints nicely
257 ppr con <+> sep [ hsep (map pprPatBndr tvs) <+> hsep (map pprPatBndr dicts),
258 pprLHsBinds binds, pprConArgs details]
259 else pprUserCon con details
261 pprPat (LitPat s) = ppr s
262 pprPat (NPat l Nothing _) = ppr l
263 pprPat (NPat l (Just _) _) = char '-' <> ppr l
264 pprPat (NPlusKPat n k _ _) = hcat [ppr n, char '+', ppr k]
265 pprPat (QuasiQuotePat (HsQuasiQuote name quoter _ quote))
266 = char '$' <> brackets (ppr name) <>
267 ptext SLIT("[:") <> ppr quoter <> ptext SLIT("|") <>
268 ppr quote <> ptext SLIT("|]")
269 pprPat (TypePat ty) = ptext SLIT("{|") <> ppr ty <> ptext SLIT("|}")
270 pprPat (CoPat co pat _) = parens (pprHsWrapper (ppr pat) co)
271 pprPat (SigPatIn pat ty) = ppr pat <+> dcolon <+> ppr ty
272 pprPat (SigPatOut pat ty) = ppr pat <+> dcolon <+> ppr ty
274 pprUserCon c (InfixCon p1 p2) = ppr p1 <+> ppr c <+> ppr p2
275 pprUserCon c details = ppr c <+> pprConArgs details
277 pprConArgs (PrefixCon pats) = interppSP pats
278 pprConArgs (InfixCon p1 p2) = interppSP [p1,p2]
279 pprConArgs (RecCon rpats) = ppr rpats
281 instance (OutputableBndr id, Outputable arg)
282 => Outputable (HsRecFields id arg) where
283 ppr (HsRecFields { rec_flds = flds, rec_dotdot = Nothing })
284 = braces (fsep (punctuate comma (map ppr flds)))
285 ppr (HsRecFields { rec_flds = flds, rec_dotdot = Just n })
286 = braces (fsep (punctuate comma (map ppr (take n flds) ++ [dotdot])))
288 dotdot = ptext SLIT("..") <+> ifPprDebug (ppr (drop n flds))
290 instance (OutputableBndr id, Outputable arg)
291 => Outputable (HsRecField id arg) where
292 ppr (HsRecField { hsRecFieldId = f, hsRecFieldArg = arg,
294 = ppr f <+> (if pun then empty else equals <+> ppr arg)
296 -- add parallel array brackets around a document
298 pabrackets :: SDoc -> SDoc
299 pabrackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")
303 %************************************************************************
307 %************************************************************************
310 mkPrefixConPat :: DataCon -> [OutPat id] -> Type -> OutPat id
311 -- Make a vanilla Prefix constructor pattern
312 mkPrefixConPat dc pats ty
313 = noLoc $ ConPatOut { pat_con = noLoc dc, pat_tvs = [], pat_dicts = [],
314 pat_binds = emptyLHsBinds, pat_args = PrefixCon pats,
317 mkNilPat :: Type -> OutPat id
318 mkNilPat ty = mkPrefixConPat nilDataCon [] ty
320 mkCharLitPat :: Char -> OutPat id
321 mkCharLitPat c = mkPrefixConPat charDataCon [noLoc $ LitPat (HsCharPrim c)] charTy
323 mkCoPat :: HsWrapper -> Pat id -> Type -> Pat id
325 | isIdHsWrapper co = pat
326 | otherwise = CoPat co pat ty
328 mkCoPatCoI :: CoercionI -> Pat id -> Type -> Pat id
329 mkCoPatCoI IdCo pat ty = pat
330 mkCoPatCoI (ACo co) pat ty = mkCoPat (WpCo co) pat ty
334 %************************************************************************
336 %* Predicates for checking things about pattern-lists in EquationInfo *
338 %************************************************************************
340 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
342 Unlike in the Wadler chapter, where patterns are either ``variables''
343 or ``constructors,'' here we distinguish between:
346 Patterns that cannot fail to match: variables, wildcards, and lazy
349 These are the irrefutable patterns; the two other categories
350 are refutable patterns.
353 A non-literal constructor pattern (see next category).
355 \item[literal patterns:]
356 At least the numeric ones may be overloaded.
359 A pattern is in {\em exactly one} of the above three categories; `as'
360 patterns are treated specially, of course.
362 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
364 isWildPat (WildPat _) = True
365 isWildPat other = False
367 patsAreAllCons :: [Pat id] -> Bool
368 patsAreAllCons pat_list = all isConPat pat_list
370 isConPat (AsPat _ pat) = isConPat (unLoc pat)
371 isConPat (ConPatIn {}) = True
372 isConPat (ConPatOut {}) = True
373 isConPat (ListPat {}) = True
374 isConPat (PArrPat {}) = True
375 isConPat (TuplePat {}) = True
376 isConPat other = False
378 isSigPat (SigPatIn _ _) = True
379 isSigPat (SigPatOut _ _) = True
380 isSigPat other = False
382 patsAreAllLits :: [Pat id] -> Bool
383 patsAreAllLits pat_list = all isLitPat pat_list
385 isLitPat (AsPat _ pat) = isLitPat (unLoc pat)
386 isLitPat (LitPat _) = True
387 isLitPat (NPat _ _ _) = True
388 isLitPat (NPlusKPat _ _ _ _) = True
389 isLitPat other = False
391 isBangHsBind :: HsBind id -> Bool
392 -- In this module because HsPat is above HsBinds in the import graph
393 isBangHsBind (PatBind { pat_lhs = L _ (BangPat p) }) = True
394 isBangHsBind bind = False
396 isIrrefutableHsPat :: 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 (VarPatOut _ _) = True
413 go1 (LazyPat pat) = True
414 go1 (BangPat pat) = go pat
415 go1 (CoPat _ pat _) = go1 pat
416 go1 (ParPat pat) = go pat
417 go1 (AsPat _ pat) = go pat
418 go1 (ViewPat _ pat _) = go pat
419 go1 (SigPatIn pat _) = go pat
420 go1 (SigPatOut pat _) = go pat
421 go1 (TuplePat pats _ _) = all go pats
422 go1 (ListPat pats _) = False
423 go1 (PArrPat pats _) = False -- ?
425 go1 (ConPatIn _ _) = False -- Conservative
426 go1 (ConPatOut{ pat_con = L _ con, pat_args = details })
427 = isProductTyCon (dataConTyCon con)
428 && all go (hsConPatArgs details)
430 go1 (LitPat _) = False
431 go1 (NPat _ _ _) = False
432 go1 (NPlusKPat _ _ _ _) = False
434 go1 (TypePat _) = panic "isIrrefutableHsPat: type pattern"