Revert multiple commits
[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, pprSplice)
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) -- Includes quasi-quotes
170
171 ------------ Literal and n+k patterns ---------------
172 | LitPat HsLit -- Used for *non-overloaded* literal patterns:
173 -- Int#, Char#, Int, Char, String, etc.
174
175 | NPat -- Used for all overloaded literals,
176 -- including overloaded strings with -XOverloadedStrings
177 (Located (HsOverLit id)) -- ALWAYS positive
178 (Maybe (SyntaxExpr id)) -- Just (Name of 'negate') for negative
179 -- patterns, Nothing otherwise
180 (SyntaxExpr id) -- Equality checker, of type t->t->Bool
181
182 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVal' @'+'@
183
184 -- For details on above see note [Api annotations] in ApiAnnotation
185 | NPlusKPat (Located id) -- n+k pattern
186 (Located (HsOverLit id)) -- It'll always be an HsIntegral
187 (SyntaxExpr id) -- (>=) function, of type t->t->Bool
188 (SyntaxExpr id) -- Name of '-' (see RnEnv.lookupSyntaxName)
189
190 ------------ Pattern type signatures ---------------
191 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
192
193 -- For details on above see note [Api annotations] in ApiAnnotation
194 | SigPatIn (LPat id) -- Pattern with a type signature
195 (HsWithBndrs id (LHsType id)) -- Signature can bind both
196 -- kind and type vars
197
198 | SigPatOut (LPat id) -- Pattern with a type signature
199 Type
200
201 ------------ Pattern coercions (translation only) ---------------
202 | CoPat HsWrapper -- If co :: t1 ~ t2, p :: t2,
203 -- then (CoPat co p) :: t1
204 (Pat id) -- Why not LPat? Ans: existing locn will do
205 Type -- Type of whole pattern, t1
206 -- During desugaring a (CoPat co pat) turns into a cast with 'co' on
207 -- the scrutinee, followed by a match on 'pat'
208 deriving (Typeable)
209 deriving instance (DataId id) => Data (Pat id)
210
211 -- HsConDetails is use for patterns/expressions *and* for data type declarations
212
213 data HsConDetails arg rec
214 = PrefixCon [arg] -- C p1 p2 p3
215 | RecCon rec -- C { x = p1, y = p2 }
216 | InfixCon arg arg -- p1 `C` p2
217 deriving (Data, Typeable)
218
219 type HsConPatDetails id = HsConDetails (LPat id) (HsRecFields id (LPat id))
220
221 hsConPatArgs :: HsConPatDetails id -> [LPat id]
222 hsConPatArgs (PrefixCon ps) = ps
223 hsConPatArgs (RecCon fs) = map (hsRecFieldArg . unLoc) (rec_flds fs)
224 hsConPatArgs (InfixCon p1 p2) = [p1,p2]
225
226 {-
227 However HsRecFields is used only for patterns and expressions
228 (not data type declarations)
229 -}
230
231 data HsRecFields id arg -- A bunch of record fields
232 -- { x = 3, y = True }
233 -- Used for both expressions and patterns
234 = HsRecFields { rec_flds :: [LHsRecField id arg],
235 rec_dotdot :: Maybe Int } -- Note [DotDot fields]
236 deriving (Data, Typeable)
237
238 -- Note [DotDot fields]
239 -- ~~~~~~~~~~~~~~~~~~~~
240 -- The rec_dotdot field means this:
241 -- Nothing => the normal case
242 -- Just n => the group uses ".." notation,
243 --
244 -- In the latter case:
245 --
246 -- *before* renamer: rec_flds are exactly the n user-written fields
247 --
248 -- *after* renamer: rec_flds includes *all* fields, with
249 -- the first 'n' being the user-written ones
250 -- and the remainder being 'filled in' implicitly
251
252 type LHsRecField id arg = Located (HsRecField id arg)
253 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnEqual',
254
255 -- For details on above see note [Api annotations] in ApiAnnotation
256 data HsRecField id arg = HsRecField {
257 hsRecFieldId :: Located id,
258 hsRecFieldArg :: arg, -- Filled in by renamer
259 hsRecPun :: Bool -- Note [Punning]
260 } deriving (Data, Typeable)
261
262 -- Note [Punning]
263 -- ~~~~~~~~~~~~~~
264 -- If you write T { x, y = v+1 }, the HsRecFields will be
265 -- HsRecField x x True ...
266 -- HsRecField y (v+1) False ...
267 -- That is, for "punned" field x is expanded (in the renamer)
268 -- to x=x; but with a punning flag so we can detect it later
269 -- (e.g. when pretty printing)
270 --
271 -- If the original field was qualified, we un-qualify it, thus
272 -- T { A.x } means T { A.x = x }
273
274 hsRecFields :: HsRecFields id arg -> [id]
275 hsRecFields rbinds = map (unLoc . hsRecFieldId . unLoc) (rec_flds rbinds)
276
277 {-
278 ************************************************************************
279 * *
280 * Printing patterns
281 * *
282 ************************************************************************
283 -}
284
285 instance (OutputableBndr name) => Outputable (Pat name) where
286 ppr = pprPat
287
288 pprPatBndr :: OutputableBndr name => name -> SDoc
289 pprPatBndr var -- Print with type info if -dppr-debug is on
290 = getPprStyle $ \ sty ->
291 if debugStyle sty then
292 parens (pprBndr LambdaBind var) -- Could pass the site to pprPat
293 -- but is it worth it?
294 else
295 pprPrefixOcc var
296
297 pprParendLPat :: (OutputableBndr name) => LPat name -> SDoc
298 pprParendLPat (L _ p) = pprParendPat p
299
300 pprParendPat :: (OutputableBndr name) => Pat name -> SDoc
301 pprParendPat p | hsPatNeedsParens p = parens (pprPat p)
302 | otherwise = pprPat p
303
304 pprPat :: (OutputableBndr name) => Pat name -> SDoc
305 pprPat (VarPat var) = pprPatBndr var
306 pprPat (WildPat _) = char '_'
307 pprPat (LazyPat pat) = char '~' <> pprParendLPat pat
308 pprPat (BangPat pat) = char '!' <> pprParendLPat pat
309 pprPat (AsPat name pat) = hcat [pprPrefixOcc (unLoc name), char '@', pprParendLPat pat]
310 pprPat (ViewPat expr pat _) = hcat [pprLExpr expr, text " -> ", ppr pat]
311 pprPat (ParPat pat) = parens (ppr pat)
312 pprPat (ListPat pats _ _) = brackets (interpp'SP pats)
313 pprPat (PArrPat pats _) = paBrackets (interpp'SP pats)
314 pprPat (TuplePat pats bx _) = tupleParens (boxityNormalTupleSort bx) (interpp'SP pats)
315
316 pprPat (ConPatIn con details) = pprUserCon (unLoc con) details
317 pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts,
318 pat_binds = binds, pat_args = details })
319 = getPprStyle $ \ sty -> -- Tiresome; in TcBinds.tcRhs we print out a
320 if debugStyle sty then -- typechecked Pat in an error message,
321 -- and we want to make sure it prints nicely
322 ppr con
323 <> braces (sep [ hsep (map pprPatBndr (tvs ++ dicts))
324 , ppr binds])
325 <+> pprConArgs details
326 else pprUserCon (unLoc con) details
327
328 pprPat (LitPat s) = ppr s
329 pprPat (NPat l Nothing _) = ppr l
330 pprPat (NPat l (Just _) _) = char '-' <> ppr l
331 pprPat (NPlusKPat n k _ _) = hcat [ppr n, char '+', ppr k]
332 pprPat (SplicePat splice) = pprSplice splice
333 pprPat (CoPat co pat _) = pprHsWrapper (ppr pat) co
334 pprPat (SigPatIn pat ty) = ppr pat <+> dcolon <+> ppr ty
335 pprPat (SigPatOut pat ty) = ppr pat <+> dcolon <+> ppr ty
336
337 pprUserCon :: (OutputableBndr con, OutputableBndr id) => con -> HsConPatDetails id -> SDoc
338 pprUserCon c (InfixCon p1 p2) = ppr p1 <+> pprInfixOcc c <+> ppr p2
339 pprUserCon c details = pprPrefixOcc c <+> pprConArgs details
340
341 pprConArgs :: OutputableBndr id => HsConPatDetails id -> SDoc
342 pprConArgs (PrefixCon pats) = sep (map pprParendLPat pats)
343 pprConArgs (InfixCon p1 p2) = sep [pprParendLPat p1, pprParendLPat p2]
344 pprConArgs (RecCon rpats) = ppr rpats
345
346 instance (OutputableBndr id, Outputable arg)
347 => Outputable (HsRecFields id arg) where
348 ppr (HsRecFields { rec_flds = flds, rec_dotdot = Nothing })
349 = braces (fsep (punctuate comma (map ppr flds)))
350 ppr (HsRecFields { rec_flds = flds, rec_dotdot = Just n })
351 = braces (fsep (punctuate comma (map ppr (take n flds) ++ [dotdot])))
352 where
353 dotdot = ptext (sLit "..") <+> ifPprDebug (ppr (drop n flds))
354
355 instance (OutputableBndr id, Outputable arg)
356 => Outputable (HsRecField id arg) where
357 ppr (HsRecField { hsRecFieldId = f, hsRecFieldArg = arg,
358 hsRecPun = pun })
359 = ppr f <+> (ppUnless pun $ equals <+> ppr arg)
360
361 {-
362 ************************************************************************
363 * *
364 * Building patterns
365 * *
366 ************************************************************************
367 -}
368
369 mkPrefixConPat :: DataCon -> [OutPat id] -> [Type] -> OutPat id
370 -- Make a vanilla Prefix constructor pattern
371 mkPrefixConPat dc pats tys
372 = noLoc $ ConPatOut { pat_con = noLoc (RealDataCon dc), pat_tvs = [], pat_dicts = [],
373 pat_binds = emptyTcEvBinds, pat_args = PrefixCon pats,
374 pat_arg_tys = tys, pat_wrap = idHsWrapper }
375
376 mkNilPat :: Type -> OutPat id
377 mkNilPat ty = mkPrefixConPat nilDataCon [] [ty]
378
379 mkCharLitPat :: String -> Char -> OutPat id
380 mkCharLitPat src c = mkPrefixConPat charDataCon
381 [noLoc $ LitPat (HsCharPrim src c)] []
382
383 {-
384 ************************************************************************
385 * *
386 * Predicates for checking things about pattern-lists in EquationInfo *
387 * *
388 ************************************************************************
389
390 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
391
392 Unlike in the Wadler chapter, where patterns are either ``variables''
393 or ``constructors,'' here we distinguish between:
394 \begin{description}
395 \item[unfailable:]
396 Patterns that cannot fail to match: variables, wildcards, and lazy
397 patterns.
398
399 These are the irrefutable patterns; the two other categories
400 are refutable patterns.
401
402 \item[constructor:]
403 A non-literal constructor pattern (see next category).
404
405 \item[literal patterns:]
406 At least the numeric ones may be overloaded.
407 \end{description}
408
409 A pattern is in {\em exactly one} of the above three categories; `as'
410 patterns are treated specially, of course.
411
412 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
413 -}
414
415 isStrictLPat :: LPat id -> Bool
416 isStrictLPat (L _ (ParPat p)) = isStrictLPat p
417 isStrictLPat (L _ (BangPat {})) = True
418 isStrictLPat (L _ (TuplePat _ Unboxed _)) = True
419 isStrictLPat _ = False
420
421 isStrictHsBind :: HsBind id -> Bool
422 -- A pattern binding with an outermost bang or unboxed tuple must be matched strictly
423 -- Defined in this module because HsPat is above HsBinds in the import graph
424 isStrictHsBind (PatBind { pat_lhs = p }) = isStrictLPat p
425 isStrictHsBind _ = False
426
427 looksLazyPatBind :: HsBind id -> Bool
428 -- Returns True of anything *except*
429 -- a StrictHsBind (as above) or
430 -- a VarPat
431 -- In particular, returns True of a pattern binding with a compound pattern, like (I# x)
432 looksLazyPatBind (PatBind { pat_lhs = p }) = looksLazyLPat p
433 looksLazyPatBind _ = False
434
435 looksLazyLPat :: LPat id -> Bool
436 looksLazyLPat (L _ (ParPat p)) = looksLazyLPat p
437 looksLazyLPat (L _ (AsPat _ p)) = looksLazyLPat p
438 looksLazyLPat (L _ (BangPat {})) = False
439 looksLazyLPat (L _ (TuplePat _ Unboxed _)) = False
440 looksLazyLPat (L _ (VarPat {})) = False
441 looksLazyLPat (L _ (WildPat {})) = False
442 looksLazyLPat _ = True
443
444 isIrrefutableHsPat :: OutputableBndr id => LPat id -> Bool
445 -- (isIrrefutableHsPat p) is true if matching against p cannot fail,
446 -- in the sense of falling through to the next pattern.
447 -- (NB: this is not quite the same as the (silly) defn
448 -- in 3.17.2 of the Haskell 98 report.)
449 --
450 -- isIrrefutableHsPat returns False if it's in doubt; specifically
451 -- on a ConPatIn it doesn't know the size of the constructor family
452 -- But if it returns True, the pattern is definitely irrefutable
453 isIrrefutableHsPat pat
454 = go pat
455 where
456 go (L _ pat) = go1 pat
457
458 go1 (WildPat {}) = True
459 go1 (VarPat {}) = True
460 go1 (LazyPat {}) = True
461 go1 (BangPat pat) = go pat
462 go1 (CoPat _ pat _) = go1 pat
463 go1 (ParPat pat) = go pat
464 go1 (AsPat _ pat) = go pat
465 go1 (ViewPat _ pat _) = go pat
466 go1 (SigPatIn pat _) = go pat
467 go1 (SigPatOut pat _) = go pat
468 go1 (TuplePat pats _ _) = all go pats
469 go1 (ListPat {}) = False
470 go1 (PArrPat {}) = False -- ?
471
472 go1 (ConPatIn {}) = False -- Conservative
473 go1 (ConPatOut{ pat_con = L _ (RealDataCon con), pat_args = details })
474 = isJust (tyConSingleDataCon_maybe (dataConTyCon con))
475 -- NB: tyConSingleDataCon_maybe, *not* isProductTyCon, because
476 -- the latter is false of existentials. See Trac #4439
477 && all go (hsConPatArgs details)
478 go1 (ConPatOut{ pat_con = L _ (PatSynCon _pat) })
479 = False -- Conservative
480
481 go1 (LitPat {}) = False
482 go1 (NPat {}) = False
483 go1 (NPlusKPat {}) = False
484
485 -- Both should be gotten rid of by renamer before
486 -- isIrrefutablePat is called
487 go1 (SplicePat {}) = urk pat
488
489 urk pat = pprPanic "isIrrefutableHsPat:" (ppr pat)
490
491 hsPatNeedsParens :: Pat a -> Bool
492 hsPatNeedsParens (NPlusKPat {}) = True
493 hsPatNeedsParens (SplicePat {}) = False
494 hsPatNeedsParens (ConPatIn _ ds) = conPatNeedsParens ds
495 hsPatNeedsParens p@(ConPatOut {}) = conPatNeedsParens (pat_args p)
496 hsPatNeedsParens (SigPatIn {}) = True
497 hsPatNeedsParens (SigPatOut {}) = True
498 hsPatNeedsParens (ViewPat {}) = True
499 hsPatNeedsParens (CoPat {}) = True
500 hsPatNeedsParens (WildPat {}) = False
501 hsPatNeedsParens (VarPat {}) = False
502 hsPatNeedsParens (LazyPat {}) = False
503 hsPatNeedsParens (BangPat {}) = False
504 hsPatNeedsParens (ParPat {}) = False
505 hsPatNeedsParens (AsPat {}) = False
506 hsPatNeedsParens (TuplePat {}) = False
507 hsPatNeedsParens (ListPat {}) = False
508 hsPatNeedsParens (PArrPat {}) = False
509 hsPatNeedsParens (LitPat {}) = False
510 hsPatNeedsParens (NPat {}) = False
511
512 conPatNeedsParens :: HsConDetails a b -> Bool
513 conPatNeedsParens (PrefixCon args) = not (null args)
514 conPatNeedsParens (InfixCon {}) = True
515 conPatNeedsParens (RecCon {}) = True