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