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