Use OPTIONS rather than OPTIONS_GHC for pragmas
[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/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,
23
24         isBangHsBind,   
25         patsAreAllCons, isConPat, isSigPat, isWildPat,
26         patsAreAllLits, isLitPat, isIrrefutableHsPat
27     ) where
28
29 #include "HsVersions.h"
30
31
32 import {-# SOURCE #-} HsExpr            ( SyntaxExpr )
33
34 -- friends:
35 import HsBinds
36 import HsLit
37 import HsTypes
38 import BasicTypes
39 -- others:
40 import PprCore          ( {- instance OutputableBndr TyVar -} )
41 import TysWiredIn
42 import Var
43 import DataCon
44 import TyCon
45 import Outputable       
46 import Type
47 import SrcLoc
48 \end{code}
49
50
51 \begin{code}
52 type InPat id  = LPat id        -- No 'Out' constructors
53 type OutPat id = LPat id        -- No 'In' constructors
54
55 type LPat id = Located (Pat id)
56
57 data 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
62
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
70
71         ------------ Lists, tuples, arrays ---------------
72   | ListPat     [LPat id]               -- Syntactic list
73                 PostTcType              -- The type of the elements
74                     
75   | TuplePat    [LPat id]               -- Tuple
76                 Boxity                  -- UnitPat is TuplePat []
77                 PostTcType
78         -- You might think that the PostTcType was redundant, but it's essential
79         --      data T a where
80         --        T1 :: Int -> T Int
81         --      f :: (T a, a) -> Int
82         --      f (T1 x, z) = z
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
89
90   | PArrPat     [LPat id]               -- Syntactic parallel array
91                 PostTcType              -- The type of the elements
92
93         ------------ Constructor patterns ---------------
94   | ConPatIn    (Located id)
95                 (HsConPatDetails id)
96
97   | ConPatOut {
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
105     }
106
107         ------------ Literal and n+k patterns ---------------
108   | LitPat          HsLit               -- Used for *non-overloaded* literal patterns:
109                                         -- Int#, Char#, Int, Char, String, etc.
110
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
116
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)
121
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
127
128         ------------ Pattern type signatures ---------------
129   | SigPatIn        (LPat id)           -- Pattern with a type signature
130                     (LHsType id)
131
132   | SigPatOut       (LPat id)           -- Pattern with a type signature
133                     Type
134
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'
142 \end{code}
143
144 HsConDetails is use for patterns/expressions *and* for data type declarations
145
146 \begin{code}
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
151
152 type HsConPatDetails id = HsConDetails (LPat id) (HsRecFields id (LPat id))
153
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]
158 \end{code}
159
160 However HsRecFields is used only for patterns and expressions
161 (not data type declarations)
162
163 \begin{code}
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)
175
176 data HsRecField id arg = HsRecField {
177         hsRecFieldId  :: Located id,
178         hsRecFieldArg :: arg,
179         hsRecPun      :: Bool           -- Note [Punning]
180   }
181
182 -- Note [Punning]
183 -- ~~~~~~~~~~~~~~
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)
190
191 hsRecFields :: HsRecFields id arg -> [id]
192 hsRecFields rbinds = map (unLoc . hsRecFieldId) (rec_flds rbinds)
193 \end{code}
194
195
196 %************************************************************************
197 %*                                                                      *
198 %*              Printing patterns
199 %*                                                                      *
200 %************************************************************************
201
202 \begin{code}
203 instance (OutputableBndr name) => Outputable (Pat name) where
204     ppr = pprPat
205
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?
212     else
213         ppr var
214
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)
226
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
236
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
245
246 pprUserCon c (InfixCon p1 p2) = ppr p1 <+> ppr c <+> ppr p2
247 pprUserCon c details          = ppr c <+> pprConArgs details
248
249 pprConArgs (PrefixCon pats) = interppSP pats
250 pprConArgs (InfixCon p1 p2) = interppSP [p1,p2]
251 pprConArgs (RecCon rpats)   = ppr rpats
252
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])))
259         where
260           dotdot = ptext SLIT("..") <+> ifPprDebug (ppr (drop n flds))
261
262 instance (OutputableBndr id, Outputable arg)
263       => Outputable (HsRecField id arg) where
264   ppr (HsRecField { hsRecFieldId = f, hsRecFieldArg = arg, 
265                     hsRecPun = pun })
266     = ppr f <+> (if pun then empty else equals <+> ppr arg)
267
268 -- add parallel array brackets around a document
269 --
270 pabrackets   :: SDoc -> SDoc
271 pabrackets p  = ptext SLIT("[:") <> p <> ptext SLIT(":]")
272 \end{code}
273
274
275 %************************************************************************
276 %*                                                                      *
277 %*              Building patterns
278 %*                                                                      *
279 %************************************************************************
280
281 \begin{code}
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, 
287                         pat_ty = ty }
288
289 mkNilPat :: Type -> OutPat id
290 mkNilPat ty = mkPrefixConPat nilDataCon [] ty
291
292 mkCharLitPat :: Char -> OutPat id
293 mkCharLitPat c = mkPrefixConPat charDataCon [noLoc $ LitPat (HsCharPrim c)] charTy
294
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)
299 \end{code}
300
301
302 %************************************************************************
303 %*                                                                      *
304 %* Predicates for checking things about pattern-lists in EquationInfo   *
305 %*                                                                      *
306 %************************************************************************
307
308 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
309
310 Unlike in the Wadler chapter, where patterns are either ``variables''
311 or ``constructors,'' here we distinguish between:
312 \begin{description}
313 \item[unfailable:]
314 Patterns that cannot fail to match: variables, wildcards, and lazy
315 patterns.
316
317 These are the irrefutable patterns; the two other categories
318 are refutable patterns.
319
320 \item[constructor:]
321 A non-literal constructor pattern (see next category).
322
323 \item[literal patterns:]
324 At least the numeric ones may be overloaded.
325 \end{description}
326
327 A pattern is in {\em exactly one} of the above three categories; `as'
328 patterns are treated specially, of course.
329
330 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
331 \begin{code}
332 isWildPat (WildPat _) = True
333 isWildPat other       = False
334
335 patsAreAllCons :: [Pat id] -> Bool
336 patsAreAllCons pat_list = all isConPat pat_list
337
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
345
346 isSigPat (SigPatIn _ _)  = True
347 isSigPat (SigPatOut _ _) = True
348 isSigPat other           = False
349
350 patsAreAllLits :: [Pat id] -> Bool
351 patsAreAllLits pat_list = all isLitPat pat_list
352
353 isLitPat (AsPat _ pat)          = isLitPat (unLoc pat)
354 isLitPat (LitPat _)             = True
355 isLitPat (NPat _ _ _ _)         = True
356 isLitPat (NPlusKPat _ _ _ _)    = True
357 isLitPat other                  = False
358
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
363
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
369   = go pat
370   where
371     go (L _ pat)         = go1 pat
372
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     -- ?
386
387     go1 (ConPatIn _ _) = False  -- Conservative
388     go1 (ConPatOut{ pat_con = L _ con, pat_args = details }) 
389         =  isProductTyCon (dataConTyCon con)
390         && all go (hsConPatArgs details)
391
392     go1 (LitPat _)         = False
393     go1 (NPat _ _ _ _)     = False
394     go1 (NPlusKPat _ _ _ _) = False
395
396     go1 (TypePat _)   = panic "isIrrefutableHsPat: type pattern"
397 \end{code}
398