Add quasi-quotation, courtesy of Geoffrey Mainland
[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         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 HsDoc
40 import BasicTypes
41 -- others:
42 import Coercion
43 import PprCore          ( {- instance OutputableBndr TyVar -} )
44 import TysWiredIn
45 import Var
46 import DataCon
47 import TyCon
48 import Outputable       
49 import Type
50 import SrcLoc
51 import FastString
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 \end{code}
158
159 HsConDetails is use for patterns/expressions *and* for data type declarations
160
161 \begin{code}
162 data HsConDetails arg rec
163   = PrefixCon [arg]             -- C p1 p2 p3
164   | RecCon    rec               -- C { x = p1, y = p2 }
165   | InfixCon  arg arg           -- p1 `C` p2
166
167 type HsConPatDetails id = HsConDetails (LPat id) (HsRecFields id (LPat id))
168
169 hsConPatArgs :: HsConPatDetails id -> [LPat id]
170 hsConPatArgs (PrefixCon ps)   = ps
171 hsConPatArgs (RecCon fs)      = map hsRecFieldArg (rec_flds fs)
172 hsConPatArgs (InfixCon p1 p2) = [p1,p2]
173 \end{code}
174
175 However HsRecFields is used only for patterns and expressions
176 (not data type declarations)
177
178 \begin{code}
179 data HsRecFields id arg         -- A bunch of record fields
180                                 --      { x = 3, y = True }
181         -- Used for both expressiona and patterns
182   = HsRecFields { rec_flds   :: [HsRecField id arg],
183                   rec_dotdot :: Maybe Int }
184         -- Nothing => the normal case
185         -- Just n  => the group uses ".." notation, 
186         --              and the first n elts of rec_flds
187         --              were the user-written ones
188         -- (In the latter case, the remaining elts of
189         --  rec_flds are the non-user-written ones)
190
191 data HsRecField id arg = HsRecField {
192         hsRecFieldId  :: Located id,
193         hsRecFieldArg :: arg,
194         hsRecPun      :: Bool           -- Note [Punning]
195   }
196
197 -- Note [Punning]
198 -- ~~~~~~~~~~~~~~
199 -- If you write T { x, y = v+1 }, the HsRecFields will be
200 --      HsRecField x x True ...
201 --      HsRecField y (v+1) False ...
202 -- That is, for "punned" field x is immediately expanded to x=x
203 -- but with a punning flag so we can detect it later
204 -- (e.g. when pretty printing)
205
206 hsRecFields :: HsRecFields id arg -> [id]
207 hsRecFields rbinds = map (unLoc . hsRecFieldId) (rec_flds rbinds)
208 \end{code}
209
210 \begin{code}
211 data HsQuasiQuote id = HsQuasiQuote 
212                        id
213                        id
214                        SrcSpan
215                        FastString
216 \end{code}
217
218
219 %************************************************************************
220 %*                                                                      *
221 %*              Printing patterns
222 %*                                                                      *
223 %************************************************************************
224
225 \begin{code}
226 instance (OutputableBndr name) => Outputable (Pat name) where
227     ppr = pprPat
228
229 pprPatBndr :: OutputableBndr name => name -> SDoc
230 pprPatBndr var                  -- Print with type info if -dppr-debug is on
231   = getPprStyle $ \ sty ->
232     if debugStyle sty then
233         parens (pprBndr LambdaBind var)         -- Could pass the site to pprPat
234                                                 -- but is it worth it?
235     else
236         ppr var
237
238 pprPat :: (OutputableBndr name) => Pat name -> SDoc
239 pprPat (VarPat var)       = pprPatBndr var
240 pprPat (VarPatOut var bs) = parens (pprPatBndr var <+> braces (ppr bs))
241 pprPat (WildPat _)        = char '_'
242 pprPat (LazyPat pat)      = char '~' <> ppr pat
243 pprPat (BangPat pat)      = char '!' <> ppr pat
244 pprPat (AsPat name pat)   = parens (hcat [ppr name, char '@', ppr pat])
245 pprPat (ViewPat expr pat _)   = parens (hcat [pprLExpr expr, text " -> ", ppr pat])
246 pprPat (ParPat pat)       = parens (ppr pat)
247 pprPat (ListPat pats _)     = brackets (interpp'SP pats)
248 pprPat (PArrPat pats _)     = pabrackets (interpp'SP pats)
249 pprPat (TuplePat pats bx _) = tupleParens bx (interpp'SP pats)
250
251 pprPat (ConPatIn con details) = pprUserCon con details
252 pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts, 
253                     pat_binds = binds, pat_args = details })
254   = getPprStyle $ \ sty ->      -- Tiresome; in TcBinds.tcRhs we print out a 
255     if debugStyle sty then      -- typechecked Pat in an error message, 
256                                 -- and we want to make sure it prints nicely
257         ppr con <+> sep [ hsep (map pprPatBndr tvs) <+> hsep (map pprPatBndr dicts),
258                           pprLHsBinds binds, pprConArgs details]
259     else pprUserCon con details
260
261 pprPat (LitPat s)             = ppr s
262 pprPat (NPat l Nothing  _)  = ppr l
263 pprPat (NPat l (Just _) _)  = char '-' <> ppr l
264 pprPat (NPlusKPat n k _ _)    = hcat [ppr n, char '+', ppr k]
265 pprPat (QuasiQuotePat (HsQuasiQuote name quoter _ quote)) 
266     = char '$' <> brackets (ppr name) <>
267       ptext SLIT("[:") <> ppr quoter <> ptext SLIT("|") <>
268       ppr quote <> ptext SLIT("|]")
269 pprPat (TypePat ty)           = ptext SLIT("{|") <> ppr ty <> ptext SLIT("|}")
270 pprPat (CoPat co pat _)       = parens (pprHsWrapper (ppr pat) co)
271 pprPat (SigPatIn pat ty)      = ppr pat <+> dcolon <+> ppr ty
272 pprPat (SigPatOut pat ty)     = ppr pat <+> dcolon <+> ppr ty
273
274 pprUserCon c (InfixCon p1 p2) = ppr p1 <+> ppr c <+> ppr p2
275 pprUserCon c details          = ppr c <+> pprConArgs details
276
277 pprConArgs (PrefixCon pats) = interppSP pats
278 pprConArgs (InfixCon p1 p2) = interppSP [p1,p2]
279 pprConArgs (RecCon rpats)   = ppr rpats
280
281 instance (OutputableBndr id, Outputable arg)
282       => Outputable (HsRecFields id arg) where
283   ppr (HsRecFields { rec_flds = flds, rec_dotdot = Nothing })
284         = braces (fsep (punctuate comma (map ppr flds)))
285   ppr (HsRecFields { rec_flds = flds, rec_dotdot = Just n })
286         = braces (fsep (punctuate comma (map ppr (take n flds) ++ [dotdot])))
287         where
288           dotdot = ptext SLIT("..") <+> ifPprDebug (ppr (drop n flds))
289
290 instance (OutputableBndr id, Outputable arg)
291       => Outputable (HsRecField id arg) where
292   ppr (HsRecField { hsRecFieldId = f, hsRecFieldArg = arg, 
293                     hsRecPun = pun })
294     = ppr f <+> (if pun then empty else equals <+> ppr arg)
295
296 -- add parallel array brackets around a document
297 --
298 pabrackets   :: SDoc -> SDoc
299 pabrackets p  = ptext SLIT("[:") <> p <> ptext SLIT(":]")
300 \end{code}
301
302
303 %************************************************************************
304 %*                                                                      *
305 %*              Building patterns
306 %*                                                                      *
307 %************************************************************************
308
309 \begin{code}
310 mkPrefixConPat :: DataCon -> [OutPat id] -> Type -> OutPat id
311 -- Make a vanilla Prefix constructor pattern
312 mkPrefixConPat dc pats ty 
313   = noLoc $ ConPatOut { pat_con = noLoc dc, pat_tvs = [], pat_dicts = [],
314                         pat_binds = emptyLHsBinds, pat_args = PrefixCon pats, 
315                         pat_ty = ty }
316
317 mkNilPat :: Type -> OutPat id
318 mkNilPat ty = mkPrefixConPat nilDataCon [] ty
319
320 mkCharLitPat :: Char -> OutPat id
321 mkCharLitPat c = mkPrefixConPat charDataCon [noLoc $ LitPat (HsCharPrim c)] charTy
322
323 mkCoPat :: HsWrapper -> Pat id -> Type -> Pat id
324 mkCoPat co pat ty
325   | isIdHsWrapper co = pat
326   | otherwise        = CoPat co pat ty
327
328 mkCoPatCoI :: CoercionI -> Pat id -> Type -> Pat id
329 mkCoPatCoI IdCo     pat ty = pat
330 mkCoPatCoI (ACo co) pat ty = mkCoPat (WpCo co) pat ty
331 \end{code}
332
333
334 %************************************************************************
335 %*                                                                      *
336 %* Predicates for checking things about pattern-lists in EquationInfo   *
337 %*                                                                      *
338 %************************************************************************
339
340 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
341
342 Unlike in the Wadler chapter, where patterns are either ``variables''
343 or ``constructors,'' here we distinguish between:
344 \begin{description}
345 \item[unfailable:]
346 Patterns that cannot fail to match: variables, wildcards, and lazy
347 patterns.
348
349 These are the irrefutable patterns; the two other categories
350 are refutable patterns.
351
352 \item[constructor:]
353 A non-literal constructor pattern (see next category).
354
355 \item[literal patterns:]
356 At least the numeric ones may be overloaded.
357 \end{description}
358
359 A pattern is in {\em exactly one} of the above three categories; `as'
360 patterns are treated specially, of course.
361
362 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
363 \begin{code}
364 isWildPat (WildPat _) = True
365 isWildPat other       = False
366
367 patsAreAllCons :: [Pat id] -> Bool
368 patsAreAllCons pat_list = all isConPat pat_list
369
370 isConPat (AsPat _ pat)   = isConPat (unLoc pat)
371 isConPat (ConPatIn {})   = True
372 isConPat (ConPatOut {})  = True
373 isConPat (ListPat {})    = True
374 isConPat (PArrPat {})    = True
375 isConPat (TuplePat {})   = True
376 isConPat other           = False
377
378 isSigPat (SigPatIn _ _)  = True
379 isSigPat (SigPatOut _ _) = True
380 isSigPat other           = False
381
382 patsAreAllLits :: [Pat id] -> Bool
383 patsAreAllLits pat_list = all isLitPat pat_list
384
385 isLitPat (AsPat _ pat)          = isLitPat (unLoc pat)
386 isLitPat (LitPat _)             = True
387 isLitPat (NPat _ _ _)           = True
388 isLitPat (NPlusKPat _ _ _ _)    = True
389 isLitPat other                  = False
390
391 isBangHsBind :: HsBind id -> Bool
392 -- In this module because HsPat is above HsBinds in the import graph
393 isBangHsBind (PatBind { pat_lhs = L _ (BangPat p) }) = True
394 isBangHsBind bind                                    = False
395
396 isIrrefutableHsPat :: LPat id -> Bool
397 -- (isIrrefutableHsPat p) is true if matching against p cannot fail,
398 -- in the sense of falling through to the next pattern.
399 --      (NB: this is not quite the same as the (silly) defn
400 --      in 3.17.2 of the Haskell 98 report.)
401 -- 
402 -- isIrrefutableHsPat returns False if it's in doubt; specifically
403 -- on a ConPatIn it doesn't know the size of the constructor family
404 -- But if it returns True, the pattern is definitely irrefutable
405 isIrrefutableHsPat pat
406   = go pat
407   where
408     go (L _ pat)         = go1 pat
409
410     go1 (WildPat _)         = True
411     go1 (VarPat _)          = True
412     go1 (VarPatOut _ _)     = True
413     go1 (LazyPat pat)       = True
414     go1 (BangPat pat)       = go pat
415     go1 (CoPat _ pat _)     = go1 pat
416     go1 (ParPat pat)        = go pat
417     go1 (AsPat _ pat)       = go pat
418     go1 (ViewPat _ pat _)   = go pat
419     go1 (SigPatIn pat _)    = go pat
420     go1 (SigPatOut pat _)   = go pat
421     go1 (TuplePat pats _ _) = all go pats
422     go1 (ListPat pats _)    = False
423     go1 (PArrPat pats _)    = False     -- ?
424
425     go1 (ConPatIn _ _) = False  -- Conservative
426     go1 (ConPatOut{ pat_con = L _ con, pat_args = details }) 
427         =  isProductTyCon (dataConTyCon con)
428         && all go (hsConPatArgs details)
429
430     go1 (LitPat _)         = False
431     go1 (NPat _ _ _)       = False
432     go1 (NPlusKPat _ _ _ _) = False
433
434     go1 (TypePat _)   = panic "isIrrefutableHsPat: type pattern"
435 \end{code}
436