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