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