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