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