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 Pat(..), InPat, OutPat, LPat,
12 HsConPatDetails, hsConPatArgs,
13 HsRecFields(..), HsRecField(..), hsRecFields,
15 mkPrefixConPat, mkCharLitPat, mkNilPat, mkCoPat,
18 patsAreAllCons, isConPat, isSigPat, isWildPat,
19 patsAreAllLits, isLitPat, isIrrefutableHsPat
22 #include "HsVersions.h"
25 import {-# SOURCE #-} HsExpr ( SyntaxExpr )
33 import PprCore ( {- instance OutputableBndr TyVar -} )
45 type InPat id = LPat id -- No 'Out' constructors
46 type OutPat id = LPat id -- No 'In' constructors
48 type LPat id = Located (Pat id)
51 = ------------ Simple patterns ---------------
52 WildPat PostTcType -- Wild card
53 -- The sole reason for a type on a WildPat is to
54 -- support hsPatType :: Pat Id -> Type
56 | VarPat id -- Variable
57 | VarPatOut id (DictBinds id) -- Used only for overloaded Ids; the
58 -- bindings give its overloaded instances
59 | LazyPat (LPat id) -- Lazy pattern
60 | AsPat (Located id) (LPat id) -- As pattern
61 | ParPat (LPat id) -- Parenthesised pattern
62 | BangPat (LPat id) -- Bang patterng
64 ------------ Lists, tuples, arrays ---------------
65 | ListPat [LPat id] -- Syntactic list
66 PostTcType -- The type of the elements
68 | TuplePat [LPat id] -- Tuple
69 Boxity -- UnitPat is TuplePat []
71 -- You might think that the PostTcType was redundant, but it's essential
74 -- f :: (T a, a) -> Int
76 -- When desugaring, we must generate
77 -- f = /\a. \v::a. case v of (t::T a, w::a) ->
78 -- case t of (T1 (x::Int)) ->
79 -- Note the (w::a), NOT (w::Int), because we have not yet
80 -- refined 'a' to Int. So we must know that the second component
81 -- of the tuple is of type 'a' not Int. See selectMatchVar
83 | PArrPat [LPat id] -- Syntactic parallel array
84 PostTcType -- The type of the elements
86 ------------ Constructor patterns ---------------
87 | ConPatIn (Located id)
91 pat_con :: Located DataCon,
92 pat_tvs :: [TyVar], -- Existentially bound type variables
93 -- including any bound coercion variables
94 pat_dicts :: [id], -- Ditto dictionaries
95 pat_binds :: DictBinds id, -- Bindings involving those dictionaries
96 pat_args :: HsConPatDetails id,
97 pat_ty :: Type -- The type of the pattern
100 ------------ Literal and n+k patterns ---------------
101 | LitPat HsLit -- Used for *non-overloaded* literal patterns:
102 -- Int#, Char#, Int, Char, String, etc.
104 | NPat (HsOverLit id) -- ALWAYS positive
105 (Maybe (SyntaxExpr id)) -- Just (Name of 'negate') for negative
106 -- patterns, Nothing otherwise
107 (SyntaxExpr id) -- Equality checker, of type t->t->Bool
108 PostTcType -- Type of the pattern
110 | NPlusKPat (Located id) -- n+k pattern
111 (HsOverLit id) -- It'll always be an HsIntegral
112 (SyntaxExpr id) -- (>=) function, of type t->t->Bool
113 (SyntaxExpr id) -- Name of '-' (see RnEnv.lookupSyntaxName)
115 ------------ Generics ---------------
116 | TypePat (LHsType id) -- Type pattern for generic definitions
117 -- e.g f{| a+b |} = ...
118 -- These show up only in class declarations,
119 -- and should be a top-level pattern
121 ------------ Pattern type signatures ---------------
122 | SigPatIn (LPat id) -- Pattern with a type signature
125 | SigPatOut (LPat id) -- Pattern with a type signature
128 ------------ Pattern coercions (translation only) ---------------
129 | CoPat HsWrapper -- If co::t1 -> t2, p::t2,
130 -- then (CoPat co p) :: t1
131 (Pat id) -- Why not LPat? Ans: existing locn will do
132 Type -- Type of whole pattern, t1
133 -- During desugaring a (CoPat co pat) turns into a cast with 'co' on
134 -- the scrutinee, followed by a match on 'pat'
137 HsConDetails is use for patterns/expressions *and* for data type declarations
140 data HsConDetails arg rec
141 = PrefixCon [arg] -- C p1 p2 p3
142 | RecCon rec -- C { x = p1, y = p2 }
143 | InfixCon arg arg -- p1 `C` p2
145 type HsConPatDetails id = HsConDetails (LPat id) (HsRecFields id (LPat id))
147 hsConPatArgs :: HsConPatDetails id -> [LPat id]
148 hsConPatArgs (PrefixCon ps) = ps
149 hsConPatArgs (RecCon fs) = map hsRecFieldArg (rec_flds fs)
150 hsConPatArgs (InfixCon p1 p2) = [p1,p2]
153 However HsRecFields is used only for patterns and expressions
154 (not data type declarations)
157 data HsRecFields id arg -- A bunch of record fields
158 -- { x = 3, y = True }
159 -- Used for both expressiona and patterns
160 = HsRecFields { rec_flds :: [HsRecField id arg],
161 rec_dotdot :: Maybe Int }
162 -- Nothing => the normal case
163 -- Just n => the group uses ".." notation,
164 -- and the first n elts of rec_flds
165 -- were the user-written ones
166 -- (In the latter case, the remaining elts of
167 -- rec_flds are the non-user-written ones)
169 data HsRecField id arg = HsRecField {
170 hsRecFieldId :: Located id,
171 hsRecFieldArg :: arg,
172 hsRecPun :: Bool -- Note [Punning]
177 -- If you write T { x, y = v+1 }, the HsRecFields will be
178 -- HsRecField x x True ...
179 -- HsRecField y (v+1) False ...
180 -- That is, for "punned" field x is immediately expanded to x=x
181 -- but with a punning flag so we can detect it later
182 -- (e.g. when pretty printing)
184 hsRecFields :: HsRecFields id arg -> [id]
185 hsRecFields rbinds = map (unLoc . hsRecFieldId) (rec_flds rbinds)
189 %************************************************************************
193 %************************************************************************
196 instance (OutputableBndr name) => Outputable (Pat name) where
199 pprPatBndr :: OutputableBndr name => name -> SDoc
200 pprPatBndr var -- Print with type info if -dppr-debug is on
201 = getPprStyle $ \ sty ->
202 if debugStyle sty then
203 parens (pprBndr LambdaBind var) -- Could pass the site to pprPat
204 -- but is it worth it?
208 pprPat :: (OutputableBndr name) => Pat name -> SDoc
209 pprPat (VarPat var) = pprPatBndr var
210 pprPat (VarPatOut var bs) = parens (pprPatBndr var <+> braces (ppr bs))
211 pprPat (WildPat _) = char '_'
212 pprPat (LazyPat pat) = char '~' <> ppr pat
213 pprPat (BangPat pat) = char '!' <> ppr pat
214 pprPat (AsPat name pat) = parens (hcat [ppr name, char '@', ppr pat])
215 pprPat (ParPat pat) = parens (ppr pat)
216 pprPat (ListPat pats _) = brackets (interpp'SP pats)
217 pprPat (PArrPat pats _) = pabrackets (interpp'SP pats)
218 pprPat (TuplePat pats bx _) = tupleParens bx (interpp'SP pats)
220 pprPat (ConPatIn con details) = pprUserCon con details
221 pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts,
222 pat_binds = binds, pat_args = details })
223 = getPprStyle $ \ sty -> -- Tiresome; in TcBinds.tcRhs we print out a
224 if debugStyle sty then -- typechecked Pat in an error message,
225 -- and we want to make sure it prints nicely
226 ppr con <+> sep [ hsep (map pprPatBndr tvs) <+> hsep (map pprPatBndr dicts),
227 pprLHsBinds binds, pprConArgs details]
228 else pprUserCon con details
230 pprPat (LitPat s) = ppr s
231 pprPat (NPat l Nothing _ _) = ppr l
232 pprPat (NPat l (Just _) _ _) = char '-' <> ppr l
233 pprPat (NPlusKPat n k _ _) = hcat [ppr n, char '+', ppr k]
234 pprPat (TypePat ty) = ptext SLIT("{|") <> ppr ty <> ptext SLIT("|}")
235 pprPat (CoPat co pat _) = parens (pprHsWrapper (ppr pat) co)
236 pprPat (SigPatIn pat ty) = ppr pat <+> dcolon <+> ppr ty
237 pprPat (SigPatOut pat ty) = ppr pat <+> dcolon <+> ppr ty
239 pprUserCon c (InfixCon p1 p2) = ppr p1 <+> ppr c <+> ppr p2
240 pprUserCon c details = ppr c <+> pprConArgs details
242 pprConArgs (PrefixCon pats) = interppSP pats
243 pprConArgs (InfixCon p1 p2) = interppSP [p1,p2]
244 pprConArgs (RecCon rpats) = ppr rpats
246 instance (OutputableBndr id, Outputable arg)
247 => Outputable (HsRecFields id arg) where
248 ppr (HsRecFields { rec_flds = flds, rec_dotdot = Nothing })
249 = braces (fsep (punctuate comma (map ppr flds)))
250 ppr (HsRecFields { rec_flds = flds, rec_dotdot = Just n })
251 = braces (fsep (punctuate comma (map ppr (take n flds) ++ [dotdot])))
253 dotdot = ptext SLIT("..") <+> ifPprDebug (ppr (drop n flds))
255 instance (OutputableBndr id, Outputable arg)
256 => Outputable (HsRecField id arg) where
257 ppr (HsRecField { hsRecFieldId = f, hsRecFieldArg = arg,
259 = ppr f <+> (if pun then empty else equals <+> ppr arg)
261 -- add parallel array brackets around a document
263 pabrackets :: SDoc -> SDoc
264 pabrackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")
268 %************************************************************************
272 %************************************************************************
275 mkPrefixConPat :: DataCon -> [OutPat id] -> Type -> OutPat id
276 -- Make a vanilla Prefix constructor pattern
277 mkPrefixConPat dc pats ty
278 = noLoc $ ConPatOut { pat_con = noLoc dc, pat_tvs = [], pat_dicts = [],
279 pat_binds = emptyLHsBinds, pat_args = PrefixCon pats,
282 mkNilPat :: Type -> OutPat id
283 mkNilPat ty = mkPrefixConPat nilDataCon [] ty
285 mkCharLitPat :: Char -> OutPat id
286 mkCharLitPat c = mkPrefixConPat charDataCon [noLoc $ LitPat (HsCharPrim c)] charTy
288 mkCoPat :: HsWrapper -> OutPat id -> Type -> OutPat id
289 mkCoPat co lpat@(L loc pat) ty
290 | isIdHsWrapper co = lpat
291 | otherwise = L loc (CoPat co pat ty)
295 %************************************************************************
297 %* Predicates for checking things about pattern-lists in EquationInfo *
299 %************************************************************************
301 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
303 Unlike in the Wadler chapter, where patterns are either ``variables''
304 or ``constructors,'' here we distinguish between:
307 Patterns that cannot fail to match: variables, wildcards, and lazy
310 These are the irrefutable patterns; the two other categories
311 are refutable patterns.
314 A non-literal constructor pattern (see next category).
316 \item[literal patterns:]
317 At least the numeric ones may be overloaded.
320 A pattern is in {\em exactly one} of the above three categories; `as'
321 patterns are treated specially, of course.
323 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
325 isWildPat (WildPat _) = True
326 isWildPat other = False
328 patsAreAllCons :: [Pat id] -> Bool
329 patsAreAllCons pat_list = all isConPat pat_list
331 isConPat (AsPat _ pat) = isConPat (unLoc pat)
332 isConPat (ConPatIn {}) = True
333 isConPat (ConPatOut {}) = True
334 isConPat (ListPat {}) = True
335 isConPat (PArrPat {}) = True
336 isConPat (TuplePat {}) = True
337 isConPat other = False
339 isSigPat (SigPatIn _ _) = True
340 isSigPat (SigPatOut _ _) = True
341 isSigPat other = False
343 patsAreAllLits :: [Pat id] -> Bool
344 patsAreAllLits pat_list = all isLitPat pat_list
346 isLitPat (AsPat _ pat) = isLitPat (unLoc pat)
347 isLitPat (LitPat _) = True
348 isLitPat (NPat _ _ _ _) = True
349 isLitPat (NPlusKPat _ _ _ _) = True
350 isLitPat other = False
352 isBangHsBind :: HsBind id -> Bool
353 -- In this module because HsPat is above HsBinds in the import graph
354 isBangHsBind (PatBind { pat_lhs = L _ (BangPat p) }) = True
355 isBangHsBind bind = False
357 isIrrefutableHsPat :: LPat id -> Bool
358 -- This function returns False if it's in doubt; specifically
359 -- on a ConPatIn it doesn't know the size of the constructor family
360 -- But if it returns True, the pattern is definitely irrefutable
361 isIrrefutableHsPat pat
364 go (L _ pat) = go1 pat
366 go1 (WildPat _) = True
367 go1 (VarPat _) = True
368 go1 (VarPatOut _ _) = True
369 go1 (LazyPat pat) = True
370 go1 (BangPat pat) = go pat
371 go1 (CoPat _ pat _) = go1 pat
372 go1 (ParPat pat) = go pat
373 go1 (AsPat _ pat) = go pat
374 go1 (SigPatIn pat _) = go pat
375 go1 (SigPatOut pat _) = go pat
376 go1 (TuplePat pats _ _) = all go pats
377 go1 (ListPat pats _) = False
378 go1 (PArrPat pats _) = False -- ?
380 go1 (ConPatIn _ _) = False -- Conservative
381 go1 (ConPatOut{ pat_con = L _ con, pat_args = details })
382 = isProductTyCon (dataConTyCon con)
383 && all go (hsConPatArgs details)
385 go1 (LitPat _) = False
386 go1 (NPat _ _ _ _) = False
387 go1 (NPlusKPat _ _ _ _) = False
389 go1 (TypePat _) = panic "isIrrefutableHsPat: type pattern"