[project @ 2002-05-27 16:13:42 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                     Type                        -- Type of pattern, t
137                     (HsExpr id (OutPat id))     -- Of type t -> Bool; detects match
138
139   | NPlusKPat       id
140                     Integer
141                     Type                        -- Type of pattern, t
142                     (HsExpr id (OutPat id))     -- Of type t -> Bool; detects match
143                     (HsExpr id (OutPat id))     -- Of type t -> t; subtracts k
144
145   | DictPat         -- Used when destructing Dictionaries with an explicit case
146                     [id]                        -- superclass dicts
147                     [id]                        -- methods
148 \end{code}
149
150 Now name in Inpat is not need to be in NAmedThing to be Outputable.
151 Needed by ../deSugar/Check.lhs
152
153 JJQC-2-12-97
154
155 \begin{code}
156 instance (Outputable name) => Outputable (InPat name) where
157     ppr = pprInPat
158
159 pprInPat :: (Outputable name) => InPat name -> SDoc
160
161 pprInPat (WildPatIn)          = char '_'
162 pprInPat (VarPatIn var)       = ppr var
163 pprInPat (LitPatIn s)         = ppr s
164 pprInPat (SigPatIn pat ty)    = ppr pat <+> dcolon <+> ppr ty
165 pprInPat (LazyPatIn pat)      = char '~' <> ppr pat
166 pprInPat (AsPatIn name pat)   = parens (hcat [ppr name, char '@', ppr pat])
167 pprInPat (ParPatIn pat)       = parens (pprInPat pat)
168 pprInPat (ListPatIn pats)     = brackets (interpp'SP pats)
169 pprInPat (PArrPatIn pats)     = pabrackets (interpp'SP pats)
170 pprInPat (TuplePatIn pats bx) = tupleParens bx (interpp'SP pats)
171 pprInPat (NPlusKPatIn n k _)  = parens (hcat [ppr n, char '+', ppr k])
172 pprInPat (NPatIn l _)         = ppr l
173
174 pprInPat (ConPatIn c pats)
175   | null pats = ppr c
176   | otherwise = hsep [ppr c, interppSP pats] -- inner ParPats supply the necessary parens.
177
178 pprInPat (ConOpPatIn pat1 op fixity pat2)
179  = hsep [ppr pat1, ppr op, ppr pat2] -- ParPats put in parens
180
181         -- ToDo: use pprSym to print op (but this involves fiddling various
182         -- contexts & I'm lazy...); *PatIns are *rarely* printed anyway... (WDP)
183
184 pprInPat (RecPatIn con rpats)
185   = hsep [ppr con, braces (hsep (punctuate comma (map (pp_rpat) rpats)))]
186   where
187     pp_rpat (v, _, True) = ppr v
188     pp_rpat (v, p, _)    = hsep [ppr v, char '=', ppr p]
189
190 pprInPat (TypePatIn ty) = ptext SLIT("{|") <> ppr ty <> ptext SLIT("|}")
191
192 -- add parallel array brackets around a document
193 --
194 pabrackets   :: SDoc -> SDoc
195 pabrackets p  = ptext SLIT("[:") <> p <> ptext SLIT(":]")
196 \end{code}
197
198 \begin{code}
199 instance (NamedThing id, Outputable id) => Outputable (OutPat id) where
200     ppr = pprOutPat
201 \end{code}
202
203 \begin{code}
204 pprOutPat (WildPat ty)  = char '_'
205 pprOutPat (VarPat var)  = ppr var
206 pprOutPat (LazyPat pat) = hcat [char '~', ppr pat]
207 pprOutPat (AsPat name pat)
208   = parens (hcat [ppr name, char '@', ppr pat])
209
210 pprOutPat (SigPat pat ty _)   = ppr pat <+> dcolon <+> ppr ty
211
212 pprOutPat (ConPat name ty [] [] [])
213   = ppr name
214
215 -- Kludge to get infix constructors to come out right
216 -- when ppr'ing desugar warnings.
217 pprOutPat (ConPat name ty tyvars dicts pats)
218   = getPprStyle $ \ sty ->
219     parens      $
220     case pats of
221       [p1,p2] 
222         | userStyle sty && isDataSymOcc (getOccName name) ->
223             hsep [ppr p1, ppr name, ppr p2]
224       _ -> hsep [ppr name, interppSP tyvars, interppSP dicts, interppSP pats]
225
226 pprOutPat (ListPat ty pats)      = brackets (interpp'SP pats)
227 pprOutPat (PArrPat ty pats)      = pabrackets (interpp'SP pats)
228 pprOutPat (TuplePat pats boxity) = tupleParens boxity (interpp'SP pats)
229
230 pprOutPat (RecPat con ty tvs dicts rpats)
231   = hsep [ppr con, interppSP tvs, interppSP dicts, braces (hsep (punctuate comma (map (pp_rpat) rpats)))]
232   where
233     pp_rpat (v, _, True) = ppr v
234     pp_rpat (v, p, _)    = hsep [ppr v, char '=', ppr p]
235
236 pprOutPat (LitPat l ty)         = ppr l -- ToDo: print more
237 pprOutPat (NPat   l ty e)       = ppr l -- ToDo: print more
238 pprOutPat (NPlusKPat n k ty e1 e2)              -- ToDo: print more
239   = parens (hcat [ppr n, char '+', integer k])
240
241 pprOutPat (DictPat dicts methods)
242  = parens (sep [ptext SLIT("{-dict-}"),
243                   brackets (interpp'SP dicts),
244                   brackets (interpp'SP methods)])
245
246 \end{code}
247
248 %************************************************************************
249 %*                                                                      *
250 %* predicates for checking things about pattern-lists in EquationInfo   *
251 %*                                                                      *
252 %************************************************************************
253 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
254
255 Unlike in the Wadler chapter, where patterns are either ``variables''
256 or ``constructors,'' here we distinguish between:
257 \begin{description}
258 \item[unfailable:]
259 Patterns that cannot fail to match: variables, wildcards, and lazy
260 patterns.
261
262 These are the irrefutable patterns; the two other categories
263 are refutable patterns.
264
265 \item[constructor:]
266 A non-literal constructor pattern (see next category).
267
268 \item[literal patterns:]
269 At least the numeric ones may be overloaded.
270 \end{description}
271
272 A pattern is in {\em exactly one} of the above three categories; `as'
273 patterns are treated specially, of course.
274
275 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
276 \begin{code}
277 irrefutablePats :: [OutPat id] -> Bool
278 irrefutablePats pat_list = all irrefutablePat pat_list
279
280 irrefutablePat (AsPat   _ pat)  = irrefutablePat pat
281 irrefutablePat (WildPat _)      = True
282 irrefutablePat (VarPat  _)      = True
283 irrefutablePat (LazyPat _)      = True
284 irrefutablePat (DictPat ds ms)  = (length ds + length ms) <= 1
285 irrefutablePat other            = False
286
287 failureFreePat :: OutPat id -> Bool
288
289 failureFreePat (WildPat _)                = True
290 failureFreePat (VarPat _)                 = True
291 failureFreePat (LazyPat _)                = True
292 failureFreePat (AsPat _ pat)              = failureFreePat pat
293 failureFreePat (ConPat con tys _ _ pats)  = only_con con && all failureFreePat pats
294 failureFreePat (RecPat con _ _ _ fields)  = only_con con && and [ failureFreePat pat | (_,pat,_) <- fields ]
295 failureFreePat (ListPat _ _)              = False
296 failureFreePat (PArrPat _ _)              = False
297 failureFreePat (TuplePat pats _)          = all failureFreePat pats
298 failureFreePat (DictPat _ _)              = True
299 failureFreePat other_pat                  = False   -- Literals, NPat
300
301 only_con con = maybeToBool (maybeTyConSingleCon (dataConTyCon con))
302 \end{code}
303
304 \begin{code}
305 isWildPat (WildPat _) = True
306 isWildPat other       = False
307
308 patsAreAllCons :: [OutPat id] -> Bool
309 patsAreAllCons pat_list = all isConPat pat_list
310
311 isConPat (AsPat _ pat)          = isConPat pat
312 isConPat (ConPat _ _ _ _ _)     = True
313 isConPat (ListPat _ _)          = True
314 isConPat (PArrPat _ _)          = True
315 isConPat (TuplePat _ _)         = True
316 isConPat (RecPat _ _ _ _ _)     = True
317 isConPat (DictPat ds ms)        = (length ds + length ms) > 1
318 isConPat other                  = False
319
320 patsAreAllLits :: [OutPat id] -> Bool
321 patsAreAllLits pat_list = all isLitPat pat_list
322
323 isLitPat (AsPat _ pat)         = isLitPat pat
324 isLitPat (LitPat _ _)          = True
325 isLitPat (NPat   _ _ _)        = True
326 isLitPat (NPlusKPat _ _ _ _ _) = True
327 isLitPat other                 = False
328 \end{code}
329
330 This function @collectPatBinders@ works with the ``collectBinders''
331 functions for @HsBinds@, etc.  The order in which the binders are
332 collected is important; see @HsBinds.lhs@.
333
334 \begin{code}
335 collectPatBinders :: InPat a -> [a]
336 collectPatBinders pat = collect pat []
337
338 collectOutPatBinders :: OutPat a -> [a]
339 collectOutPatBinders pat = collectOut pat []
340
341 collectPatsBinders :: [InPat a] -> [a]
342 collectPatsBinders pats = foldr collect [] pats
343
344 collect WildPatIn                bndrs = bndrs
345 collect (VarPatIn var)           bndrs = var : bndrs
346 collect (LitPatIn _)             bndrs = bndrs
347 collect (SigPatIn pat _)         bndrs = collect pat bndrs
348 collect (LazyPatIn pat)          bndrs = collect pat bndrs
349 collect (AsPatIn a pat)          bndrs = a : collect pat bndrs
350 collect (NPlusKPatIn n _ _)      bndrs = n : bndrs
351 collect (NPatIn _ _)             bndrs = bndrs
352 collect (ConPatIn c pats)        bndrs = foldr collect bndrs pats
353 collect (ConOpPatIn p1 c f p2)   bndrs = collect p1 (collect p2 bndrs)
354 collect (ParPatIn  pat)          bndrs = collect pat bndrs
355 collect (ListPatIn pats)         bndrs = foldr collect bndrs pats
356 collect (PArrPatIn pats)         bndrs = foldr collect bndrs pats
357 collect (TuplePatIn pats _)      bndrs = foldr collect bndrs pats
358 collect (RecPatIn c fields)      bndrs = foldr (\ (f,pat,_) bndrs -> collect pat bndrs) bndrs fields
359 -- Generics
360 collect (TypePatIn ty)           bndrs = bndrs
361 -- assume the type variables do not need to be bound
362
363 -- collect the bounds *value* variables in renamed patterns; type variables
364 -- are *not* collected
365 --
366 collectOut (WildPat _)              bndrs = bndrs
367 collectOut (VarPat var)             bndrs = var : bndrs
368 collectOut (LazyPat pat)            bndrs = collectOut pat bndrs
369 collectOut (AsPat a pat)            bndrs = a : collectOut pat bndrs
370 collectOut (ListPat _ pats)         bndrs = foldr collectOut bndrs pats
371 collectOut (PArrPat _ pats)         bndrs = foldr collectOut bndrs pats
372 collectOut (TuplePat pats _)        bndrs = foldr collectOut bndrs pats
373 collectOut (ConPat _ _ _ ds pats)   bndrs = ds ++ foldr collectOut bndrs pats
374 collectOut (RecPat _ _ _ ds fields) bndrs = ds ++ foldr comb bndrs fields
375   where
376     comb (_, pat, _) bndrs = collectOut pat bndrs
377 collectOut (LitPat _ _)             bndrs = bndrs
378 collectOut (NPat _ _ _)             bndrs = bndrs
379 collectOut (NPlusKPat n _ _ _ _)    bndrs = n : bndrs
380 collectOut (DictPat ids1 ids2)      bndrs = ids1 ++ ids2 ++ bndrs
381 \end{code}
382
383 \begin{code}
384 collectSigTysFromPats :: [InPat name] -> [HsType name]
385 collectSigTysFromPats pats = foldr collect_pat [] pats
386
387 collectSigTysFromPat :: InPat name -> [HsType name]
388 collectSigTysFromPat pat = collect_pat pat []
389
390 collect_pat (SigPatIn pat ty)      acc = collect_pat pat (ty:acc)
391 collect_pat WildPatIn              acc = acc
392 collect_pat (VarPatIn var)         acc = acc
393 collect_pat (LitPatIn _)           acc = acc
394 collect_pat (LazyPatIn pat)        acc = collect_pat pat acc
395 collect_pat (AsPatIn a pat)        acc = collect_pat pat acc
396 collect_pat (NPatIn _ _)           acc = acc
397 collect_pat (NPlusKPatIn n _ _)    acc = acc
398 collect_pat (ConPatIn c pats)      acc = foldr collect_pat acc pats
399 collect_pat (ConOpPatIn p1 c f p2) acc = collect_pat p1 (collect_pat p2 acc)
400 collect_pat (ParPatIn  pat)        acc = collect_pat pat acc
401 collect_pat (ListPatIn pats)       acc = foldr collect_pat acc pats
402 collect_pat (PArrPatIn pats)       acc = foldr collect_pat acc pats
403 collect_pat (TuplePatIn pats _)    acc = foldr collect_pat acc pats
404 collect_pat (RecPatIn c fields)    acc = foldr (\ (f,pat,_) acc -> collect_pat pat acc) acc fields
405 -- Generics
406 collect_pat (TypePatIn ty)         acc = ty:acc
407 \end{code}
408