Fix a bug in MatchCon, and clarify what dataConInstOrigArgTys does
[ghc-hetmet.git] / compiler / hsSyn / HsPat.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5 \section[PatSyntax]{Abstract Haskell syntax---patterns}
6
7 \begin{code}
8 module HsPat (
9         Pat(..), InPat, OutPat, LPat, 
10         
11         HsConDetails(..), hsConArgs,
12         HsRecField(..), mkRecField,
13
14         mkPrefixConPat, mkCharLitPat, mkNilPat, mkCoPat,
15
16         isBangHsBind,   
17         patsAreAllCons, isConPat, isSigPat, isWildPat,
18         patsAreAllLits, isLitPat, isIrrefutableHsPat
19     ) where
20
21 #include "HsVersions.h"
22
23
24 import {-# SOURCE #-} HsExpr            ( SyntaxExpr )
25
26 -- friends:
27 import HsBinds
28 import HsLit
29 import HsTypes
30 import HsDoc
31 import BasicTypes
32 -- others:
33 import PprCore          ( {- instance OutputableBndr TyVar -} )
34 import TysWiredIn
35 import Var
36 import DataCon
37 import TyCon
38 import Outputable       
39 import Type
40 import SrcLoc
41 \end{code}
42
43
44 \begin{code}
45 type InPat id  = LPat id        -- No 'Out' constructors
46 type OutPat id = LPat id        -- No 'In' constructors
47
48 type LPat id = Located (Pat id)
49
50 data Pat id
51   =     ------------ Simple patterns ---------------
52     WildPat     PostTcType              -- Wild card
53         -- The sole reason for a type on a WildPat is to
54         -- support hsPatType :: Pat Id -> Type
55
56   | VarPat      id                      -- Variable
57   | VarPatOut   id (DictBinds id)       -- Used only for overloaded Ids; the 
58                                         -- bindings give its overloaded instances
59   | LazyPat     (LPat id)               -- Lazy pattern
60   | AsPat       (Located id) (LPat id)  -- As pattern
61   | ParPat      (LPat id)               -- Parenthesised pattern
62   | BangPat     (LPat id)               -- Bang patterng
63
64         ------------ Lists, tuples, arrays ---------------
65   | ListPat     [LPat id]               -- Syntactic list
66                 PostTcType              -- The type of the elements
67                     
68   | TuplePat    [LPat id]               -- Tuple
69                 Boxity                  -- UnitPat is TuplePat []
70                 PostTcType
71         -- You might think that the PostTcType was redundant, but it's essential
72         --      data T a where
73         --        T1 :: Int -> T Int
74         --      f :: (T a, a) -> Int
75         --      f (T1 x, z) = z
76         -- When desugaring, we must generate
77         --      f = /\a. \v::a.  case v of (t::T a, w::a) ->
78         --                       case t of (T1 (x::Int)) -> 
79         -- Note the (w::a), NOT (w::Int), because we have not yet
80         -- refined 'a' to Int.  So we must know that the second component
81         -- of the tuple is of type 'a' not Int.  See selectMatchVar
82
83   | PArrPat     [LPat id]               -- Syntactic parallel array
84                 PostTcType              -- The type of the elements
85
86         ------------ Constructor patterns ---------------
87   | ConPatIn    (Located id)
88                 (HsConDetails id (LPat id))
89
90   | ConPatOut {
91         pat_con   :: Located DataCon,
92         pat_tvs   :: [TyVar],           -- Existentially bound type variables
93                                         --   including any bound coercion variables
94         pat_dicts :: [id],              -- Ditto dictionaries
95         pat_binds :: DictBinds id,      -- Bindings involving those dictionaries
96         pat_args  :: HsConDetails id (LPat id),
97         pat_ty    :: Type               -- The type of the pattern
98     }
99
100         ------------ Literal and n+k patterns ---------------
101   | LitPat          HsLit               -- Used for *non-overloaded* literal patterns:
102                                         -- Int#, Char#, Int, Char, String, etc.
103
104   | NPat            (HsOverLit id)              -- ALWAYS positive
105                     (Maybe (SyntaxExpr id))     -- Just (Name of 'negate') for negative
106                                                 -- patterns, Nothing otherwise
107                     (SyntaxExpr id)             -- Equality checker, of type t->t->Bool
108                     PostTcType                  -- Type of the pattern
109
110   | NPlusKPat       (Located id)        -- n+k pattern
111                     (HsOverLit id)      -- It'll always be an HsIntegral
112                     (SyntaxExpr id)     -- (>=) function, of type t->t->Bool
113                     (SyntaxExpr id)     -- Name of '-' (see RnEnv.lookupSyntaxName)
114
115         ------------ Generics ---------------
116   | TypePat         (LHsType id)        -- Type pattern for generic definitions
117                                         -- e.g  f{| a+b |} = ...
118                                         -- These show up only in class declarations,
119                                         -- and should be a top-level pattern
120
121         ------------ Pattern type signatures ---------------
122   | SigPatIn        (LPat id)           -- Pattern with a type signature
123                     (LHsType id)
124
125   | SigPatOut       (LPat id)           -- Pattern with a type signature
126                     Type
127
128         ------------ Dictionary patterns (translation only) ---------------
129   | DictPat         -- Used when destructing Dictionaries with an explicit case
130                     [id]                -- Superclass dicts
131                     [id]                -- Methods
132
133         ------------ Pattern coercions (translation only) ---------------
134   | CoPat       HsWrapper               -- If co::t1 -> t2, p::t2, 
135                                         -- then (CoPat co p) :: t1
136                 (Pat id)                -- Why not LPat?  Ans: existing locn will do
137                 Type                    -- Type of whole pattern, t1
138         -- During desugaring a (CoPat co pat) turns into a cast with 'co' on 
139         -- the scrutinee, followed by a match on 'pat'
140 \end{code}
141
142 HsConDetails is use both for patterns and for data type declarations
143
144 \begin{code}
145 data HsConDetails id arg
146   = PrefixCon [arg]               -- C p1 p2 p3
147   | RecCon    [HsRecField id arg] -- C { x = p1, y = p2 }
148   | InfixCon  arg arg             -- p1 `C` p2
149
150 data HsRecField id arg = HsRecField {
151         hsRecFieldId  :: Located id,
152         hsRecFieldArg :: arg,
153         hsRecFieldDoc :: Maybe (LHsDoc id)
154 }
155
156 mkRecField id arg = HsRecField id arg Nothing
157
158 hsConArgs :: HsConDetails id arg -> [arg]
159 hsConArgs (PrefixCon ps)   = ps
160 hsConArgs (RecCon fs)      = map hsRecFieldArg fs
161 hsConArgs (InfixCon p1 p2) = [p1,p2]
162 \end{code}
163
164
165 %************************************************************************
166 %*                                                                      *
167 %*              Printing patterns
168 %*                                                                      *
169 %************************************************************************
170
171 \begin{code}
172 instance (OutputableBndr name) => Outputable (Pat name) where
173     ppr = pprPat
174
175 pprPatBndr :: OutputableBndr name => name -> SDoc
176 pprPatBndr var                  -- Print with type info if -dppr-debug is on
177   = getPprStyle $ \ sty ->
178     if debugStyle sty then
179         parens (pprBndr LambdaBind var)         -- Could pass the site to pprPat
180                                                 -- but is it worth it?
181     else
182         ppr var
183
184 pprPat :: (OutputableBndr name) => Pat name -> SDoc
185 pprPat (VarPat var)       = pprPatBndr var
186 pprPat (VarPatOut var bs) = parens (pprPatBndr var <+> braces (ppr bs))
187 pprPat (WildPat _)        = char '_'
188 pprPat (LazyPat pat)      = char '~' <> ppr pat
189 pprPat (BangPat pat)      = char '!' <> ppr pat
190 pprPat (AsPat name pat)   = parens (hcat [ppr name, char '@', ppr pat])
191 pprPat (ParPat pat)       = parens (ppr pat)
192 pprPat (ListPat pats _)     = brackets (interpp'SP pats)
193 pprPat (PArrPat pats _)     = pabrackets (interpp'SP pats)
194 pprPat (TuplePat pats bx _) = tupleParens bx (interpp'SP pats)
195
196 pprPat (ConPatIn con details) = pprUserCon con details
197 pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts, 
198                     pat_binds = binds, pat_args = details })
199   = getPprStyle $ \ sty ->      -- Tiresome; in TcBinds.tcRhs we print out a 
200     if debugStyle sty then      -- typechecked Pat in an error message, 
201                                 -- and we want to make sure it prints nicely
202         ppr con <+> sep [ hsep (map pprPatBndr tvs) <+> hsep (map pprPatBndr dicts),
203                           pprLHsBinds binds, pprConArgs details]
204     else pprUserCon con details
205
206 pprPat (LitPat s)             = ppr s
207 pprPat (NPat l Nothing  _ _)  = ppr l
208 pprPat (NPat l (Just _) _ _)  = char '-' <> ppr l
209 pprPat (NPlusKPat n k _ _)    = hcat [ppr n, char '+', ppr k]
210 pprPat (TypePat ty)           = ptext SLIT("{|") <> ppr ty <> ptext SLIT("|}")
211 pprPat (CoPat co pat _)       = parens (pprHsWrapper (ppr pat) co)
212 pprPat (SigPatIn pat ty)      = ppr pat <+> dcolon <+> ppr ty
213 pprPat (SigPatOut pat ty)     = ppr pat <+> dcolon <+> ppr ty
214 pprPat (DictPat ds ms)        = parens (sep [ptext SLIT("{-dict-}"),
215                                              brackets (interpp'SP ds),
216                                              brackets (interpp'SP ms)])
217
218 pprUserCon c (InfixCon p1 p2) = ppr p1 <+> ppr c <+> ppr p2
219 pprUserCon c details          = ppr c <+> pprConArgs details
220
221 pprConArgs (PrefixCon pats) = interppSP pats
222 pprConArgs (InfixCon p1 p2) = interppSP [p1,p2]
223 pprConArgs (RecCon rpats)   = braces (hsep (punctuate comma (map (pp_rpat) rpats)))
224                             where
225                               pp_rpat (HsRecField v p _d) = 
226                                 hsep [ppr v, char '=', ppr p]
227
228 -- add parallel array brackets around a document
229 --
230 pabrackets   :: SDoc -> SDoc
231 pabrackets p  = ptext SLIT("[:") <> p <> ptext SLIT(":]")
232
233 instance (OutputableBndr id, Outputable arg) =>
234          Outputable (HsRecField id arg) where
235     ppr (HsRecField n ty doc) = ppr n <+> dcolon <+> ppr ty <+> ppr_mbDoc doc
236 \end{code}
237
238
239 %************************************************************************
240 %*                                                                      *
241 %*              Building patterns
242 %*                                                                      *
243 %************************************************************************
244
245 \begin{code}
246 mkPrefixConPat :: DataCon -> [OutPat id] -> Type -> OutPat id
247 -- Make a vanilla Prefix constructor pattern
248 mkPrefixConPat dc pats ty 
249   = noLoc $ ConPatOut { pat_con = noLoc dc, pat_tvs = [], pat_dicts = [],
250                         pat_binds = emptyLHsBinds, pat_args = PrefixCon pats, 
251                         pat_ty = ty }
252
253 mkNilPat :: Type -> OutPat id
254 mkNilPat ty = mkPrefixConPat nilDataCon [] ty
255
256 mkCharLitPat :: Char -> OutPat id
257 mkCharLitPat c = mkPrefixConPat charDataCon [noLoc $ LitPat (HsCharPrim c)] charTy
258
259 mkCoPat :: HsWrapper -> OutPat id -> Type -> OutPat id
260 mkCoPat co lpat@(L loc pat) ty
261   | isIdHsWrapper co = lpat
262   | otherwise = L loc (CoPat co pat ty)
263 \end{code}
264
265
266 %************************************************************************
267 %*                                                                      *
268 %* Predicates for checking things about pattern-lists in EquationInfo   *
269 %*                                                                      *
270 %************************************************************************
271
272 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
273
274 Unlike in the Wadler chapter, where patterns are either ``variables''
275 or ``constructors,'' here we distinguish between:
276 \begin{description}
277 \item[unfailable:]
278 Patterns that cannot fail to match: variables, wildcards, and lazy
279 patterns.
280
281 These are the irrefutable patterns; the two other categories
282 are refutable patterns.
283
284 \item[constructor:]
285 A non-literal constructor pattern (see next category).
286
287 \item[literal patterns:]
288 At least the numeric ones may be overloaded.
289 \end{description}
290
291 A pattern is in {\em exactly one} of the above three categories; `as'
292 patterns are treated specially, of course.
293
294 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
295 \begin{code}
296 isWildPat (WildPat _) = True
297 isWildPat other       = False
298
299 patsAreAllCons :: [Pat id] -> Bool
300 patsAreAllCons pat_list = all isConPat pat_list
301
302 isConPat (AsPat _ pat)   = isConPat (unLoc pat)
303 isConPat (ConPatIn {})   = True
304 isConPat (ConPatOut {})  = True
305 isConPat (ListPat {})    = True
306 isConPat (PArrPat {})    = True
307 isConPat (TuplePat {})   = True
308 isConPat (DictPat ds ms) = (length ds + length ms) > 1
309 isConPat other           = False
310
311 isSigPat (SigPatIn _ _)  = True
312 isSigPat (SigPatOut _ _) = True
313 isSigPat other           = False
314
315 patsAreAllLits :: [Pat id] -> Bool
316 patsAreAllLits pat_list = all isLitPat pat_list
317
318 isLitPat (AsPat _ pat)          = isLitPat (unLoc pat)
319 isLitPat (LitPat _)             = True
320 isLitPat (NPat _ _ _ _)         = True
321 isLitPat (NPlusKPat _ _ _ _)    = True
322 isLitPat other                  = False
323
324 isBangHsBind :: HsBind id -> Bool
325 -- In this module because HsPat is above HsBinds in the import graph
326 isBangHsBind (PatBind { pat_lhs = L _ (BangPat p) }) = True
327 isBangHsBind bind                                    = False
328
329 isIrrefutableHsPat :: LPat id -> Bool
330 -- This function returns False if it's in doubt; specifically
331 -- on a ConPatIn it doesn't know the size of the constructor family
332 -- But if it returns True, the pattern is definitely irrefutable
333 isIrrefutableHsPat pat
334   = go pat
335   where
336     go (L _ pat)         = go1 pat
337
338     go1 (WildPat _)         = True
339     go1 (VarPat _)          = True
340     go1 (VarPatOut _ _)     = True
341     go1 (LazyPat pat)       = True
342     go1 (BangPat pat)       = go pat
343     go1 (CoPat _ pat _)     = go1 pat
344     go1 (ParPat pat)        = go pat
345     go1 (AsPat _ pat)       = go pat
346     go1 (SigPatIn pat _)    = go pat
347     go1 (SigPatOut pat _)   = go pat
348     go1 (TuplePat pats _ _) = all go pats
349     go1 (ListPat pats _)    = False
350     go1 (PArrPat pats _)    = False     -- ?
351
352     go1 (ConPatIn _ _) = False  -- Conservative
353     go1 (ConPatOut{ pat_con = L _ con, pat_args = details }) 
354         =  isProductTyCon (dataConTyCon con)
355         && all go (hsConArgs details)
356
357     go1 (LitPat _)         = False
358     go1 (NPat _ _ _ _)     = False
359     go1 (NPlusKPat _ _ _ _) = False
360
361     go1 (TypePat _)   = panic "isIrrefutableHsPat: type pattern"
362     go1 (DictPat _ _) = panic "isIrrefutableHsPat: type pattern"
363 \end{code}
364