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