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