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