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