Global renamings in HsSyn
[ghc-hetmet.git] / compiler / hsSyn / HsPat.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[PatSyntax]{Abstract Haskell syntax---patterns}
5
6 \begin{code}
7 module HsPat (
8         Pat(..), InPat, OutPat, LPat, 
9         
10         HsConDetails(..), hsConArgs,
11
12         mkPrefixConPat, mkCharLitPat, mkNilPat, mkCoPat,
13
14         isBangHsBind,   
15         patsAreAllCons, isConPat, isSigPat, isWildPat,
16         patsAreAllLits, isLitPat, isIrrefutableHsPat
17     ) where
18
19 #include "HsVersions.h"
20
21
22 import {-# SOURCE #-} HsExpr            ( SyntaxExpr )
23
24 -- friends:
25 import HsBinds          ( DictBinds, HsBind(..), HsWrapper, isIdHsWrapper, pprHsWrapper,
26                           emptyLHsBinds, pprLHsBinds )
27 import HsLit            ( HsLit(HsCharPrim), HsOverLit )
28 import HsTypes          ( LHsType, PostTcType )
29 import BasicTypes       ( Boxity, tupleParens )
30 -- others:
31 import PprCore          ( {- instance OutputableBndr TyVar -} )
32 import TysWiredIn       ( nilDataCon, charDataCon, charTy )
33 import Var              ( TyVar )
34 import DataCon          ( DataCon, dataConTyCon )
35 import TyCon            ( isProductTyCon )
36 import Outputable       
37 import Type             ( Type )
38 import SrcLoc           ( Located(..), unLoc, noLoc )
39 \end{code}
40
41
42 \begin{code}
43 type InPat id  = LPat id        -- No 'Out' constructors
44 type OutPat id = LPat id        -- No 'In' constructors
45
46 type LPat id = Located (Pat id)
47
48 data Pat id
49   =     ------------ Simple patterns ---------------
50     WildPat     PostTcType              -- Wild card
51   | VarPat      id                      -- Variable
52   | VarPatOut   id (DictBinds id)       -- Used only for overloaded Ids; the 
53                                         -- bindings give its overloaded instances
54   | LazyPat     (LPat id)               -- Lazy pattern
55   | AsPat       (Located id) (LPat id)  -- As pattern
56   | ParPat      (LPat id)               -- Parenthesised pattern
57   | BangPat     (LPat id)               -- Bang patterng
58
59         ------------ Lists, tuples, arrays ---------------
60   | ListPat     [LPat id]               -- Syntactic list
61                 PostTcType              -- The type of the elements
62                     
63   | TuplePat    [LPat id]               -- Tuple
64                 Boxity                  -- UnitPat is TuplePat []
65                 PostTcType
66         -- You might think that the PostTcType was redundant, but it's essential
67         --      data T a where
68         --        T1 :: Int -> T Int
69         --      f :: (T a, a) -> Int
70         --      f (T1 x, z) = z
71         -- When desugaring, we must generate
72         --      f = /\a. \v::a.  case v of (t::T a, w::a) ->
73         --                       case t of (T1 (x::Int)) -> 
74         -- Note the (w::a), NOT (w::Int), because we have not yet
75         -- refined 'a' to Int.  So we must know that the second component
76         -- of the tuple is of type 'a' not Int.  See selectMatchVar
77
78   | PArrPat     [LPat id]               -- Syntactic parallel array
79                 PostTcType              -- The type of the elements
80
81         ------------ Constructor patterns ---------------
82   | ConPatIn    (Located id)
83                 (HsConDetails id (LPat id))
84
85   | ConPatOut {
86         pat_con   :: Located DataCon,
87         pat_tvs   :: [TyVar],           -- Existentially bound type variables
88                                         --   including any bound coercion variables
89         pat_dicts :: [id],              -- Ditto dictionaries
90         pat_binds :: DictBinds id,      -- Bindings involving those dictionaries
91         pat_args  :: HsConDetails id (LPat id),
92         pat_ty    :: Type               -- The type of the pattern
93     }
94
95         ------------ Literal and n+k patterns ---------------
96   | LitPat          HsLit               -- Used for *non-overloaded* literal patterns:
97                                         -- Int#, Char#, Int, Char, String, etc.
98
99   | NPat            (HsOverLit id)              -- ALWAYS positive
100                     (Maybe (SyntaxExpr id))     -- Just (Name of 'negate') for negative
101                                                 -- patterns, Nothing otherwise
102                     (SyntaxExpr id)             -- Equality checker, of type t->t->Bool
103                     PostTcType                  -- Type of the pattern
104
105   | NPlusKPat       (Located id)        -- n+k pattern
106                     (HsOverLit id)      -- It'll always be an HsIntegral
107                     (SyntaxExpr id)     -- (>=) function, of type t->t->Bool
108                     (SyntaxExpr id)     -- Name of '-' (see RnEnv.lookupSyntaxName)
109
110         ------------ Generics ---------------
111   | TypePat         (LHsType id)        -- Type pattern for generic definitions
112                                         -- e.g  f{| a+b |} = ...
113                                         -- These show up only in class declarations,
114                                         -- and should be a top-level pattern
115
116         ------------ Pattern type signatures ---------------
117   | SigPatIn        (LPat id)           -- Pattern with a type signature
118                     (LHsType id)
119
120   | SigPatOut       (LPat id)           -- Pattern with a type signature
121                     Type
122
123         ------------ Dictionary patterns (translation only) ---------------
124   | DictPat         -- Used when destructing Dictionaries with an explicit case
125                     [id]                -- Superclass dicts
126                     [id]                -- Methods
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
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 both for patterns and for data type declarations
138
139 \begin{code}
140 data HsConDetails id arg
141   = PrefixCon [arg]                     -- C p1 p2 p3
142   | RecCon    [(Located id, arg)]       -- C { x = p1, y = p2 }
143   | InfixCon  arg arg                   -- p1 `C` p2
144
145 hsConArgs :: HsConDetails id arg -> [arg]
146 hsConArgs (PrefixCon ps)   = ps
147 hsConArgs (RecCon fs)      = map snd fs
148 hsConArgs (InfixCon p1 p2) = [p1,p2]
149 \end{code}
150
151
152 %************************************************************************
153 %*                                                                      *
154 %*              Printing patterns
155 %*                                                                      *
156 %************************************************************************
157
158 \begin{code}
159 instance (OutputableBndr name) => Outputable (Pat name) where
160     ppr = pprPat
161
162 pprPatBndr :: OutputableBndr name => name -> SDoc
163 pprPatBndr var                  -- Print with type info if -dppr-debug is on
164   = getPprStyle $ \ sty ->
165     if debugStyle sty then
166         parens (pprBndr LambdaBind var)         -- Could pass the site to pprPat
167                                                 -- but is it worth it?
168     else
169         ppr var
170
171 pprPat :: (OutputableBndr name) => Pat name -> SDoc
172 pprPat (VarPat var)       = pprPatBndr var
173 pprPat (VarPatOut var bs) = parens (pprPatBndr var <+> braces (ppr bs))
174 pprPat (WildPat _)        = char '_'
175 pprPat (LazyPat pat)      = char '~' <> ppr pat
176 pprPat (BangPat pat)      = char '!' <> ppr pat
177 pprPat (AsPat name pat)   = parens (hcat [ppr name, char '@', ppr pat])
178 pprPat (ParPat pat)       = parens (ppr pat)
179 pprPat (ListPat pats _)     = brackets (interpp'SP pats)
180 pprPat (PArrPat pats _)     = pabrackets (interpp'SP pats)
181 pprPat (TuplePat pats bx _) = tupleParens bx (interpp'SP pats)
182
183 pprPat (ConPatIn con details) = pprUserCon con details
184 pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts, 
185                     pat_binds = binds, pat_args = details })
186   = getPprStyle $ \ sty ->      -- Tiresome; in TcBinds.tcRhs we print out a 
187     if debugStyle sty then      -- typechecked Pat in an error message, 
188                                 -- and we want to make sure it prints nicely
189         ppr con <+> sep [ hsep (map pprPatBndr tvs) <+> hsep (map pprPatBndr dicts),
190                           pprLHsBinds binds, pprConArgs details]
191     else pprUserCon con details
192
193 pprPat (LitPat s)             = ppr s
194 pprPat (NPat l Nothing  _ _)  = ppr l
195 pprPat (NPat l (Just _) _ _)  = char '-' <> ppr l
196 pprPat (NPlusKPat n k _ _)    = hcat [ppr n, char '+', ppr k]
197 pprPat (TypePat ty)           = ptext SLIT("{|") <> ppr ty <> ptext SLIT("|}")
198 pprPat (CoPat co pat _)       = parens (pprHsWrapper (ppr pat) co)
199 pprPat (SigPatIn pat ty)      = ppr pat <+> dcolon <+> ppr ty
200 pprPat (SigPatOut pat ty)     = ppr pat <+> dcolon <+> ppr ty
201 pprPat (DictPat ds ms)        = parens (sep [ptext SLIT("{-dict-}"),
202                                              brackets (interpp'SP ds),
203                                              brackets (interpp'SP ms)])
204
205 pprUserCon c (InfixCon p1 p2) = ppr p1 <+> ppr c <+> ppr p2
206 pprUserCon c details          = ppr c <+> pprConArgs details
207
208 pprConArgs (PrefixCon pats) = interppSP pats
209 pprConArgs (InfixCon p1 p2) = interppSP [p1,p2]
210 pprConArgs (RecCon rpats)   = braces (hsep (punctuate comma (map (pp_rpat) rpats)))
211                             where
212                               pp_rpat (v, p) = hsep [ppr v, char '=', ppr p]
213
214
215 -- add parallel array brackets around a document
216 --
217 pabrackets   :: SDoc -> SDoc
218 pabrackets p  = ptext SLIT("[:") <> p <> ptext SLIT(":]")
219 \end{code}
220
221
222 %************************************************************************
223 %*                                                                      *
224 %*              Building patterns
225 %*                                                                      *
226 %************************************************************************
227
228 \begin{code}
229 mkPrefixConPat :: DataCon -> [OutPat id] -> Type -> OutPat id
230 -- Make a vanilla Prefix constructor pattern
231 mkPrefixConPat dc pats ty 
232   = noLoc $ ConPatOut { pat_con = noLoc dc, pat_tvs = [], pat_dicts = [],
233                         pat_binds = emptyLHsBinds, pat_args = PrefixCon pats, 
234                         pat_ty = ty }
235
236 mkNilPat :: Type -> OutPat id
237 mkNilPat ty = mkPrefixConPat nilDataCon [] ty
238
239 mkCharLitPat :: Char -> OutPat id
240 mkCharLitPat c = mkPrefixConPat charDataCon [noLoc $ LitPat (HsCharPrim c)] charTy
241
242 mkCoPat :: HsWrapper -> OutPat id -> Type -> OutPat id
243 mkCoPat co lpat@(L loc pat) ty
244   | isIdHsWrapper co = lpat
245   | otherwise = L loc (CoPat co pat ty)
246 \end{code}
247
248
249 %************************************************************************
250 %*                                                                      *
251 %* Predicates for checking things about pattern-lists in EquationInfo   *
252 %*                                                                      *
253 %************************************************************************
254
255 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
256
257 Unlike in the Wadler chapter, where patterns are either ``variables''
258 or ``constructors,'' here we distinguish between:
259 \begin{description}
260 \item[unfailable:]
261 Patterns that cannot fail to match: variables, wildcards, and lazy
262 patterns.
263
264 These are the irrefutable patterns; the two other categories
265 are refutable patterns.
266
267 \item[constructor:]
268 A non-literal constructor pattern (see next category).
269
270 \item[literal patterns:]
271 At least the numeric ones may be overloaded.
272 \end{description}
273
274 A pattern is in {\em exactly one} of the above three categories; `as'
275 patterns are treated specially, of course.
276
277 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
278 \begin{code}
279 isWildPat (WildPat _) = True
280 isWildPat other       = False
281
282 patsAreAllCons :: [Pat id] -> Bool
283 patsAreAllCons pat_list = all isConPat pat_list
284
285 isConPat (AsPat _ pat)   = isConPat (unLoc pat)
286 isConPat (ConPatIn {})   = True
287 isConPat (ConPatOut {})  = True
288 isConPat (ListPat {})    = True
289 isConPat (PArrPat {})    = True
290 isConPat (TuplePat {})   = True
291 isConPat (DictPat ds ms) = (length ds + length ms) > 1
292 isConPat other           = False
293
294 isSigPat (SigPatIn _ _)  = True
295 isSigPat (SigPatOut _ _) = True
296 isSigPat other           = False
297
298 patsAreAllLits :: [Pat id] -> Bool
299 patsAreAllLits pat_list = all isLitPat pat_list
300
301 isLitPat (AsPat _ pat)          = isLitPat (unLoc pat)
302 isLitPat (LitPat _)             = True
303 isLitPat (NPat _ _ _ _)         = True
304 isLitPat (NPlusKPat _ _ _ _)    = True
305 isLitPat other                  = False
306
307 isBangHsBind :: HsBind id -> Bool
308 -- In this module because HsPat is above HsBinds in the import graph
309 isBangHsBind (PatBind { pat_lhs = L _ (BangPat p) }) = True
310 isBangHsBind bind                                    = False
311
312 isIrrefutableHsPat :: LPat id -> Bool
313 -- This function returns False if it's in doubt; specifically
314 -- on a ConPatIn it doesn't know the size of the constructor family
315 -- But if it returns True, the pattern is definitely irrefutable
316 isIrrefutableHsPat pat
317   = go pat
318   where
319     go (L _ pat)         = go1 pat
320
321     go1 (WildPat _)         = True
322     go1 (VarPat _)          = True
323     go1 (VarPatOut _ _)     = True
324     go1 (LazyPat pat)       = True
325     go1 (BangPat pat)       = go pat
326     go1 (CoPat _ pat _)     = go1 pat
327     go1 (ParPat pat)        = go pat
328     go1 (AsPat _ pat)       = go pat
329     go1 (SigPatIn pat _)    = go pat
330     go1 (SigPatOut pat _)   = go pat
331     go1 (TuplePat pats _ _) = all go pats
332     go1 (ListPat pats _)    = False
333     go1 (PArrPat pats _)    = False     -- ?
334
335     go1 (ConPatIn _ _) = False  -- Conservative
336     go1 (ConPatOut{ pat_con = L _ con, pat_args = details }) 
337         =  isProductTyCon (dataConTyCon con)
338         && all go (hsConArgs details)
339
340     go1 (LitPat _)         = False
341     go1 (NPat _ _ _ _)     = False
342     go1 (NPlusKPat _ _ _ _) = False
343
344     go1 (TypePat _)   = panic "isIrrefutableHsPat: type pattern"
345     go1 (DictPat _ _) = panic "isIrrefutableHsPat: type pattern"
346 \end{code}
347