87f471788129a863aa9cdd745925449dac66f919
[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 {-# OPTIONS -w #-}
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
13 -- for details
14
15 module HsPat (
16         Pat(..), InPat, OutPat, LPat, 
17         
18         HsConDetails(..), 
19         HsConPatDetails, hsConPatArgs, 
20         HsRecFields(..), HsRecField(..), hsRecFields,
21
22         mkPrefixConPat, mkCharLitPat, mkNilPat, mkCoPat, mkCoPatCoI,
23
24         isBangHsBind,   
25         patsAreAllCons, isConPat, isSigPat, isWildPat,
26         patsAreAllLits, isLitPat, isIrrefutableHsPat
27     ) where
28
29 #include "HsVersions.h"
30
31 import {-# SOURCE #-} HsExpr            (SyntaxExpr, LHsExpr, pprLExpr)
32
33 -- friends:
34 import HsBinds
35 import HsLit
36 import HsTypes
37 import HsDoc
38 import BasicTypes
39 -- others:
40 import Coercion
41 import PprCore          ( {- instance OutputableBndr TyVar -} )
42 import TysWiredIn
43 import Var
44 import DataCon
45 import TyCon
46 import Outputable       
47 import Type
48 import SrcLoc
49 \end{code}
50
51
52 \begin{code}
53 type InPat id  = LPat id        -- No 'Out' constructors
54 type OutPat id = LPat id        -- No 'In' constructors
55
56 type LPat id = Located (Pat id)
57
58 data 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
63
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 pattern
71
72         ------------ Lists, tuples, arrays ---------------
73   | ListPat     [LPat id]               -- Syntactic list
74                 PostTcType              -- The type of the elements
75                     
76   | TuplePat    [LPat id]               -- Tuple
77                 Boxity                  -- UnitPat is TuplePat []
78                 PostTcType
79         -- You might think that the PostTcType was redundant, but it's essential
80         --      data T a where
81         --        T1 :: Int -> T Int
82         --      f :: (T a, a) -> Int
83         --      f (T1 x, z) = z
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
90
91   | PArrPat     [LPat id]               -- Syntactic parallel array
92                 PostTcType              -- The type of the elements
93
94         ------------ Constructor patterns ---------------
95   | ConPatIn    (Located id)
96                 (HsConPatDetails id)
97
98   | ConPatOut {
99         pat_con   :: Located DataCon,
100         pat_tvs   :: [TyVar],           -- Existentially bound type variables (tyvars only)
101         pat_dicts :: [id],              -- Ditto *coercion variables* and *dictionaries*
102                                         -- One reason for putting coercion variable here, I think,
103                                         --      is to ensure their kinds are zonked
104         pat_binds :: DictBinds id,      -- Bindings involving those dictionaries
105         pat_args  :: HsConPatDetails id,
106         pat_ty    :: Type               -- The type of the pattern
107     }
108
109         ------------ View patterns ---------------
110   | ViewPat       (LHsExpr id)      
111                   (LPat id)
112                   PostTcType        -- The overall type of the pattern
113                                     -- (= the argument type of the view function)
114                                     -- for hsPatType.
115
116         ------------ Literal and n+k patterns ---------------
117   | LitPat          HsLit               -- Used for *non-overloaded* literal patterns:
118                                         -- Int#, Char#, Int, Char, String, etc.
119
120   | NPat            (HsOverLit id)              -- ALWAYS positive
121                     (Maybe (SyntaxExpr id))     -- Just (Name of 'negate') for negative
122                                                 -- patterns, Nothing otherwise
123                     (SyntaxExpr id)             -- Equality checker, of type t->t->Bool
124
125   | NPlusKPat       (Located id)        -- n+k pattern
126                     (HsOverLit id)      -- It'll always be an HsIntegral
127                     (SyntaxExpr id)     -- (>=) function, of type t->t->Bool
128                     (SyntaxExpr id)     -- Name of '-' (see RnEnv.lookupSyntaxName)
129
130         ------------ Generics ---------------
131   | TypePat         (LHsType id)        -- Type pattern for generic definitions
132                                         -- e.g  f{| a+b |} = ...
133                                         -- These show up only in class declarations,
134                                         -- and should be a top-level pattern
135
136         ------------ Pattern type signatures ---------------
137   | SigPatIn        (LPat id)           -- Pattern with a type signature
138                     (LHsType id)
139
140   | SigPatOut       (LPat id)           -- Pattern with a type signature
141                     Type
142
143         ------------ Pattern coercions (translation only) ---------------
144   | CoPat       HsWrapper               -- If co::t1 -> t2, p::t2, 
145                                         -- then (CoPat co p) :: t1
146                 (Pat id)                -- Why not LPat?  Ans: existing locn will do
147                 Type                    -- Type of whole pattern, t1
148         -- During desugaring a (CoPat co pat) turns into a cast with 'co' on 
149         -- the scrutinee, followed by a match on 'pat'
150 \end{code}
151
152 HsConDetails is use for patterns/expressions *and* for data type declarations
153
154 \begin{code}
155 data HsConDetails arg rec
156   = PrefixCon [arg]             -- C p1 p2 p3
157   | RecCon    rec               -- C { x = p1, y = p2 }
158   | InfixCon  arg arg           -- p1 `C` p2
159
160 type HsConPatDetails id = HsConDetails (LPat id) (HsRecFields id (LPat id))
161
162 hsConPatArgs :: HsConPatDetails id -> [LPat id]
163 hsConPatArgs (PrefixCon ps)   = ps
164 hsConPatArgs (RecCon fs)      = map hsRecFieldArg (rec_flds fs)
165 hsConPatArgs (InfixCon p1 p2) = [p1,p2]
166 \end{code}
167
168 However HsRecFields is used only for patterns and expressions
169 (not data type declarations)
170
171 \begin{code}
172 data HsRecFields id arg         -- A bunch of record fields
173                                 --      { x = 3, y = True }
174         -- Used for both expressiona and patterns
175   = HsRecFields { rec_flds   :: [HsRecField id arg],
176                   rec_dotdot :: Maybe Int }
177         -- Nothing => the normal case
178         -- Just n  => the group uses ".." notation, 
179         --              and the first n elts of rec_flds
180         --              were the user-written ones
181         -- (In the latter case, the remaining elts of
182         --  rec_flds are the non-user-written ones)
183
184 data HsRecField id arg = HsRecField {
185         hsRecFieldId  :: Located id,
186         hsRecFieldArg :: arg,
187         hsRecPun      :: Bool           -- Note [Punning]
188   }
189
190 -- Note [Punning]
191 -- ~~~~~~~~~~~~~~
192 -- If you write T { x, y = v+1 }, the HsRecFields will be
193 --      HsRecField x x True ...
194 --      HsRecField y (v+1) False ...
195 -- That is, for "punned" field x is immediately expanded to x=x
196 -- but with a punning flag so we can detect it later
197 -- (e.g. when pretty printing)
198
199 hsRecFields :: HsRecFields id arg -> [id]
200 hsRecFields rbinds = map (unLoc . hsRecFieldId) (rec_flds rbinds)
201 \end{code}
202
203
204 %************************************************************************
205 %*                                                                      *
206 %*              Printing patterns
207 %*                                                                      *
208 %************************************************************************
209
210 \begin{code}
211 instance (OutputableBndr name) => Outputable (Pat name) where
212     ppr = pprPat
213
214 pprPatBndr :: OutputableBndr name => name -> SDoc
215 pprPatBndr var                  -- Print with type info if -dppr-debug is on
216   = getPprStyle $ \ sty ->
217     if debugStyle sty then
218         parens (pprBndr LambdaBind var)         -- Could pass the site to pprPat
219                                                 -- but is it worth it?
220     else
221         ppr var
222
223 pprPat :: (OutputableBndr name) => Pat name -> SDoc
224 pprPat (VarPat var)       = pprPatBndr var
225 pprPat (VarPatOut var bs) = parens (pprPatBndr var <+> braces (ppr bs))
226 pprPat (WildPat _)        = char '_'
227 pprPat (LazyPat pat)      = char '~' <> ppr pat
228 pprPat (BangPat pat)      = char '!' <> ppr pat
229 pprPat (AsPat name pat)   = parens (hcat [ppr name, char '@', ppr pat])
230 pprPat (ViewPat expr pat _)   = parens (hcat [pprLExpr expr, text " -> ", ppr pat])
231 pprPat (ParPat pat)       = parens (ppr pat)
232 pprPat (ListPat pats _)     = brackets (interpp'SP pats)
233 pprPat (PArrPat pats _)     = pabrackets (interpp'SP pats)
234 pprPat (TuplePat pats bx _) = tupleParens bx (interpp'SP pats)
235
236 pprPat (ConPatIn con details) = pprUserCon con details
237 pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts, 
238                     pat_binds = binds, pat_args = details })
239   = getPprStyle $ \ sty ->      -- Tiresome; in TcBinds.tcRhs we print out a 
240     if debugStyle sty then      -- typechecked Pat in an error message, 
241                                 -- and we want to make sure it prints nicely
242         ppr con <+> sep [ hsep (map pprPatBndr tvs) <+> hsep (map pprPatBndr dicts),
243                           pprLHsBinds binds, pprConArgs details]
244     else pprUserCon con details
245
246 pprPat (LitPat s)             = ppr s
247 pprPat (NPat l Nothing  _)  = ppr l
248 pprPat (NPat l (Just _) _)  = char '-' <> ppr l
249 pprPat (NPlusKPat n k _ _)    = hcat [ppr n, char '+', ppr k]
250 pprPat (TypePat ty)           = ptext SLIT("{|") <> ppr ty <> ptext SLIT("|}")
251 pprPat (CoPat co pat _)       = parens (pprHsWrapper (ppr pat) co)
252 pprPat (SigPatIn pat ty)      = ppr pat <+> dcolon <+> ppr ty
253 pprPat (SigPatOut pat ty)     = ppr pat <+> dcolon <+> ppr ty
254
255 pprUserCon c (InfixCon p1 p2) = ppr p1 <+> ppr c <+> ppr p2
256 pprUserCon c details          = ppr c <+> pprConArgs details
257
258 pprConArgs (PrefixCon pats) = interppSP pats
259 pprConArgs (InfixCon p1 p2) = interppSP [p1,p2]
260 pprConArgs (RecCon rpats)   = ppr rpats
261
262 instance (OutputableBndr id, Outputable arg)
263       => Outputable (HsRecFields id arg) where
264   ppr (HsRecFields { rec_flds = flds, rec_dotdot = Nothing })
265         = braces (fsep (punctuate comma (map ppr flds)))
266   ppr (HsRecFields { rec_flds = flds, rec_dotdot = Just n })
267         = braces (fsep (punctuate comma (map ppr (take n flds) ++ [dotdot])))
268         where
269           dotdot = ptext SLIT("..") <+> ifPprDebug (ppr (drop n flds))
270
271 instance (OutputableBndr id, Outputable arg)
272       => Outputable (HsRecField id arg) where
273   ppr (HsRecField { hsRecFieldId = f, hsRecFieldArg = arg, 
274                     hsRecPun = pun })
275     = ppr f <+> (if pun then empty else equals <+> ppr arg)
276
277 -- add parallel array brackets around a document
278 --
279 pabrackets   :: SDoc -> SDoc
280 pabrackets p  = ptext SLIT("[:") <> p <> ptext SLIT(":]")
281 \end{code}
282
283
284 %************************************************************************
285 %*                                                                      *
286 %*              Building patterns
287 %*                                                                      *
288 %************************************************************************
289
290 \begin{code}
291 mkPrefixConPat :: DataCon -> [OutPat id] -> Type -> OutPat id
292 -- Make a vanilla Prefix constructor pattern
293 mkPrefixConPat dc pats ty 
294   = noLoc $ ConPatOut { pat_con = noLoc dc, pat_tvs = [], pat_dicts = [],
295                         pat_binds = emptyLHsBinds, pat_args = PrefixCon pats, 
296                         pat_ty = ty }
297
298 mkNilPat :: Type -> OutPat id
299 mkNilPat ty = mkPrefixConPat nilDataCon [] ty
300
301 mkCharLitPat :: Char -> OutPat id
302 mkCharLitPat c = mkPrefixConPat charDataCon [noLoc $ LitPat (HsCharPrim c)] charTy
303
304 mkCoPat :: HsWrapper -> Pat id -> Type -> Pat id
305 mkCoPat co pat ty
306   | isIdHsWrapper co = pat
307   | otherwise        = CoPat co pat ty
308
309 mkCoPatCoI :: CoercionI -> Pat id -> Type -> Pat id
310 mkCoPatCoI IdCo     pat ty = pat
311 mkCoPatCoI (ACo co) pat ty = mkCoPat (WpCo co) pat ty
312 \end{code}
313
314
315 %************************************************************************
316 %*                                                                      *
317 %* Predicates for checking things about pattern-lists in EquationInfo   *
318 %*                                                                      *
319 %************************************************************************
320
321 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
322
323 Unlike in the Wadler chapter, where patterns are either ``variables''
324 or ``constructors,'' here we distinguish between:
325 \begin{description}
326 \item[unfailable:]
327 Patterns that cannot fail to match: variables, wildcards, and lazy
328 patterns.
329
330 These are the irrefutable patterns; the two other categories
331 are refutable patterns.
332
333 \item[constructor:]
334 A non-literal constructor pattern (see next category).
335
336 \item[literal patterns:]
337 At least the numeric ones may be overloaded.
338 \end{description}
339
340 A pattern is in {\em exactly one} of the above three categories; `as'
341 patterns are treated specially, of course.
342
343 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
344 \begin{code}
345 isWildPat (WildPat _) = True
346 isWildPat other       = False
347
348 patsAreAllCons :: [Pat id] -> Bool
349 patsAreAllCons pat_list = all isConPat pat_list
350
351 isConPat (AsPat _ pat)   = isConPat (unLoc pat)
352 isConPat (ConPatIn {})   = True
353 isConPat (ConPatOut {})  = True
354 isConPat (ListPat {})    = True
355 isConPat (PArrPat {})    = True
356 isConPat (TuplePat {})   = True
357 isConPat other           = False
358
359 isSigPat (SigPatIn _ _)  = True
360 isSigPat (SigPatOut _ _) = True
361 isSigPat other           = False
362
363 patsAreAllLits :: [Pat id] -> Bool
364 patsAreAllLits pat_list = all isLitPat pat_list
365
366 isLitPat (AsPat _ pat)          = isLitPat (unLoc pat)
367 isLitPat (LitPat _)             = True
368 isLitPat (NPat _ _ _)           = True
369 isLitPat (NPlusKPat _ _ _ _)    = True
370 isLitPat other                  = False
371
372 isBangHsBind :: HsBind id -> Bool
373 -- In this module because HsPat is above HsBinds in the import graph
374 isBangHsBind (PatBind { pat_lhs = L _ (BangPat p) }) = True
375 isBangHsBind bind                                    = False
376
377 isIrrefutableHsPat :: LPat id -> Bool
378 -- (isIrrefutableHsPat p) is true if matching against p cannot fail,
379 -- in the sense of falling through to the next pattern.
380 --      (NB: this is not quite the same as the (silly) defn
381 --      in 3.17.2 of the Haskell 98 report.)
382 -- 
383 -- isIrrefutableHsPat returns False if it's in doubt; specifically
384 -- on a ConPatIn it doesn't know the size of the constructor family
385 -- But if it returns True, the pattern is definitely irrefutable
386 isIrrefutableHsPat pat
387   = go pat
388   where
389     go (L _ pat)         = go1 pat
390
391     go1 (WildPat _)         = True
392     go1 (VarPat _)          = True
393     go1 (VarPatOut _ _)     = True
394     go1 (LazyPat pat)       = True
395     go1 (BangPat pat)       = go pat
396     go1 (CoPat _ pat _)     = go1 pat
397     go1 (ParPat pat)        = go pat
398     go1 (AsPat _ pat)       = go pat
399     go1 (ViewPat _ pat _)   = go pat
400     go1 (SigPatIn pat _)    = go pat
401     go1 (SigPatOut pat _)   = go pat
402     go1 (TuplePat pats _ _) = all go pats
403     go1 (ListPat pats _)    = False
404     go1 (PArrPat pats _)    = False     -- ?
405
406     go1 (ConPatIn _ _) = False  -- Conservative
407     go1 (ConPatOut{ pat_con = L _ con, pat_args = details }) 
408         =  isProductTyCon (dataConTyCon con)
409         && all go (hsConPatArgs details)
410
411     go1 (LitPat _)         = False
412     go1 (NPat _ _ _)       = False
413     go1 (NPlusKPat _ _ _ _) = False
414
415     go1 (TypePat _)   = panic "isIrrefutableHsPat: type pattern"
416 \end{code}
417