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