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