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