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
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)
42 import PprCore ( {- instance OutputableBndr TyVar -} )
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 (DictBinds id) -- 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 :: [id], -- 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 :: DictBinds id, -- 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'
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
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 expressiona and patterns
181 = HsRecFields { rec_flds :: [HsRecField id arg],
182 rec_dotdot :: Maybe Int }
183 -- Nothing => the normal case
184 -- Just n => the group uses ".." notation,
185 -- and the first n elts of rec_flds
186 -- were the user-written ones
187 -- (In the latter case, the remaining elts of
188 -- rec_flds are the non-user-written ones)
190 data HsRecField id arg = HsRecField {
191 hsRecFieldId :: Located id,
192 hsRecFieldArg :: arg,
193 hsRecPun :: Bool -- Note [Punning]
198 -- If you write T { x, y = v+1 }, the HsRecFields will be
199 -- HsRecField x x True ...
200 -- HsRecField y (v+1) False ...
201 -- That is, for "punned" field x is immediately expanded to x=x
202 -- but with a punning flag so we can detect it later
203 -- (e.g. when pretty printing)
205 hsRecFields :: HsRecFields id arg -> [id]
206 hsRecFields rbinds = map (unLoc . hsRecFieldId) (rec_flds rbinds)
210 data HsQuasiQuote id = HsQuasiQuote
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 pprPat :: (OutputableBndr name) => Pat name -> SDoc
238 pprPat (VarPat var) = pprPatBndr var
239 pprPat (VarPatOut var bs) = parens (pprPatBndr var <+> braces (ppr bs))
240 pprPat (WildPat _) = char '_'
241 pprPat (LazyPat pat) = char '~' <> ppr pat
242 pprPat (BangPat pat) = char '!' <> ppr pat
243 pprPat (AsPat name pat) = parens (hcat [ppr name, char '@', ppr pat])
244 pprPat (ViewPat expr pat _) = parens (hcat [pprLExpr expr, text " -> ", ppr pat])
245 pprPat (ParPat pat) = parens (ppr pat)
246 pprPat (ListPat pats _) = brackets (interpp'SP pats)
247 pprPat (PArrPat pats _) = pabrackets (interpp'SP pats)
248 pprPat (TuplePat pats bx _) = tupleParens bx (interpp'SP pats)
250 pprPat (ConPatIn con details) = pprUserCon con details
251 pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts,
252 pat_binds = binds, pat_args = details })
253 = getPprStyle $ \ sty -> -- Tiresome; in TcBinds.tcRhs we print out a
254 if debugStyle sty then -- typechecked Pat in an error message,
255 -- and we want to make sure it prints nicely
256 ppr con <+> sep [ hsep (map pprPatBndr tvs) <+> hsep (map pprPatBndr dicts),
257 pprLHsBinds binds, pprConArgs details]
258 else pprUserCon con details
260 pprPat (LitPat s) = ppr s
261 pprPat (NPat l Nothing _) = ppr l
262 pprPat (NPat l (Just _) _) = char '-' <> ppr l
263 pprPat (NPlusKPat n k _ _) = hcat [ppr n, char '+', ppr k]
264 pprPat (QuasiQuotePat (HsQuasiQuote name quoter _ quote))
265 = char '$' <> brackets (ppr name) <>
266 ptext SLIT("[:") <> ppr quoter <> ptext SLIT("|") <>
267 ppr quote <> ptext SLIT("|]")
268 pprPat (TypePat ty) = ptext SLIT("{|") <> ppr ty <> ptext SLIT("|}")
269 pprPat (CoPat co pat _) = parens (pprHsWrapper (ppr pat) co)
270 pprPat (SigPatIn pat ty) = ppr pat <+> dcolon <+> ppr ty
271 pprPat (SigPatOut pat ty) = ppr pat <+> dcolon <+> ppr ty
273 pprUserCon :: (Outputable con, OutputableBndr id) => con -> HsConPatDetails id -> SDoc
274 pprUserCon c (InfixCon p1 p2) = ppr p1 <+> ppr c <+> ppr p2
275 pprUserCon c details = ppr c <+> pprConArgs details
277 pprConArgs :: OutputableBndr id => HsConPatDetails id -> SDoc
278 pprConArgs (PrefixCon pats) = interppSP pats
279 pprConArgs (InfixCon p1 p2) = interppSP [p1,p2]
280 pprConArgs (RecCon rpats) = ppr rpats
282 instance (OutputableBndr id, Outputable arg)
283 => Outputable (HsRecFields id arg) where
284 ppr (HsRecFields { rec_flds = flds, rec_dotdot = Nothing })
285 = braces (fsep (punctuate comma (map ppr flds)))
286 ppr (HsRecFields { rec_flds = flds, rec_dotdot = Just n })
287 = braces (fsep (punctuate comma (map ppr (take n flds) ++ [dotdot])))
289 dotdot = ptext SLIT("..") <+> ifPprDebug (ppr (drop n flds))
291 instance (OutputableBndr id, Outputable arg)
292 => Outputable (HsRecField id arg) where
293 ppr (HsRecField { hsRecFieldId = f, hsRecFieldArg = arg,
295 = ppr f <+> (if pun then empty else equals <+> ppr arg)
297 -- add parallel array brackets around a document
299 pabrackets :: SDoc -> SDoc
300 pabrackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")
304 %************************************************************************
308 %************************************************************************
311 mkPrefixConPat :: DataCon -> [OutPat id] -> Type -> OutPat id
312 -- Make a vanilla Prefix constructor pattern
313 mkPrefixConPat dc pats ty
314 = noLoc $ ConPatOut { pat_con = noLoc dc, pat_tvs = [], pat_dicts = [],
315 pat_binds = emptyLHsBinds, pat_args = PrefixCon pats,
318 mkNilPat :: Type -> OutPat id
319 mkNilPat ty = mkPrefixConPat nilDataCon [] ty
321 mkCharLitPat :: Char -> OutPat id
322 mkCharLitPat c = mkPrefixConPat charDataCon [noLoc $ LitPat (HsCharPrim c)] charTy
324 mkCoPat :: HsWrapper -> Pat id -> Type -> Pat id
326 | isIdHsWrapper co = pat
327 | otherwise = CoPat co pat ty
329 mkCoPatCoI :: CoercionI -> Pat id -> Type -> Pat id
330 mkCoPatCoI IdCo pat _ = pat
331 mkCoPatCoI (ACo co) pat ty = mkCoPat (WpCo co) pat ty
335 %************************************************************************
337 %* Predicates for checking things about pattern-lists in EquationInfo *
339 %************************************************************************
341 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
343 Unlike in the Wadler chapter, where patterns are either ``variables''
344 or ``constructors,'' here we distinguish between:
347 Patterns that cannot fail to match: variables, wildcards, and lazy
350 These are the irrefutable patterns; the two other categories
351 are refutable patterns.
354 A non-literal constructor pattern (see next category).
356 \item[literal patterns:]
357 At least the numeric ones may be overloaded.
360 A pattern is in {\em exactly one} of the above three categories; `as'
361 patterns are treated specially, of course.
363 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
365 isWildPat :: Pat id -> Bool
366 isWildPat (WildPat _) = True
369 patsAreAllCons :: [Pat id] -> Bool
370 patsAreAllCons pat_list = all isConPat pat_list
372 isConPat :: Pat id -> Bool
373 isConPat (AsPat _ pat) = isConPat (unLoc pat)
374 isConPat (ConPatIn {}) = True
375 isConPat (ConPatOut {}) = True
376 isConPat (ListPat {}) = True
377 isConPat (PArrPat {}) = True
378 isConPat (TuplePat {}) = True
381 isSigPat :: Pat id -> Bool
382 isSigPat (SigPatIn _ _) = True
383 isSigPat (SigPatOut _ _) = True
386 patsAreAllLits :: [Pat id] -> Bool
387 patsAreAllLits pat_list = all isLitPat pat_list
389 isLitPat :: Pat id -> Bool
390 isLitPat (AsPat _ pat) = isLitPat (unLoc pat)
391 isLitPat (LitPat _) = True
392 isLitPat (NPat _ _ _) = True
393 isLitPat (NPlusKPat _ _ _ _) = True
396 isBangHsBind :: HsBind id -> Bool
397 -- In this module because HsPat is above HsBinds in the import graph
398 isBangHsBind (PatBind { pat_lhs = L _ (BangPat _) }) = True
399 isBangHsBind _ = False
401 isIrrefutableHsPat :: LPat id -> Bool
402 -- (isIrrefutableHsPat p) is true if matching against p cannot fail,
403 -- in the sense of falling through to the next pattern.
404 -- (NB: this is not quite the same as the (silly) defn
405 -- in 3.17.2 of the Haskell 98 report.)
407 -- isIrrefutableHsPat returns False if it's in doubt; specifically
408 -- on a ConPatIn it doesn't know the size of the constructor family
409 -- But if it returns True, the pattern is definitely irrefutable
410 isIrrefutableHsPat pat
413 go (L _ pat) = go1 pat
415 go1 (WildPat _) = True
416 go1 (VarPat _) = True
417 go1 (VarPatOut _ _) = True
418 go1 (LazyPat _) = True
419 go1 (BangPat pat) = go pat
420 go1 (CoPat _ pat _) = go1 pat
421 go1 (ParPat pat) = go pat
422 go1 (AsPat _ pat) = go pat
423 go1 (ViewPat _ pat _) = go pat
424 go1 (SigPatIn pat _) = go pat
425 go1 (SigPatOut pat _) = go pat
426 go1 (TuplePat pats _ _) = all go pats
427 go1 (ListPat _ _) = False
428 go1 (PArrPat _ _) = False -- ?
430 go1 (ConPatIn _ _) = False -- Conservative
431 go1 (ConPatOut{ pat_con = L _ con, pat_args = details })
432 = isProductTyCon (dataConTyCon con)
433 && all go (hsConPatArgs details)
435 go1 (LitPat _) = False
436 go1 (NPat _ _ _) = False
437 go1 (NPlusKPat _ _ _ _) = False
439 go1 (TypePat _) = panic "isIrrefutableHsPat: type pattern"