00df7797b42b788be659fb2e4bdc670f78f4676f
[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         InPat(..),
9         OutPat(..),
10
11         irrefutablePat, irrefutablePats,
12         failureFreePat, isWildPat, 
13         patsAreAllCons, isConPat, 
14         patsAreAllLits, isLitPat,
15         collectPatBinders, collectPatsBinders,
16         collectSigTysFromPat, collectSigTysFromPats
17     ) where
18
19 #include "HsVersions.h"
20
21
22 -- friends:
23 import HsLit            ( HsLit, HsOverLit )
24 import HsExpr           ( HsExpr )
25 import HsTypes          ( HsType )
26 import BasicTypes       ( Fixity, Boxity, tupleParens )
27
28 -- others:
29 import Name             ( Name )
30 import Var              ( Id, TyVar )
31 import DataCon          ( DataCon, dataConTyCon )
32 import Name             ( isDataSymOcc, getOccName, NamedThing )
33 import Maybes           ( maybeToBool )
34 import Outputable       
35 import TyCon            ( maybeTyConSingleCon )
36 import Type             ( Type )
37 \end{code}
38
39 Patterns come in distinct before- and after-typechecking flavo(u)rs.
40 \begin{code}
41 data InPat name
42   = WildPatIn                           -- wild card
43   | VarPatIn        name                -- variable
44   | LitPatIn        HsLit               -- literal
45   | LazyPatIn       (InPat name)        -- lazy pattern
46   | AsPatIn         name                -- as pattern
47                     (InPat name)
48   | SigPatIn        (InPat name)
49                     (HsType name)
50   | ConPatIn        name                -- constructed type
51                     [InPat name]
52   | ConOpPatIn      (InPat name)
53                     name
54                     Fixity              -- c.f. OpApp in HsExpr
55                     (InPat name)
56
57   | NPatIn          HsOverLit
58
59   | NPlusKPatIn     name                -- n+k pattern
60                     HsOverLit           -- It'll always be an HsIntegral
61                     Name                -- Name of '-' (see RnEnv.lookupSyntaxName)
62
63   -- We preserve prefix negation and parenthesis for the precedence parser.
64
65   | ParPatIn        (InPat name)        -- parenthesised pattern
66
67   | ListPatIn       [InPat name]        -- syntactic list
68                                         -- must have >= 1 elements
69   | TuplePatIn      [InPat name] Boxity -- tuple (boxed?)
70
71   | RecPatIn        name                -- record
72                     [(name, InPat name, Bool)]  -- True <=> source used punning
73
74 -- Generics
75   | TypePatIn       (HsType name)       -- Type pattern for generic definitions
76                                         -- e.g  f{| a+b |} = ...
77                                         -- These show up only in class 
78                                         -- declarations,
79                                         -- and should be a top-level pattern
80
81 -- /Generics
82
83 data OutPat id
84   = WildPat         Type        -- wild card
85   | VarPat          id          -- variable (type is in the Id)
86   | LazyPat         (OutPat id) -- lazy pattern
87   | AsPat           id          -- as pattern
88                     (OutPat id)
89
90   | SigPat          (OutPat id) -- Pattern p
91                     Type        -- Type, t, of the whole pattern
92                     (HsExpr id (OutPat id))
93                                 -- Coercion function,
94                                 -- of type t -> typeof(p)
95
96   | ListPat                     -- Syntactic list
97                     Type        -- The type of the elements
98                     [OutPat id]
99
100   | TuplePat        [OutPat id] -- Tuple
101                     Boxity
102                                 -- UnitPat is TuplePat []
103
104   | ConPat          DataCon
105                     Type        -- the type of the pattern
106                     [TyVar]     -- Existentially bound type variables
107                     [id]        -- Ditto dictionaries
108                     [OutPat id]
109
110   -- ConOpPats are only used on the input side
111
112   | RecPat          DataCon             -- Record constructor
113                     Type                -- The type of the pattern
114                     [TyVar]             -- Existentially bound type variables
115                     [id]                -- Ditto dictionaries
116                     [(Id, OutPat id, Bool)]     -- True <=> source used punning
117
118   | LitPat          -- Used for *non-overloaded* literal patterns:
119                     -- Int#, Char#, Int, Char, String, etc.
120                     HsLit
121                     Type                -- Type of pattern
122
123   | NPat            -- Used for literal patterns where there's an equality function to call
124                     HsLit                       -- The literal is retained so that
125                                                 -- the desugarer can readily identify
126                                                 -- equations with identical literal-patterns
127                                                 -- Always HsInteger, HsRat or HsString.
128                     Type                        -- Type of pattern, t
129                     (HsExpr id (OutPat id))     -- Of type t -> Bool; detects match
130
131   | NPlusKPat       id
132                     Integer
133                     Type                        -- Type of pattern, t
134                     (HsExpr id (OutPat id))     -- Of type t -> Bool; detects match
135                     (HsExpr id (OutPat id))     -- Of type t -> t; subtracts k
136
137   | DictPat         -- Used when destructing Dictionaries with an explicit case
138                     [id]                        -- superclass dicts
139                     [id]                        -- methods
140 \end{code}
141
142 Now name in Inpat is not need to be in NAmedThing to be Outputable.
143 Needed by ../deSugar/Check.lhs
144
145 JJQC-2-12-97
146
147 \begin{code}
148 instance (Outputable name) => Outputable (InPat name) where
149     ppr = pprInPat
150
151 pprInPat :: (Outputable name) => InPat name -> SDoc
152
153 pprInPat (WildPatIn)          = char '_'
154 pprInPat (VarPatIn var)       = ppr var
155 pprInPat (LitPatIn s)         = ppr s
156 pprInPat (SigPatIn pat ty)    = ppr pat <+> dcolon <+> ppr ty
157 pprInPat (LazyPatIn pat)      = char '~' <> ppr pat
158 pprInPat (AsPatIn name pat)   = parens (hcat [ppr name, char '@', ppr pat])
159 pprInPat (ParPatIn pat)       = parens (pprInPat pat)
160 pprInPat (ListPatIn pats)     = brackets (interpp'SP pats)
161 pprInPat (TuplePatIn pats bx) = tupleParens bx (interpp'SP pats)
162 pprInPat (NPlusKPatIn n k _)  = parens (hcat [ppr n, char '+', ppr k])
163 pprInPat (NPatIn l)           = ppr l
164
165 pprInPat (ConPatIn c pats)
166   | null pats = ppr c
167   | otherwise = hsep [ppr c, interppSP pats] -- inner ParPats supply the necessary parens.
168
169 pprInPat (ConOpPatIn pat1 op fixity pat2)
170  = hsep [ppr pat1, ppr op, ppr pat2] -- ParPats put in parens
171
172         -- ToDo: use pprSym to print op (but this involves fiddling various
173         -- contexts & I'm lazy...); *PatIns are *rarely* printed anyway... (WDP)
174
175 pprInPat (RecPatIn con rpats)
176   = hsep [ppr con, braces (hsep (punctuate comma (map (pp_rpat) rpats)))]
177   where
178     pp_rpat (v, _, True) = ppr v
179     pp_rpat (v, p, _)    = hsep [ppr v, char '=', ppr p]
180
181 pprInPat (TypePatIn ty) = ptext SLIT("{|") <> ppr ty <> ptext SLIT("|}")
182 \end{code}
183
184 \begin{code}
185 instance (NamedThing id, Outputable id) => Outputable (OutPat id) where
186     ppr = pprOutPat
187 \end{code}
188
189 \begin{code}
190 pprOutPat (WildPat ty)  = char '_'
191 pprOutPat (VarPat var)  = ppr var
192 pprOutPat (LazyPat pat) = hcat [char '~', ppr pat]
193 pprOutPat (AsPat name pat)
194   = parens (hcat [ppr name, char '@', ppr pat])
195
196 pprOutPat (SigPat pat ty _)   = ppr pat <+> dcolon <+> ppr ty
197
198 pprOutPat (ConPat name ty [] [] [])
199   = ppr name
200
201 -- Kludge to get infix constructors to come out right
202 -- when ppr'ing desugar warnings.
203 pprOutPat (ConPat name ty tyvars dicts pats)
204   = getPprStyle $ \ sty ->
205     parens      $
206     case pats of
207       [p1,p2] 
208         | userStyle sty && isDataSymOcc (getOccName name) ->
209             hsep [ppr p1, ppr name, ppr p2]
210       _ -> hsep [ppr name, interppSP tyvars, interppSP dicts, interppSP pats]
211
212 pprOutPat (ListPat ty pats)      = brackets (interpp'SP pats)
213 pprOutPat (TuplePat pats boxity) = tupleParens boxity (interpp'SP pats)
214
215 pprOutPat (RecPat con ty tvs dicts rpats)
216   = hsep [ppr con, interppSP tvs, interppSP dicts, braces (hsep (punctuate comma (map (pp_rpat) rpats)))]
217   where
218     pp_rpat (v, _, True) = ppr v
219     pp_rpat (v, p, _)    = hsep [ppr v, char '=', ppr p]
220
221 pprOutPat (LitPat l ty)         = ppr l -- ToDo: print more
222 pprOutPat (NPat   l ty e)       = ppr l -- ToDo: print more
223 pprOutPat (NPlusKPat n k ty e1 e2)              -- ToDo: print more
224   = parens (hcat [ppr n, char '+', integer k])
225
226 pprOutPat (DictPat dicts methods)
227  = parens (sep [ptext SLIT("{-dict-}"),
228                   brackets (interpp'SP dicts),
229                   brackets (interpp'SP methods)])
230
231 \end{code}
232
233 %************************************************************************
234 %*                                                                      *
235 %* predicates for checking things about pattern-lists in EquationInfo   *
236 %*                                                                      *
237 %************************************************************************
238 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
239
240 Unlike in the Wadler chapter, where patterns are either ``variables''
241 or ``constructors,'' here we distinguish between:
242 \begin{description}
243 \item[unfailable:]
244 Patterns that cannot fail to match: variables, wildcards, and lazy
245 patterns.
246
247 These are the irrefutable patterns; the two other categories
248 are refutable patterns.
249
250 \item[constructor:]
251 A non-literal constructor pattern (see next category).
252
253 \item[literal patterns:]
254 At least the numeric ones may be overloaded.
255 \end{description}
256
257 A pattern is in {\em exactly one} of the above three categories; `as'
258 patterns are treated specially, of course.
259
260 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
261 \begin{code}
262 irrefutablePats :: [OutPat id] -> Bool
263 irrefutablePats pat_list = all irrefutablePat pat_list
264
265 irrefutablePat (AsPat   _ pat)  = irrefutablePat pat
266 irrefutablePat (WildPat _)      = True
267 irrefutablePat (VarPat  _)      = True
268 irrefutablePat (LazyPat _)      = True
269 irrefutablePat (DictPat ds ms)  = (length ds + length ms) <= 1
270 irrefutablePat other            = False
271
272 failureFreePat :: OutPat id -> Bool
273
274 failureFreePat (WildPat _)                = True
275 failureFreePat (VarPat _)                 = True
276 failureFreePat (LazyPat _)                = True
277 failureFreePat (AsPat _ pat)              = failureFreePat pat
278 failureFreePat (ConPat con tys _ _ pats)  = only_con con && all failureFreePat pats
279 failureFreePat (RecPat con _ _ _ fields)  = only_con con && and [ failureFreePat pat | (_,pat,_) <- fields ]
280 failureFreePat (ListPat _ _)              = False
281 failureFreePat (TuplePat pats _)          = all failureFreePat pats
282 failureFreePat (DictPat _ _)              = True
283 failureFreePat other_pat                  = False   -- Literals, NPat
284
285 only_con con = maybeToBool (maybeTyConSingleCon (dataConTyCon con))
286 \end{code}
287
288 \begin{code}
289 isWildPat (WildPat _) = True
290 isWildPat other       = False
291
292 patsAreAllCons :: [OutPat id] -> Bool
293 patsAreAllCons pat_list = all isConPat pat_list
294
295 isConPat (AsPat _ pat)          = isConPat pat
296 isConPat (ConPat _ _ _ _ _)     = True
297 isConPat (ListPat _ _)          = True
298 isConPat (TuplePat _ _)         = True
299 isConPat (RecPat _ _ _ _ _)     = True
300 isConPat (DictPat ds ms)        = (length ds + length ms) > 1
301 isConPat other                  = False
302
303 patsAreAllLits :: [OutPat id] -> Bool
304 patsAreAllLits pat_list = all isLitPat pat_list
305
306 isLitPat (AsPat _ pat)         = isLitPat pat
307 isLitPat (LitPat _ _)          = True
308 isLitPat (NPat   _ _ _)        = True
309 isLitPat (NPlusKPat _ _ _ _ _) = True
310 isLitPat other                 = False
311 \end{code}
312
313 This function @collectPatBinders@ works with the ``collectBinders''
314 functions for @HsBinds@, etc.  The order in which the binders are
315 collected is important; see @HsBinds.lhs@.
316
317 \begin{code}
318 collectPatBinders :: InPat a -> [a]
319 collectPatBinders pat = collect pat []
320
321 collectPatsBinders :: [InPat a] -> [a]
322 collectPatsBinders pats = foldr collect [] pats
323
324 collect WildPatIn                bndrs = bndrs
325 collect (VarPatIn var)           bndrs = var : bndrs
326 collect (LitPatIn _)             bndrs = bndrs
327 collect (SigPatIn pat _)         bndrs = collect pat bndrs
328 collect (LazyPatIn pat)          bndrs = collect pat bndrs
329 collect (AsPatIn a pat)          bndrs = a : collect pat bndrs
330 collect (NPlusKPatIn n _ _)      bndrs = n : bndrs
331 collect (NPatIn _)               bndrs = bndrs
332 collect (ConPatIn c pats)        bndrs = foldr collect bndrs pats
333 collect (ConOpPatIn p1 c f p2)   bndrs = collect p1 (collect p2 bndrs)
334 collect (ParPatIn  pat)          bndrs = collect pat bndrs
335 collect (ListPatIn pats)         bndrs = foldr collect bndrs pats
336 collect (TuplePatIn pats _)      bndrs = foldr collect bndrs pats
337 collect (RecPatIn c fields)      bndrs = foldr (\ (f,pat,_) bndrs -> collect pat bndrs) bndrs fields
338 -- Generics
339 collect (TypePatIn ty)           bndrs = bndrs
340 -- assume the type variables do not need to be bound
341 \end{code}
342
343 \begin{code}
344 collectSigTysFromPats :: [InPat name] -> [HsType name]
345 collectSigTysFromPats pats = foldr collect_pat [] pats
346
347 collectSigTysFromPat :: InPat name -> [HsType name]
348 collectSigTysFromPat pat = collect_pat pat []
349
350 collect_pat (SigPatIn pat ty)      acc = collect_pat pat (ty:acc)
351 collect_pat WildPatIn              acc = acc
352 collect_pat (VarPatIn var)         acc = acc
353 collect_pat (LitPatIn _)           acc = acc
354 collect_pat (LazyPatIn pat)        acc = collect_pat pat acc
355 collect_pat (AsPatIn a pat)        acc = collect_pat pat acc
356 collect_pat (NPatIn _)             acc = acc
357 collect_pat (NPlusKPatIn n _ _)    acc = acc
358 collect_pat (ConPatIn c pats)      acc = foldr collect_pat acc pats
359 collect_pat (ConOpPatIn p1 c f p2) acc = collect_pat p1 (collect_pat p2 acc)
360 collect_pat (ParPatIn  pat)        acc = collect_pat pat acc
361 collect_pat (ListPatIn pats)       acc = foldr collect_pat acc pats
362 collect_pat (TuplePatIn pats _)    acc = foldr collect_pat acc pats
363 collect_pat (RecPatIn c fields)    acc = foldr (\ (f,pat,_) acc -> collect_pat pat acc) acc fields
364 -- Generics
365 collect_pat (TypePatIn ty)         acc = ty:acc
366 \end{code}
367