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