Add several new record features
[ghc-hetmet.git] / compiler / hsSyn / HsPat.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5 \section[PatSyntax]{Abstract Haskell syntax---patterns}
6
7 \begin{code}
8 module HsPat (
9         Pat(..), InPat, OutPat, LPat, 
10         
11         HsConDetails(..), 
12         HsConPatDetails, hsConPatArgs, 
13         HsRecFields(..), HsRecField(..), hsRecFields,
14
15         mkPrefixConPat, mkCharLitPat, mkNilPat, mkCoPat,
16
17         isBangHsBind,   
18         patsAreAllCons, isConPat, isSigPat, isWildPat,
19         patsAreAllLits, isLitPat, isIrrefutableHsPat
20     ) where
21
22 #include "HsVersions.h"
23
24
25 import {-# SOURCE #-} HsExpr            ( SyntaxExpr )
26
27 -- friends:
28 import HsBinds
29 import HsLit
30 import HsTypes
31 import HsDoc
32 import BasicTypes
33 -- others:
34 import PprCore          ( {- instance OutputableBndr TyVar -} )
35 import TysWiredIn
36 import Var
37 import DataCon
38 import TyCon
39 import Outputable       
40 import Type
41 import SrcLoc
42 \end{code}
43
44
45 \begin{code}
46 type InPat id  = LPat id        -- No 'Out' constructors
47 type OutPat id = LPat id        -- No 'In' constructors
48
49 type LPat id = Located (Pat id)
50
51 data 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
56
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
64
65         ------------ Lists, tuples, arrays ---------------
66   | ListPat     [LPat id]               -- Syntactic list
67                 PostTcType              -- The type of the elements
68                     
69   | TuplePat    [LPat id]               -- Tuple
70                 Boxity                  -- UnitPat is TuplePat []
71                 PostTcType
72         -- You might think that the PostTcType was redundant, but it's essential
73         --      data T a where
74         --        T1 :: Int -> T Int
75         --      f :: (T a, a) -> Int
76         --      f (T1 x, z) = z
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
83
84   | PArrPat     [LPat id]               -- Syntactic parallel array
85                 PostTcType              -- The type of the elements
86
87         ------------ Constructor patterns ---------------
88   | ConPatIn    (Located id)
89                 (HsConPatDetails id)
90
91   | ConPatOut {
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
99     }
100
101         ------------ Literal and n+k patterns ---------------
102   | LitPat          HsLit               -- Used for *non-overloaded* literal patterns:
103                                         -- Int#, Char#, Int, Char, String, etc.
104
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
110
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)
115
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
121
122         ------------ Pattern type signatures ---------------
123   | SigPatIn        (LPat id)           -- Pattern with a type signature
124                     (LHsType id)
125
126   | SigPatOut       (LPat id)           -- Pattern with a type signature
127                     Type
128
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'
136 \end{code}
137
138 HsConDetails is use for patterns/expressions *and* for data type declarations
139
140 \begin{code}
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
145
146 type HsConPatDetails id = HsConDetails (LPat id) (HsRecFields id (LPat id))
147
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]
152 \end{code}
153
154 However HsRecFields is used only for patterns and expressions
155 (not data type declarations)
156
157 \begin{code}
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)
169
170 data HsRecField id arg = HsRecField {
171         hsRecFieldId  :: Located id,
172         hsRecFieldArg :: arg,
173         hsRecPun      :: Bool           -- Note [Punning]
174   }
175
176 -- Note [Punning]
177 -- ~~~~~~~~~~~~~~
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)
184
185 hsRecFields :: HsRecFields id arg -> [id]
186 hsRecFields rbinds = map (unLoc . hsRecFieldId) (rec_flds rbinds)
187 \end{code}
188
189
190 %************************************************************************
191 %*                                                                      *
192 %*              Printing patterns
193 %*                                                                      *
194 %************************************************************************
195
196 \begin{code}
197 instance (OutputableBndr name) => Outputable (Pat name) where
198     ppr = pprPat
199
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?
206     else
207         ppr var
208
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)
220
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
230
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
239
240 pprUserCon c (InfixCon p1 p2) = ppr p1 <+> ppr c <+> ppr p2
241 pprUserCon c details          = ppr c <+> pprConArgs details
242
243 pprConArgs (PrefixCon pats) = interppSP pats
244 pprConArgs (InfixCon p1 p2) = interppSP [p1,p2]
245 pprConArgs (RecCon rpats)   = ppr rpats
246
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])))
253         where
254           dotdot = ptext SLIT("..") <+> ifPprDebug (ppr (drop n flds))
255
256 instance (OutputableBndr id, Outputable arg)
257       => Outputable (HsRecField id arg) where
258   ppr (HsRecField { hsRecFieldId = f, hsRecFieldArg = arg, 
259                     hsRecPun = pun })
260     = ppr f <+> (if pun then empty else equals <+> ppr arg)
261
262 -- add parallel array brackets around a document
263 --
264 pabrackets   :: SDoc -> SDoc
265 pabrackets p  = ptext SLIT("[:") <> p <> ptext SLIT(":]")
266 \end{code}
267
268
269 %************************************************************************
270 %*                                                                      *
271 %*              Building patterns
272 %*                                                                      *
273 %************************************************************************
274
275 \begin{code}
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, 
281                         pat_ty = ty }
282
283 mkNilPat :: Type -> OutPat id
284 mkNilPat ty = mkPrefixConPat nilDataCon [] ty
285
286 mkCharLitPat :: Char -> OutPat id
287 mkCharLitPat c = mkPrefixConPat charDataCon [noLoc $ LitPat (HsCharPrim c)] charTy
288
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)
293 \end{code}
294
295
296 %************************************************************************
297 %*                                                                      *
298 %* Predicates for checking things about pattern-lists in EquationInfo   *
299 %*                                                                      *
300 %************************************************************************
301
302 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
303
304 Unlike in the Wadler chapter, where patterns are either ``variables''
305 or ``constructors,'' here we distinguish between:
306 \begin{description}
307 \item[unfailable:]
308 Patterns that cannot fail to match: variables, wildcards, and lazy
309 patterns.
310
311 These are the irrefutable patterns; the two other categories
312 are refutable patterns.
313
314 \item[constructor:]
315 A non-literal constructor pattern (see next category).
316
317 \item[literal patterns:]
318 At least the numeric ones may be overloaded.
319 \end{description}
320
321 A pattern is in {\em exactly one} of the above three categories; `as'
322 patterns are treated specially, of course.
323
324 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
325 \begin{code}
326 isWildPat (WildPat _) = True
327 isWildPat other       = False
328
329 patsAreAllCons :: [Pat id] -> Bool
330 patsAreAllCons pat_list = all isConPat pat_list
331
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
339
340 isSigPat (SigPatIn _ _)  = True
341 isSigPat (SigPatOut _ _) = True
342 isSigPat other           = False
343
344 patsAreAllLits :: [Pat id] -> Bool
345 patsAreAllLits pat_list = all isLitPat pat_list
346
347 isLitPat (AsPat _ pat)          = isLitPat (unLoc pat)
348 isLitPat (LitPat _)             = True
349 isLitPat (NPat _ _ _ _)         = True
350 isLitPat (NPlusKPat _ _ _ _)    = True
351 isLitPat other                  = False
352
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
357
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
363   = go pat
364   where
365     go (L _ pat)         = go1 pat
366
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     -- ?
380
381     go1 (ConPatIn _ _) = False  -- Conservative
382     go1 (ConPatOut{ pat_con = L _ con, pat_args = details }) 
383         =  isProductTyCon (dataConTyCon con)
384         && all go (hsConPatArgs details)
385
386     go1 (LitPat _)         = False
387     go1 (NPat _ _ _ _)     = False
388     go1 (NPlusKPat _ _ _ _) = False
389
390     go1 (TypePat _)   = panic "isIrrefutableHsPat: type pattern"
391 \end{code}
392