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