[project @ 2002-06-05 14:07:47 by simonpj]
[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, collectOutPatBinders, 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           -- Always positive
58                     (Maybe Name)        -- Just (Name of 'negate') for negative
59                                         -- patterns, Nothing otherwise
60                                         --  (see RnEnv.lookupSyntaxName)
61
62   | NPlusKPatIn     name                -- n+k pattern
63                     HsOverLit           -- It'll always be an HsIntegral
64                     Name                -- Name of '-' (see RnEnv.lookupSyntaxName)
65
66   -- We preserve prefix negation and parenthesis for the precedence parser.
67
68   | ParPatIn        (InPat name)        -- parenthesised pattern
69
70   | ListPatIn       [InPat name]        -- syntactic list
71                                         -- must have >= 1 elements
72   | PArrPatIn       [InPat name]        -- syntactic parallel array
73                                         -- must have >= 1 elements
74   | TuplePatIn      [InPat name] Boxity -- tuple (boxed?)
75
76   | RecPatIn        name                -- record
77                     [(name, InPat name, Bool)]  -- True <=> source used punning
78
79 -- Generics
80   | TypePatIn       (HsType name)       -- Type pattern for generic definitions
81                                         -- e.g  f{| a+b |} = ...
82                                         -- These show up only in class 
83                                         -- declarations,
84                                         -- and should be a top-level pattern
85
86 -- /Generics
87
88 data OutPat id
89   = WildPat         Type        -- wild card
90   | VarPat          id          -- variable (type is in the Id)
91   | LazyPat         (OutPat id) -- lazy pattern
92   | AsPat           id          -- as pattern
93                     (OutPat id)
94
95   | SigPat          (OutPat id) -- Pattern p
96                     Type        -- Type, t, of the whole pattern
97                     (HsExpr id (OutPat id))
98                                 -- Coercion function,
99                                 -- of type t -> typeof(p)
100
101   | ListPat                     -- Syntactic list
102                     Type        -- The type of the elements
103                     [OutPat id]
104   | PArrPat                     -- Syntactic parallel array
105                     Type        -- The type of the elements
106                     [OutPat id]
107
108   | TuplePat        [OutPat id] -- Tuple
109                     Boxity
110                                 -- UnitPat is TuplePat []
111
112   | ConPat          DataCon
113                     Type        -- the type of the pattern
114                     [TyVar]     -- Existentially bound type variables
115                     [id]        -- Ditto dictionaries
116                     [OutPat id]
117
118   -- ConOpPats are only used on the input side
119
120   | RecPat          DataCon             -- Record constructor
121                     Type                -- The type of the pattern
122                     [TyVar]             -- Existentially bound type variables
123                     [id]                -- Ditto dictionaries
124                     [(Id, OutPat id, Bool)]     -- True <=> source used punning
125
126   | LitPat          -- Used for *non-overloaded* literal patterns:
127                     -- Int#, Char#, Int, Char, String, etc.
128                     HsLit
129                     Type                -- Type of pattern
130
131   | NPat            -- Used for literal patterns where there's an equality function to call
132                     HsLit                       -- The literal is retained so that
133                                                 -- the desugarer can readily identify
134                                                 -- equations with identical literal-patterns
135                                                 -- Always HsInteger, HsRat or HsString.
136                                                 -- *Unlike* NPatIn, for negative literals, the
137                                                 --      literal is acutally negative!
138                     Type                        -- Type of pattern, t
139                     (HsExpr id (OutPat id))     -- Of type t -> Bool; detects match
140
141   | NPlusKPat       id
142                     Integer
143                     Type                        -- Type of pattern, t
144                     (HsExpr id (OutPat id))     -- Of type t -> Bool; detects match
145                     (HsExpr id (OutPat id))     -- Of type t -> t; subtracts k
146
147   | DictPat         -- Used when destructing Dictionaries with an explicit case
148                     [id]                        -- superclass dicts
149                     [id]                        -- methods
150 \end{code}
151
152 Now name in Inpat is not need to be in NAmedThing to be Outputable.
153 Needed by ../deSugar/Check.lhs
154
155 JJQC-2-12-97
156
157 \begin{code}
158 instance (Outputable name) => Outputable (InPat name) where
159     ppr = pprInPat
160
161 pprInPat :: (Outputable name) => InPat name -> SDoc
162
163 pprInPat (WildPatIn)          = char '_'
164 pprInPat (VarPatIn var)       = ppr var
165 pprInPat (LitPatIn s)         = ppr s
166 pprInPat (SigPatIn pat ty)    = ppr pat <+> dcolon <+> ppr ty
167 pprInPat (LazyPatIn pat)      = char '~' <> ppr pat
168 pprInPat (AsPatIn name pat)   = parens (hcat [ppr name, char '@', ppr pat])
169 pprInPat (ParPatIn pat)       = parens (pprInPat pat)
170 pprInPat (ListPatIn pats)     = brackets (interpp'SP pats)
171 pprInPat (PArrPatIn pats)     = pabrackets (interpp'SP pats)
172 pprInPat (TuplePatIn pats bx) = tupleParens bx (interpp'SP pats)
173 pprInPat (NPlusKPatIn n k _)  = parens (hcat [ppr n, char '+', ppr k])
174 pprInPat (NPatIn l _)         = ppr l
175
176 pprInPat (ConPatIn c pats)
177   | null pats = ppr c
178   | otherwise = hsep [ppr c, interppSP pats] -- inner ParPats supply the necessary parens.
179
180 pprInPat (ConOpPatIn pat1 op fixity pat2)
181  = hsep [ppr pat1, ppr op, ppr pat2] -- ParPats put in parens
182
183         -- ToDo: use pprSym to print op (but this involves fiddling various
184         -- contexts & I'm lazy...); *PatIns are *rarely* printed anyway... (WDP)
185
186 pprInPat (RecPatIn con rpats)
187   = hsep [ppr con, braces (hsep (punctuate comma (map (pp_rpat) rpats)))]
188   where
189     pp_rpat (v, _, True) = ppr v
190     pp_rpat (v, p, _)    = hsep [ppr v, char '=', ppr p]
191
192 pprInPat (TypePatIn ty) = ptext SLIT("{|") <> ppr ty <> ptext SLIT("|}")
193
194 -- add parallel array brackets around a document
195 --
196 pabrackets   :: SDoc -> SDoc
197 pabrackets p  = ptext SLIT("[:") <> p <> ptext SLIT(":]")
198 \end{code}
199
200 \begin{code}
201 instance (NamedThing id, Outputable id) => Outputable (OutPat id) where
202     ppr = pprOutPat
203 \end{code}
204
205 \begin{code}
206 pprOutPat (WildPat ty)  = char '_'
207 pprOutPat (VarPat var)  = ppr var
208 pprOutPat (LazyPat pat) = hcat [char '~', ppr pat]
209 pprOutPat (AsPat name pat)
210   = parens (hcat [ppr name, char '@', ppr pat])
211
212 pprOutPat (SigPat pat ty _)   = ppr pat <+> dcolon <+> ppr ty
213
214 pprOutPat (ConPat name ty [] [] [])
215   = ppr name
216
217 -- Kludge to get infix constructors to come out right
218 -- when ppr'ing desugar warnings.
219 pprOutPat (ConPat name ty tyvars dicts pats)
220   = getPprStyle $ \ sty ->
221     parens      $
222     case pats of
223       [p1,p2] 
224         | userStyle sty && isDataSymOcc (getOccName name) ->
225             hsep [ppr p1, ppr name, ppr p2]
226       _ -> hsep [ppr name, interppSP tyvars, interppSP dicts, interppSP pats]
227
228 pprOutPat (ListPat ty pats)      = brackets (interpp'SP pats)
229 pprOutPat (PArrPat ty pats)      = pabrackets (interpp'SP pats)
230 pprOutPat (TuplePat pats boxity) = tupleParens boxity (interpp'SP pats)
231
232 pprOutPat (RecPat con ty tvs dicts rpats)
233   = hsep [ppr con, interppSP tvs, interppSP dicts, braces (hsep (punctuate comma (map (pp_rpat) rpats)))]
234   where
235     pp_rpat (v, _, True) = ppr v
236     pp_rpat (v, p, _)    = hsep [ppr v, char '=', ppr p]
237
238 pprOutPat (LitPat l ty)         = ppr l -- ToDo: print more
239 pprOutPat (NPat   l ty e)       = ppr l -- ToDo: print more
240 pprOutPat (NPlusKPat n k ty e1 e2)              -- ToDo: print more
241   = parens (hcat [ppr n, char '+', integer k])
242
243 pprOutPat (DictPat dicts methods)
244  = parens (sep [ptext SLIT("{-dict-}"),
245                   brackets (interpp'SP dicts),
246                   brackets (interpp'SP methods)])
247
248 \end{code}
249
250 %************************************************************************
251 %*                                                                      *
252 %* predicates for checking things about pattern-lists in EquationInfo   *
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 irrefutablePats :: [OutPat id] -> Bool
280 irrefutablePats pat_list = all irrefutablePat pat_list
281
282 irrefutablePat (AsPat   _ pat)  = irrefutablePat pat
283 irrefutablePat (WildPat _)      = True
284 irrefutablePat (VarPat  _)      = True
285 irrefutablePat (LazyPat _)      = True
286 irrefutablePat (DictPat ds ms)  = (length ds + length ms) <= 1
287 irrefutablePat other            = False
288
289 failureFreePat :: OutPat id -> Bool
290
291 failureFreePat (WildPat _)                = True
292 failureFreePat (VarPat _)                 = True
293 failureFreePat (LazyPat _)                = True
294 failureFreePat (AsPat _ pat)              = failureFreePat pat
295 failureFreePat (ConPat con tys _ _ pats)  = only_con con && all failureFreePat pats
296 failureFreePat (RecPat con _ _ _ fields)  = only_con con && and [ failureFreePat pat | (_,pat,_) <- fields ]
297 failureFreePat (ListPat _ _)              = False
298 failureFreePat (PArrPat _ _)              = False
299 failureFreePat (TuplePat pats _)          = all failureFreePat pats
300 failureFreePat (DictPat _ _)              = True
301 failureFreePat other_pat                  = False   -- Literals, NPat
302
303 only_con con = maybeToBool (maybeTyConSingleCon (dataConTyCon con))
304 \end{code}
305
306 \begin{code}
307 isWildPat (WildPat _) = True
308 isWildPat other       = False
309
310 patsAreAllCons :: [OutPat id] -> Bool
311 patsAreAllCons pat_list = all isConPat pat_list
312
313 isConPat (AsPat _ pat)          = isConPat pat
314 isConPat (ConPat _ _ _ _ _)     = True
315 isConPat (ListPat _ _)          = True
316 isConPat (PArrPat _ _)          = True
317 isConPat (TuplePat _ _)         = True
318 isConPat (RecPat _ _ _ _ _)     = True
319 isConPat (DictPat ds ms)        = (length ds + length ms) > 1
320 isConPat other                  = False
321
322 patsAreAllLits :: [OutPat id] -> Bool
323 patsAreAllLits pat_list = all isLitPat pat_list
324
325 isLitPat (AsPat _ pat)         = isLitPat pat
326 isLitPat (LitPat _ _)          = True
327 isLitPat (NPat   _ _ _)        = True
328 isLitPat (NPlusKPat _ _ _ _ _) = True
329 isLitPat other                 = False
330 \end{code}
331
332 This function @collectPatBinders@ works with the ``collectBinders''
333 functions for @HsBinds@, etc.  The order in which the binders are
334 collected is important; see @HsBinds.lhs@.
335
336 \begin{code}
337 collectPatBinders :: InPat a -> [a]
338 collectPatBinders pat = collect pat []
339
340 collectOutPatBinders :: OutPat a -> [a]
341 collectOutPatBinders pat = collectOut pat []
342
343 collectPatsBinders :: [InPat a] -> [a]
344 collectPatsBinders pats = foldr collect [] pats
345
346 collect WildPatIn                bndrs = bndrs
347 collect (VarPatIn var)           bndrs = var : bndrs
348 collect (LitPatIn _)             bndrs = bndrs
349 collect (SigPatIn pat _)         bndrs = collect pat bndrs
350 collect (LazyPatIn pat)          bndrs = collect pat bndrs
351 collect (AsPatIn a pat)          bndrs = a : collect pat bndrs
352 collect (NPlusKPatIn n _ _)      bndrs = n : bndrs
353 collect (NPatIn _ _)             bndrs = bndrs
354 collect (ConPatIn c pats)        bndrs = foldr collect bndrs pats
355 collect (ConOpPatIn p1 c f p2)   bndrs = collect p1 (collect p2 bndrs)
356 collect (ParPatIn  pat)          bndrs = collect pat bndrs
357 collect (ListPatIn pats)         bndrs = foldr collect bndrs pats
358 collect (PArrPatIn pats)         bndrs = foldr collect bndrs pats
359 collect (TuplePatIn pats _)      bndrs = foldr collect bndrs pats
360 collect (RecPatIn c fields)      bndrs = foldr (\ (f,pat,_) bndrs -> collect pat bndrs) bndrs fields
361 -- Generics
362 collect (TypePatIn ty)           bndrs = bndrs
363 -- assume the type variables do not need to be bound
364
365 -- collect the bounds *value* variables in renamed patterns; type variables
366 -- are *not* collected
367 --
368 collectOut (WildPat _)              bndrs = bndrs
369 collectOut (VarPat var)             bndrs = var : bndrs
370 collectOut (LazyPat pat)            bndrs = collectOut pat bndrs
371 collectOut (AsPat a pat)            bndrs = a : collectOut pat bndrs
372 collectOut (ListPat _ pats)         bndrs = foldr collectOut bndrs pats
373 collectOut (PArrPat _ pats)         bndrs = foldr collectOut bndrs pats
374 collectOut (TuplePat pats _)        bndrs = foldr collectOut bndrs pats
375 collectOut (ConPat _ _ _ ds pats)   bndrs = ds ++ foldr collectOut bndrs pats
376 collectOut (RecPat _ _ _ ds fields) bndrs = ds ++ foldr comb bndrs fields
377   where
378     comb (_, pat, _) bndrs = collectOut pat bndrs
379 collectOut (LitPat _ _)             bndrs = bndrs
380 collectOut (NPat _ _ _)             bndrs = bndrs
381 collectOut (NPlusKPat n _ _ _ _)    bndrs = n : bndrs
382 collectOut (DictPat ids1 ids2)      bndrs = ids1 ++ ids2 ++ bndrs
383 \end{code}
384
385 \begin{code}
386 collectSigTysFromPats :: [InPat name] -> [HsType name]
387 collectSigTysFromPats pats = foldr collect_pat [] pats
388
389 collectSigTysFromPat :: InPat name -> [HsType name]
390 collectSigTysFromPat pat = collect_pat pat []
391
392 collect_pat (SigPatIn pat ty)      acc = collect_pat pat (ty:acc)
393 collect_pat WildPatIn              acc = acc
394 collect_pat (VarPatIn var)         acc = acc
395 collect_pat (LitPatIn _)           acc = acc
396 collect_pat (LazyPatIn pat)        acc = collect_pat pat acc
397 collect_pat (AsPatIn a pat)        acc = collect_pat pat acc
398 collect_pat (NPatIn _ _)           acc = acc
399 collect_pat (NPlusKPatIn n _ _)    acc = acc
400 collect_pat (ConPatIn c pats)      acc = foldr collect_pat acc pats
401 collect_pat (ConOpPatIn p1 c f p2) acc = collect_pat p1 (collect_pat p2 acc)
402 collect_pat (ParPatIn  pat)        acc = collect_pat pat acc
403 collect_pat (ListPatIn pats)       acc = foldr collect_pat acc pats
404 collect_pat (PArrPatIn pats)       acc = foldr collect_pat acc pats
405 collect_pat (TuplePatIn pats _)    acc = foldr collect_pat acc pats
406 collect_pat (RecPatIn c fields)    acc = foldr (\ (f,pat,_) acc -> collect_pat pat acc) acc fields
407 -- Generics
408 collect_pat (TypePatIn ty)         acc = ty:acc
409 \end{code}
410