da42d1ce89068a8e76977d673a5ec1d601f8c258
[ghc-hetmet.git] / ghc / compiler / hsSyn / HsPat.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[PatSyntax]{Abstract Haskell syntax---patterns}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module HsPat (
10         InPat(..),
11         OutPat(..),
12
13         irrefutablePat, irrefutablePats,
14         failureFreePat,
15         patsAreAllCons, isConPat,
16         patsAreAllLits, isLitPat,
17         collectPatBinders
18     ) where
19
20 IMP_Ubiq()
21
22 -- friends:
23 import HsBasic                  ( HsLit, Fixity )
24 IMPORT_DELOOPER(HsLoop)         ( HsExpr )
25
26 -- others:
27 import Id               ( dataConTyCon, GenId )
28 import Maybes           ( maybeToBool )
29 import Name             ( pprSym, pprNonSym )
30 import Outputable       ( interppSP, interpp'SP, ifPprShowAll )
31 import PprStyle         ( PprStyle(..) )
32 import Pretty
33 import TyCon            ( maybeTyConSingleCon )
34 import PprType          ( GenType )
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   | ConPatIn        name                -- constructed type
47                     [InPat name]
48   | ConOpPatIn      (InPat name)
49                     name
50                     Fixity              -- c.f. OpApp in HsExpr
51                     (InPat name)
52
53   -- We preserve prefix negation and parenthesis for the precedence parser.
54
55   | NegPatIn        (InPat name)        -- negated pattern
56   | ParPatIn        (InPat name)        -- parenthesised pattern
57
58   | ListPatIn       [InPat name]        -- syntactic list
59                                         -- must have >= 1 elements
60   | TuplePatIn      [InPat name]        -- tuple
61
62   | RecPatIn        name                -- record
63                     [(name, InPat name, Bool)]  -- True <=> source used punning
64
65 data OutPat tyvar uvar id
66   = WildPat         (GenType tyvar uvar)        -- wild card
67
68   | VarPat          id                          -- variable (type is in the Id)
69
70   | LazyPat         (OutPat tyvar uvar id)      -- lazy pattern
71
72   | AsPat           id                          -- as pattern
73                     (OutPat tyvar uvar id)
74
75   | ConPat          Id                          -- Constructor is always an Id
76                     (GenType tyvar uvar)        -- the type of the pattern
77                     [OutPat tyvar uvar id]
78
79   | ConOpPat        (OutPat tyvar uvar id)      -- just a special case...
80                     Id
81                     (OutPat tyvar uvar id)
82                     (GenType tyvar uvar)
83   | ListPat                                     -- syntactic list
84                     (GenType tyvar uvar)        -- the type of the elements
85                     [OutPat tyvar uvar id]
86
87   | TuplePat        [OutPat tyvar uvar id]      -- tuple
88                                                 -- UnitPat is TuplePat []
89
90   | RecPat          Id                          -- record constructor
91                     (GenType tyvar uvar)        -- the type of the pattern
92                     [(Id, OutPat tyvar uvar id, Bool)]  -- True <=> source used punning
93
94   | LitPat          -- Used for *non-overloaded* literal patterns:
95                     -- Int#, Char#, Int, Char, String, etc.
96                     HsLit
97                     (GenType tyvar uvar)        -- type of pattern
98
99   | NPat            -- Used for *overloaded* literal patterns
100                     HsLit                       -- the literal is retained so that
101                                                 -- the desugarer can readily identify
102                                                 -- equations with identical literal-patterns
103                     (GenType tyvar uvar)        -- type of pattern, t
104                     (HsExpr tyvar uvar id (OutPat tyvar uvar id))
105                                                 -- of type t -> Bool; detects match
106
107   | DictPat         -- Used when destructing Dictionaries with an explicit case
108                     [id]                        -- superclass dicts
109                     [id]                        -- methods
110 \end{code}
111
112 \begin{code}
113 instance (Outputable name, NamedThing name) => Outputable (InPat name) where
114     ppr = pprInPat
115
116 pprInPat :: (Outputable name, NamedThing name) => PprStyle -> InPat name -> Pretty
117
118 pprInPat sty (WildPatIn)        = ppStr "_"
119 pprInPat sty (VarPatIn var)     = ppr sty var
120 pprInPat sty (LitPatIn s)       = ppr sty s
121 pprInPat sty (LazyPatIn pat)    = ppBeside (ppChar '~') (ppr sty pat)
122 pprInPat sty (AsPatIn name pat)
123     = ppBesides [ppLparen, ppr sty name, ppChar '@', ppr sty pat, ppRparen]
124
125 pprInPat sty (ConPatIn c pats)
126  = if null pats then
127       ppr sty c
128    else
129       ppCat [ppr sty c, interppSP sty pats] -- ParPats put in the parens
130
131 pprInPat sty (ConOpPatIn pat1 op fixity pat2)
132  = ppCat [ppr sty pat1, ppr sty op, ppr sty pat2] -- ParPats put in parens
133
134         -- ToDo: use pprSym to print op (but this involves fiddling various
135         -- contexts & I'm lazy...); *PatIns are *rarely* printed anyway... (WDP)
136
137 pprInPat sty (NegPatIn pat)
138   = let
139         pp_pat = pprInPat sty pat
140     in
141     ppBeside (ppChar '-') (
142     case pat of
143       LitPatIn _ -> pp_pat
144       _          -> ppParens pp_pat
145     )
146
147 pprInPat sty (ParPatIn pat)
148   = ppParens (pprInPat sty pat)
149
150 pprInPat sty (ListPatIn pats)
151   = ppBesides [ppLbrack, interpp'SP sty pats, ppRbrack]
152 pprInPat sty (TuplePatIn pats)
153   = ppParens (interpp'SP sty pats)
154
155 pprInPat sty (RecPatIn con rpats)
156   = ppCat [ppr sty con, ppCurlies (ppIntersperse pp'SP (map (pp_rpat sty) rpats))]
157   where
158     pp_rpat PprForUser (v, _, True) = ppr PprForUser v
159     pp_rpat sty        (v, p, _)    = ppCat [ppr sty v, ppStr "=", ppr sty p]
160 \end{code}
161
162 \begin{code}
163 instance (Eq tyvar, Outputable tyvar, Eq uvar, Outputable uvar, Outputable id)
164        => Outputable (OutPat tyvar uvar id) where
165     ppr = pprOutPat
166 \end{code}
167
168 \begin{code}
169 pprOutPat sty (WildPat ty)      = ppChar '_'
170 pprOutPat sty (VarPat var)      = ppr sty var
171 pprOutPat sty (LazyPat pat)     = ppBesides [ppChar '~', ppr sty pat]
172 pprOutPat sty (AsPat name pat)
173   = ppBesides [ppLparen, ppr sty name, ppChar '@', ppr sty pat, ppRparen]
174
175 pprOutPat sty (ConPat name ty [])
176   = ppBeside (ppr sty name)
177         (ifPprShowAll sty (pprConPatTy sty ty))
178
179 pprOutPat sty (ConPat name ty pats)
180   = ppBesides [ppLparen, ppr sty name, ppSP,
181          interppSP sty pats, ppRparen,
182          ifPprShowAll sty (pprConPatTy sty ty) ]
183
184 pprOutPat sty (ConOpPat pat1 op pat2 ty)
185   = ppBesides [ppLparen, ppr sty pat1, ppSP, pprSym sty op, ppSP, ppr sty pat2, ppRparen]
186
187 pprOutPat sty (ListPat ty pats)
188   = ppBesides [ppLbrack, interpp'SP sty pats, ppRbrack]
189 pprOutPat sty (TuplePat pats)
190   = ppParens (interpp'SP sty pats)
191
192 pprOutPat sty (RecPat con ty rpats)
193   = ppBesides [ppr sty con, ppCurlies (ppIntersperse pp'SP (map (pp_rpat sty) rpats))]
194   where
195     pp_rpat PprForUser (v, _, True) = ppr PprForUser v
196     pp_rpat sty (v, p, _)           = ppCat [ppr sty v, ppStr "=", ppr sty p]
197
198 pprOutPat sty (LitPat l ty)     = ppr sty l     -- ToDo: print more
199 pprOutPat sty (NPat   l ty e)   = ppr sty l     -- ToDo: print more
200
201 pprOutPat sty (DictPat dicts methods)
202  = ppSep [ppBesides [ppLparen, ppPStr SLIT("{-dict-}")],
203           ppBracket (interpp'SP sty dicts),
204           ppBesides [ppBracket (interpp'SP sty methods), ppRparen]]
205
206 pprConPatTy sty ty
207  = ppParens (ppr sty ty)
208 \end{code}
209
210 %************************************************************************
211 %*                                                                      *
212 %* predicates for checking things about pattern-lists in EquationInfo   *
213 %*                                                                      *
214 %************************************************************************
215 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
216
217 Unlike in the Wadler chapter, where patterns are either ``variables''
218 or ``constructors,'' here we distinguish between:
219 \begin{description}
220 \item[unfailable:]
221 Patterns that cannot fail to match: variables, wildcards, and lazy
222 patterns.
223
224 These are the irrefutable patterns; the two other categories
225 are refutable patterns.
226
227 \item[constructor:]
228 A non-literal constructor pattern (see next category).
229
230 \item[literal patterns:]
231 At least the numeric ones may be overloaded.
232 \end{description}
233
234 A pattern is in {\em exactly one} of the above three categories; `as'
235 patterns are treated specially, of course.
236
237 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
238 \begin{code}
239 irrefutablePats :: [OutPat a b c] -> Bool
240 irrefutablePats pat_list = all irrefutablePat pat_list
241
242 irrefutablePat (AsPat   _ pat)  = irrefutablePat pat
243 irrefutablePat (WildPat _)      = True
244 irrefutablePat (VarPat  _)      = True
245 irrefutablePat (LazyPat _)      = True
246 irrefutablePat (DictPat ds ms)  = (length ds + length ms) <= 1
247 irrefutablePat other            = False
248
249 failureFreePat :: OutPat a b c -> Bool
250
251 failureFreePat (WildPat _)                = True
252 failureFreePat (VarPat _)                 = True
253 failureFreePat (LazyPat _)                = True
254 failureFreePat (AsPat _ pat)              = failureFreePat pat
255 failureFreePat (ConPat con tys pats)      = only_con con && all failureFreePat pats
256 failureFreePat (ConOpPat pat1 con pat2 _) = only_con con && failureFreePat pat1 && failureFreePat pat1
257 failureFreePat (RecPat con _ fields)      = only_con con && and [ failureFreePat pat | (_,pat,_) <- fields ]
258 failureFreePat (ListPat _ _)              = False
259 failureFreePat (TuplePat pats)            = all failureFreePat pats
260 failureFreePat (DictPat _ _)              = True
261 failureFreePat other_pat                  = False   -- Literals, NPat
262
263 only_con con = maybeToBool (maybeTyConSingleCon (dataConTyCon con))
264 \end{code}
265
266 \begin{code}
267 patsAreAllCons :: [OutPat a b c] -> Bool
268 patsAreAllCons pat_list = all isConPat pat_list
269
270 isConPat (AsPat _ pat)          = isConPat pat
271 isConPat (ConPat _ _ _)         = True
272 isConPat (ConOpPat _ _ _ _)     = True
273 isConPat (ListPat _ _)          = True
274 isConPat (TuplePat _)           = True
275 isConPat (RecPat _ _ _)         = True
276 isConPat (DictPat ds ms)        = (length ds + length ms) > 1
277 isConPat other                  = False
278
279 patsAreAllLits :: [OutPat a b c] -> Bool
280 patsAreAllLits pat_list = all isLitPat pat_list
281
282 isLitPat (AsPat _ pat)  = isLitPat pat
283 isLitPat (LitPat _ _)   = True
284 isLitPat (NPat   _ _ _) = True
285 isLitPat other          = False
286 \end{code}
287
288 This function @collectPatBinders@ works with the ``collectBinders''
289 functions for @HsBinds@, etc.  The order in which the binders are
290 collected is important; see @HsBinds.lhs@.
291 \begin{code}
292 collectPatBinders :: InPat a -> [a]
293
294 collectPatBinders WildPatIn              = []
295 collectPatBinders (VarPatIn var)         = [var]
296 collectPatBinders (LitPatIn _)           = []
297 collectPatBinders (LazyPatIn pat)        = collectPatBinders pat
298 collectPatBinders (AsPatIn a pat)        = a : collectPatBinders pat
299 collectPatBinders (ConPatIn c pats)      = concat (map collectPatBinders pats)
300 collectPatBinders (ConOpPatIn p1 c f p2) = collectPatBinders p1 ++ collectPatBinders p2
301 collectPatBinders (NegPatIn  pat)        = collectPatBinders pat
302 collectPatBinders (ParPatIn  pat)        = collectPatBinders pat
303 collectPatBinders (ListPatIn pats)       = concat (map collectPatBinders pats)
304 collectPatBinders (TuplePatIn pats)      = concat (map collectPatBinders pats)
305 collectPatBinders (RecPatIn c fields)    = concat (map (\ (f,pat,_) -> collectPatBinders pat) fields)
306 \end{code}