506537517d755ebf7c45d1999361bdee433da744
[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 -fno-warn-incomplete-patterns #-}
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, hsPatNeedsParens,
25         patsAreAllCons, isConPat, isSigPat, isWildPat,
26         patsAreAllLits, isLitPat, isIrrefutableHsPat,
27
28         pprParendLPat
29     ) where
30
31 import {-# SOURCE #-} HsExpr            (SyntaxExpr, LHsExpr, pprLExpr)
32
33 -- friends:
34 import HsBinds
35 import HsLit
36 import HsTypes
37 import BasicTypes
38 -- others:
39 import Coercion
40 import PprCore          ( {- instance OutputableBndr TyVar -} )
41 import TysWiredIn
42 import Var
43 import DataCon
44 import TyCon
45 import Outputable       
46 import Type
47 import SrcLoc
48 import FastString
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 pattern
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 (tyvars only)
101         pat_dicts :: [id],              -- Ditto *coercion variables* and *dictionaries*
102                                         -- One reason for putting coercion variable here, I think,
103                                         --      is to ensure their kinds are zonked
104         pat_binds :: DictBinds id,      -- Bindings involving those dictionaries
105         pat_args  :: HsConPatDetails id,
106         pat_ty    :: Type               -- The type of the pattern
107     }
108
109         ------------ View patterns ---------------
110   | ViewPat       (LHsExpr id)      
111                   (LPat id)
112                   PostTcType        -- The overall type of the pattern
113                                     -- (= the argument type of the view function)
114                                     -- for hsPatType.
115
116         ------------ Quasiquoted patterns ---------------
117         -- See Note [Quasi-quote overview] in TcSplice
118   | QuasiQuotePat   (HsQuasiQuote id)
119
120         ------------ Literal and n+k patterns ---------------
121   | LitPat          HsLit               -- Used for *non-overloaded* literal patterns:
122                                         -- Int#, Char#, Int, Char, String, etc.
123
124   | NPat            (HsOverLit id)              -- ALWAYS positive
125                     (Maybe (SyntaxExpr id))     -- Just (Name of 'negate') for negative
126                                                 -- patterns, Nothing otherwise
127                     (SyntaxExpr id)             -- Equality checker, of type t->t->Bool
128
129   | NPlusKPat       (Located id)        -- n+k pattern
130                     (HsOverLit id)      -- It'll always be an HsIntegral
131                     (SyntaxExpr id)     -- (>=) function, of type t->t->Bool
132                     (SyntaxExpr id)     -- Name of '-' (see RnEnv.lookupSyntaxName)
133
134         ------------ Generics ---------------
135   | TypePat         (LHsType id)        -- Type pattern for generic definitions
136                                         -- e.g  f{| a+b |} = ...
137                                         -- These show up only in class declarations,
138                                         -- and should be a top-level pattern
139
140         ------------ Pattern type signatures ---------------
141   | SigPatIn        (LPat id)           -- Pattern with a type signature
142                     (LHsType id)
143
144   | SigPatOut       (LPat id)           -- Pattern with a type signature
145                     Type
146
147         ------------ Pattern coercions (translation only) ---------------
148   | CoPat       HsWrapper               -- If co::t1 -> t2, p::t2, 
149                                         -- then (CoPat co p) :: t1
150                 (Pat id)                -- Why not LPat?  Ans: existing locn will do
151                 Type                    -- Type of whole pattern, t1
152         -- During desugaring a (CoPat co pat) turns into a cast with 'co' on 
153         -- the scrutinee, followed by a match on 'pat'
154 \end{code}
155
156 HsConDetails is use for patterns/expressions *and* for data type declarations
157
158 \begin{code}
159 data HsConDetails arg rec
160   = PrefixCon [arg]             -- C p1 p2 p3
161   | RecCon    rec               -- C { x = p1, y = p2 }
162   | InfixCon  arg arg           -- p1 `C` p2
163
164 type HsConPatDetails id = HsConDetails (LPat id) (HsRecFields id (LPat id))
165
166 hsConPatArgs :: HsConPatDetails id -> [LPat id]
167 hsConPatArgs (PrefixCon ps)   = ps
168 hsConPatArgs (RecCon fs)      = map hsRecFieldArg (rec_flds fs)
169 hsConPatArgs (InfixCon p1 p2) = [p1,p2]
170 \end{code}
171
172 However HsRecFields is used only for patterns and expressions
173 (not data type declarations)
174
175 \begin{code}
176 data HsRecFields id arg         -- A bunch of record fields
177                                 --      { x = 3, y = True }
178         -- Used for both expressions and patterns
179   = HsRecFields { rec_flds   :: [HsRecField id arg],
180                   rec_dotdot :: Maybe Int }  -- Note [DotDot fields]
181
182 -- Note [DotDot fields]
183 -- ~~~~~~~~~~~~~~~~~~~~
184 -- The rec_dotdot field means this:
185 --   Nothing => the normal case
186 --   Just n  => the group uses ".." notation, 
187 --
188 -- In the latter case: 
189 --
190 --   *before* renamer: rec_flds are exactly the n user-written fields
191 --
192 --   *after* renamer:  rec_flds includes *all* fields, with 
193 --                     the first 'n' being the user-written ones
194 --                     and the remainder being 'filled in' implicitly
195
196 data HsRecField id arg = HsRecField {
197         hsRecFieldId  :: Located id,
198         hsRecFieldArg :: arg,
199         hsRecPun      :: Bool           -- Note [Punning]
200   }
201
202 -- Note [Punning]
203 -- ~~~~~~~~~~~~~~
204 -- If you write T { x, y = v+1 }, the HsRecFields will be
205 --      HsRecField x x True ...
206 --      HsRecField y (v+1) False ...
207 -- That is, for "punned" field x is expanded (in the renamer) 
208 -- to x=x; but with a punning flag so we can detect it later
209 -- (e.g. when pretty printing)
210 --
211 -- If the original field was qualified, we un-qualify it, thus
212 --    T { A.x } means T { A.x = x }
213
214 hsRecFields :: HsRecFields id arg -> [id]
215 hsRecFields rbinds = map (unLoc . hsRecFieldId) (rec_flds rbinds)
216 \end{code}
217
218 %************************************************************************
219 %*                                                                      *
220 %*              Printing patterns
221 %*                                                                      *
222 %************************************************************************
223
224 \begin{code}
225 instance (OutputableBndr name) => Outputable (Pat name) where
226     ppr = pprPat
227
228 pprPatBndr :: OutputableBndr name => name -> SDoc
229 pprPatBndr var                  -- Print with type info if -dppr-debug is on
230   = getPprStyle $ \ sty ->
231     if debugStyle sty then
232         parens (pprBndr LambdaBind var)         -- Could pass the site to pprPat
233                                                 -- but is it worth it?
234     else
235         ppr var
236
237 pprParendLPat :: (OutputableBndr name) => LPat name -> SDoc
238 pprParendLPat (L _ p) = pprParendPat p
239
240 pprParendPat :: (OutputableBndr name) => Pat name -> SDoc
241 pprParendPat p | patNeedsParens p = parens (pprPat p)
242                | otherwise        = pprPat p
243
244 patNeedsParens :: Pat name -> Bool
245 patNeedsParens (ConPatIn _ d)               = not (null (hsConPatArgs d))
246 patNeedsParens (ConPatOut { pat_args = d }) = not (null (hsConPatArgs d))
247 patNeedsParens (SigPatIn {})  = True
248 patNeedsParens (SigPatOut {}) = True
249 patNeedsParens (ViewPat {})   = True
250 patNeedsParens (CoPat {})     = True
251 patNeedsParens _              = False
252
253 pprPat :: (OutputableBndr name) => Pat name -> SDoc
254 pprPat (VarPat var)       = pprPatBndr var
255 pprPat (VarPatOut var bs) = pprPatBndr var <+> braces (ppr bs)
256 pprPat (WildPat _)        = char '_'
257 pprPat (LazyPat pat)      = char '~' <> pprParendLPat pat
258 pprPat (BangPat pat)      = char '!' <> pprParendLPat pat
259 pprPat (AsPat name pat)   = hcat [ppr name, char '@', pprParendLPat pat]
260 pprPat (ViewPat expr pat _) = hcat [pprLExpr expr, text " -> ", ppr pat]
261 pprPat (ParPat pat)         = parens (ppr pat)
262 pprPat (ListPat pats _)     = brackets (interpp'SP pats)
263 pprPat (PArrPat pats _)     = pabrackets (interpp'SP pats)
264 pprPat (TuplePat pats bx _) = tupleParens bx (interpp'SP pats)
265
266 pprPat (ConPatIn con details) = pprUserCon con details
267 pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts, 
268                     pat_binds = binds, pat_args = details })
269   = getPprStyle $ \ sty ->      -- Tiresome; in TcBinds.tcRhs we print out a 
270     if debugStyle sty then      -- typechecked Pat in an error message, 
271                                 -- and we want to make sure it prints nicely
272         ppr con <+> sep [ hsep (map pprPatBndr tvs) <+> hsep (map pprPatBndr dicts),
273                           pprLHsBinds binds, pprConArgs details]
274     else pprUserCon con details
275
276 pprPat (LitPat s)           = ppr s
277 pprPat (NPat l Nothing  _)  = ppr l
278 pprPat (NPat l (Just _) _)  = char '-' <> ppr l
279 pprPat (NPlusKPat n k _ _)  = hcat [ppr n, char '+', ppr k]
280 pprPat (QuasiQuotePat qq)   = ppr qq
281 pprPat (TypePat ty)         = ptext (sLit "{|") <> ppr ty <> ptext (sLit "|}")
282 pprPat (CoPat co pat _)     = pprHsWrapper (ppr pat) co
283 pprPat (SigPatIn pat ty)    = ppr pat <+> dcolon <+> ppr ty
284 pprPat (SigPatOut pat ty)   = ppr pat <+> dcolon <+> ppr ty
285
286 pprUserCon :: (Outputable con, OutputableBndr id) => con -> HsConPatDetails id -> SDoc
287 pprUserCon c (InfixCon p1 p2) = ppr p1 <+> ppr c <+> ppr p2
288 pprUserCon c details          = ppr c <+> pprConArgs details
289
290 pprConArgs ::  OutputableBndr id => HsConPatDetails id -> SDoc
291 pprConArgs (PrefixCon pats) = sep (map pprParendLPat pats)
292 pprConArgs (InfixCon p1 p2) = sep [pprParendLPat p1, pprParendLPat p2]
293 pprConArgs (RecCon rpats)   = ppr rpats
294
295 instance (OutputableBndr id, Outputable arg)
296       => Outputable (HsRecFields id arg) where
297   ppr (HsRecFields { rec_flds = flds, rec_dotdot = Nothing })
298         = braces (fsep (punctuate comma (map ppr flds)))
299   ppr (HsRecFields { rec_flds = flds, rec_dotdot = Just n })
300         = braces (fsep (punctuate comma (map ppr (take n flds) ++ [dotdot])))
301         where
302           dotdot = ptext (sLit "..") <+> ifPprDebug (ppr (drop n flds))
303
304 instance (OutputableBndr id, Outputable arg)
305       => Outputable (HsRecField id arg) where
306   ppr (HsRecField { hsRecFieldId = f, hsRecFieldArg = arg, 
307                     hsRecPun = pun })
308     = ppr f <+> (ppUnless pun $ equals <+> ppr arg)
309
310 -- add parallel array brackets around a document
311 --
312 pabrackets   :: SDoc -> SDoc
313 pabrackets p  = ptext (sLit "[:") <> p <> ptext (sLit ":]")
314 \end{code}
315
316
317 %************************************************************************
318 %*                                                                      *
319 %*              Building patterns
320 %*                                                                      *
321 %************************************************************************
322
323 \begin{code}
324 mkPrefixConPat :: DataCon -> [OutPat id] -> Type -> OutPat id
325 -- Make a vanilla Prefix constructor pattern
326 mkPrefixConPat dc pats ty 
327   = noLoc $ ConPatOut { pat_con = noLoc dc, pat_tvs = [], pat_dicts = [],
328                         pat_binds = emptyLHsBinds, pat_args = PrefixCon pats, 
329                         pat_ty = ty }
330
331 mkNilPat :: Type -> OutPat id
332 mkNilPat ty = mkPrefixConPat nilDataCon [] ty
333
334 mkCharLitPat :: Char -> OutPat id
335 mkCharLitPat c = mkPrefixConPat charDataCon [noLoc $ LitPat (HsCharPrim c)] charTy
336
337 mkCoPat :: HsWrapper -> Pat id -> Type -> Pat id
338 mkCoPat co pat ty
339   | isIdHsWrapper co = pat
340   | otherwise        = CoPat co pat ty
341
342 mkCoPatCoI :: CoercionI -> Pat id -> Type -> Pat id
343 mkCoPatCoI IdCo     pat _  = pat
344 mkCoPatCoI (ACo co) pat ty = mkCoPat (WpCast co) pat ty
345 \end{code}
346
347
348 %************************************************************************
349 %*                                                                      *
350 %* Predicates for checking things about pattern-lists in EquationInfo   *
351 %*                                                                      *
352 %************************************************************************
353
354 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
355
356 Unlike in the Wadler chapter, where patterns are either ``variables''
357 or ``constructors,'' here we distinguish between:
358 \begin{description}
359 \item[unfailable:]
360 Patterns that cannot fail to match: variables, wildcards, and lazy
361 patterns.
362
363 These are the irrefutable patterns; the two other categories
364 are refutable patterns.
365
366 \item[constructor:]
367 A non-literal constructor pattern (see next category).
368
369 \item[literal patterns:]
370 At least the numeric ones may be overloaded.
371 \end{description}
372
373 A pattern is in {\em exactly one} of the above three categories; `as'
374 patterns are treated specially, of course.
375
376 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
377 \begin{code}
378 isWildPat :: Pat id -> Bool
379 isWildPat (WildPat _) = True
380 isWildPat _           = False
381
382 patsAreAllCons :: [Pat id] -> Bool
383 patsAreAllCons pat_list = all isConPat pat_list
384
385 isConPat :: Pat id -> Bool
386 isConPat (AsPat _ pat)   = isConPat (unLoc pat)
387 isConPat (ConPatIn {})   = True
388 isConPat (ConPatOut {})  = True
389 isConPat (ListPat {})    = True
390 isConPat (PArrPat {})    = True
391 isConPat (TuplePat {})   = True
392 isConPat _               = False
393
394 isSigPat :: Pat id -> Bool
395 isSigPat (SigPatIn _ _)  = True
396 isSigPat (SigPatOut _ _) = True
397 isSigPat _               = False
398
399 patsAreAllLits :: [Pat id] -> Bool
400 patsAreAllLits pat_list = all isLitPat pat_list
401
402 isLitPat :: Pat id -> Bool
403 isLitPat (AsPat _ pat)          = isLitPat (unLoc pat)
404 isLitPat (LitPat _)             = True
405 isLitPat (NPat _ _ _)           = True
406 isLitPat (NPlusKPat _ _ _ _)    = True
407 isLitPat _                      = False
408
409 isBangHsBind :: HsBind id -> Bool
410 -- In this module because HsPat is above HsBinds in the import graph
411 isBangHsBind (PatBind { pat_lhs = L _ (BangPat _) }) = True
412 isBangHsBind _                                       = False
413
414 isIrrefutableHsPat :: OutputableBndr id => LPat id -> Bool
415 -- (isIrrefutableHsPat p) is true if matching against p cannot fail,
416 -- in the sense of falling through to the next pattern.
417 --      (NB: this is not quite the same as the (silly) defn
418 --      in 3.17.2 of the Haskell 98 report.)
419 -- 
420 -- isIrrefutableHsPat returns False if it's in doubt; specifically
421 -- on a ConPatIn it doesn't know the size of the constructor family
422 -- But if it returns True, the pattern is definitely irrefutable
423 isIrrefutableHsPat pat
424   = go pat
425   where
426     go (L _ pat) = go1 pat
427
428     go1 (WildPat {})        = True
429     go1 (VarPat {})         = True
430     go1 (VarPatOut {})      = True
431     go1 (LazyPat {})        = True
432     go1 (BangPat pat)       = go pat
433     go1 (CoPat _ pat _)     = go1 pat
434     go1 (ParPat pat)        = go pat
435     go1 (AsPat _ pat)       = go pat
436     go1 (ViewPat _ pat _)   = go pat
437     go1 (SigPatIn pat _)    = go pat
438     go1 (SigPatOut pat _)   = go pat
439     go1 (TuplePat pats _ _) = all go pats
440     go1 (ListPat {})        = False
441     go1 (PArrPat {})        = False     -- ?
442
443     go1 (ConPatIn {})       = False     -- Conservative
444     go1 (ConPatOut{ pat_con = L _ con, pat_args = details }) 
445         =  isProductTyCon (dataConTyCon con)
446         && all go (hsConPatArgs details)
447
448     go1 (LitPat {})    = False
449     go1 (NPat {})      = False
450     go1 (NPlusKPat {}) = False
451
452     go1 (QuasiQuotePat {}) = urk pat    -- Gotten rid of by renamer, before
453                                         -- isIrrefutablePat is called
454     go1 (TypePat {})       = urk pat
455
456     urk pat = pprPanic "isIrrefutableHsPat:" (ppr pat)
457
458 hsPatNeedsParens :: Pat a -> Bool
459 hsPatNeedsParens (WildPat {})        = False
460 hsPatNeedsParens (VarPat {})         = False
461 hsPatNeedsParens (VarPatOut {})      = True
462 hsPatNeedsParens (LazyPat {})        = False
463 hsPatNeedsParens (BangPat {})        = False
464 hsPatNeedsParens (CoPat {})          = True
465 hsPatNeedsParens (ParPat {})         = False
466 hsPatNeedsParens (AsPat {})          = False
467 hsPatNeedsParens (ViewPat {})        = True
468 hsPatNeedsParens (SigPatIn {})       = True
469 hsPatNeedsParens (SigPatOut {})      = True
470 hsPatNeedsParens (TuplePat {})       = False
471 hsPatNeedsParens (ListPat {})        = False
472 hsPatNeedsParens (PArrPat {})        = False    
473 hsPatNeedsParens (ConPatIn _ ds)     = conPatNeedsParens ds
474 hsPatNeedsParens (ConPatOut {})      = True
475 hsPatNeedsParens (LitPat {})         = False
476 hsPatNeedsParens (NPat {})           = False
477 hsPatNeedsParens (NPlusKPat {})      = True
478 hsPatNeedsParens (QuasiQuotePat {})  = True
479 hsPatNeedsParens (TypePat {})        = False
480
481 conPatNeedsParens :: HsConDetails a b -> Bool
482 conPatNeedsParens (PrefixCon args) = not (null args)
483 conPatNeedsParens (InfixCon {})    = False
484 conPatNeedsParens (RecCon {})      = False
485 \end{code}
486