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