Track type variable scope more carefully.
[ghc.git] / compiler / hsSyn / HsTypes.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5
6 HsTypes: Abstract syntax: user-defined types
7 -}
8
9 {-# LANGUAGE DeriveDataTypeable #-}
10 {-# LANGUAGE FlexibleContexts #-}
11 {-# LANGUAGE FlexibleInstances #-}
12 {-# LANGUAGE StandaloneDeriving #-}
13 {-# LANGUAGE TypeSynonymInstances #-}
14 {-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
15 -- in module PlaceHolder
16 {-# LANGUAGE ConstraintKinds #-}
17 {-# LANGUAGE CPP #-}
18
19 module HsTypes (
20 HsType(..), LHsType, HsKind, LHsKind,
21 HsTyVarBndr(..), LHsTyVarBndr,
22 LHsQTyVars(..),
23 HsImplicitBndrs(..),
24 HsWildCardBndrs(..),
25 LHsSigType, LHsSigWcType, LHsWcType,
26 HsTupleSort(..),
27 Promoted(..),
28 HsContext, LHsContext,
29 HsTyLit(..),
30 HsIPName(..), hsIPNameFS,
31 HsAppType(..),LHsAppType,
32
33 LBangType, BangType,
34 HsSrcBang(..), HsImplBang(..),
35 SrcStrictness(..), SrcUnpackedness(..),
36 getBangType, getBangStrictness,
37
38 ConDeclField(..), LConDeclField, pprConDeclFields,
39
40 HsConDetails(..),
41
42 FieldOcc(..), LFieldOcc, mkFieldOcc,
43 AmbiguousFieldOcc(..), mkAmbiguousFieldOcc,
44 rdrNameAmbiguousFieldOcc, selectorAmbiguousFieldOcc,
45 unambiguousFieldOcc, ambiguousFieldOcc,
46
47 HsWildCardInfo(..), mkAnonWildCardTy,
48 wildCardName, sameWildCard,
49
50 mkHsImplicitBndrs, mkHsWildCardBndrs, hsImplicitBody,
51 mkEmptyImplicitBndrs, mkEmptyWildCardBndrs,
52 mkHsQTvs, hsQTvExplicit, emptyLHsQTvs, isEmptyLHsQTvs,
53 isHsKindedTyVar, hsTvbAllKinded, isLHsForAllTy,
54 hsScopedTvs, hsWcScopedTvs, dropWildCards,
55 hsTyVarName, hsAllLTyVarNames, hsLTyVarLocNames,
56 hsLTyVarName, hsLTyVarLocName, hsExplicitLTyVarNames,
57 splitLHsInstDeclTy, getLHsInstDeclHead, getLHsInstDeclClass_maybe,
58 splitLHsPatSynTy,
59 splitLHsForAllTy, splitLHsQualTy, splitLHsSigmaTy,
60 splitHsFunType, splitHsAppsTy,
61 splitHsAppTys, getAppsTyHead_maybe, hsTyGetAppHead_maybe,
62 mkHsOpTy, mkHsAppTy, mkHsAppTys, mkHsAppsTy,
63 ignoreParens, hsSigType, hsSigWcType,
64 hsLTyVarBndrToType, hsLTyVarBndrsToTypes,
65
66 -- Printing
67 pprHsType, pprHsForAll, pprHsForAllTvs, pprHsForAllExtra,
68 pprHsContext, pprHsContextNoArrow, pprHsContextMaybe,
69 isCompoundHsType, parenthesizeCompoundHsType
70 ) where
71
72 import GhcPrelude
73
74 import {-# SOURCE #-} HsExpr ( HsSplice, pprSplice )
75
76 import PlaceHolder ( PlaceHolder(..) )
77 import HsExtension
78
79 import Id ( Id )
80 import Name( Name )
81 import RdrName ( RdrName )
82 import NameSet ( NameSet, emptyNameSet )
83 import DataCon( HsSrcBang(..), HsImplBang(..),
84 SrcStrictness(..), SrcUnpackedness(..) )
85 import TysPrim( funTyConName )
86 import Type
87 import HsDoc
88 import BasicTypes
89 import SrcLoc
90 import Outputable
91 import FastString
92 import Maybes( isJust )
93
94 import Data.Data hiding ( Fixity, Prefix, Infix )
95 import Data.Maybe ( fromMaybe )
96
97 {-
98 ************************************************************************
99 * *
100 \subsection{Bang annotations}
101 * *
102 ************************************************************************
103 -}
104
105 -- | Located Bang Type
106 type LBangType pass = Located (BangType pass)
107
108 -- | Bang Type
109 type BangType pass = HsType pass -- Bangs are in the HsType data type
110
111 getBangType :: LHsType a -> LHsType a
112 getBangType (L _ (HsBangTy _ ty)) = ty
113 getBangType ty = ty
114
115 getBangStrictness :: LHsType a -> HsSrcBang
116 getBangStrictness (L _ (HsBangTy s _)) = s
117 getBangStrictness _ = (HsSrcBang NoSourceText NoSrcUnpack NoSrcStrict)
118
119 {-
120 ************************************************************************
121 * *
122 \subsection{Data types}
123 * *
124 ************************************************************************
125
126 This is the syntax for types as seen in type signatures.
127
128 Note [HsBSig binder lists]
129 ~~~~~~~~~~~~~~~~~~~~~~~~~~
130 Consider a binder (or pattern) decorated with a type or kind,
131 \ (x :: a -> a). blah
132 forall (a :: k -> *) (b :: k). blah
133 Then we use a LHsBndrSig on the binder, so that the
134 renamer can decorate it with the variables bound
135 by the pattern ('a' in the first example, 'k' in the second),
136 assuming that neither of them is in scope already
137 See also Note [Kind and type-variable binders] in RnTypes
138
139 Note [HsType binders]
140 ~~~~~~~~~~~~~~~~~~~~~
141 The system for recording type and kind-variable binders in HsTypes
142 is a bit complicated. Here's how it works.
143
144 * In a HsType,
145 HsForAllTy represents an /explicit, user-written/ 'forall'
146 e.g. forall a b. ...
147 HsQualTy represents an /explicit, user-written/ context
148 e.g. (Eq a, Show a) => ...
149 The context can be empty if that's what the user wrote
150 These constructors represent what the user wrote, no more
151 and no less.
152
153 * HsTyVarBndr describes a quantified type variable written by the
154 user. For example
155 f :: forall a (b :: *). blah
156 here 'a' and '(b::*)' are each a HsTyVarBndr. A HsForAllTy has
157 a list of LHsTyVarBndrs.
158
159 * HsImplicitBndrs is a wrapper that gives the implicitly-quantified
160 kind and type variables of the wrapped thing. It is filled in by
161 the renamer. For example, if the user writes
162 f :: a -> a
163 the HsImplicitBinders binds the 'a' (not a HsForAllTy!).
164 NB: this implicit quantification is purely lexical: we bind any
165 type or kind variables that are not in scope. The type checker
166 may subsequently quantify over further kind variables.
167
168 * HsWildCardBndrs is a wrapper that binds the wildcard variables
169 of the wrapped thing. It is filled in by the renamer
170 f :: _a -> _
171 The enclosing HsWildCardBndrs binds the wildcards _a and _.
172
173 * The explicit presence of these wrappers specifies, in the HsSyn,
174 exactly where implicit quantification is allowed, and where
175 wildcards are allowed.
176
177 * LHsQTyVars is used in data/class declarations, where the user gives
178 explicit *type* variable bindings, but we need to implicitly bind
179 *kind* variables. For example
180 class C (a :: k -> *) where ...
181 The 'k' is implicitly bound in the hsq_tvs field of LHsQTyVars
182
183 Note [The wildcard story for types]
184 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
185 Types can have wildcards in them, to support partial type signatures,
186 like f :: Int -> (_ , _a) -> _a
187
188 A wildcard in a type can be
189
190 * An anonymous wildcard,
191 written '_'
192 In HsType this is represented by HsWildCardTy.
193 After the renamer, this contains a Name which uniquely
194 identifies this particular occurrence.
195
196 * A named wildcard,
197 written '_a', '_foo', etc
198 In HsType this is represented by (HsTyVar "_a")
199 i.e. a perfectly ordinary type variable that happens
200 to start with an underscore
201
202 Note carefully:
203
204 * When NamedWildCards is off, type variables that start with an
205 underscore really /are/ ordinary type variables. And indeed, even
206 when NamedWildCards is on you can bind _a explicitly as an ordinary
207 type variable:
208 data T _a _b = MkT _b _a
209 Or even:
210 f :: forall _a. _a -> _b
211 Here _a is an ordinary forall'd binder, but (With NamedWildCards)
212 _b is a named wildcard. (See the comments in Trac #10982)
213
214 * All wildcards, whether named or anonymous, are bound by the
215 HsWildCardBndrs construct, which wraps types that are allowed
216 to have wildcards.
217
218 * After type checking is done, we report what types the wildcards
219 got unified with.
220
221 -}
222
223 -- | Located Haskell Context
224 type LHsContext pass = Located (HsContext pass)
225 -- ^ 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnUnit'
226
227 -- For details on above see note [Api annotations] in ApiAnnotation
228
229 -- | Haskell Context
230 type HsContext pass = [LHsType pass]
231
232 -- | Located Haskell Type
233 type LHsType pass = Located (HsType pass)
234 -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when
235 -- in a list
236
237 -- For details on above see note [Api annotations] in ApiAnnotation
238
239 -- | Haskell Kind
240 type HsKind pass = HsType pass
241
242 -- | Located Haskell Kind
243 type LHsKind pass = Located (HsKind pass)
244 -- ^ 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
245
246 -- For details on above see note [Api annotations] in ApiAnnotation
247
248 --------------------------------------------------
249 -- LHsQTyVars
250 -- The explicitly-quantified binders in a data/type declaration
251
252 -- | Located Haskell Type Variable Binder
253 type LHsTyVarBndr pass = Located (HsTyVarBndr pass)
254 -- See Note [HsType binders]
255
256 -- | Located Haskell Quantified Type Variables
257 data LHsQTyVars pass -- See Note [HsType binders]
258 = HsQTvs { hsq_implicit :: PostRn pass [Name]
259 -- Implicit (dependent) variables
260
261 , hsq_explicit :: [LHsTyVarBndr pass]
262 -- Explicit variables, written by the user
263 -- See Note [HsForAllTy tyvar binders]
264
265 , hsq_dependent :: PostRn pass NameSet
266 -- Which members of hsq_explicit are dependent; that is,
267 -- mentioned in the kind of a later hsq_explicit,
268 -- or mentioned in a kind in the scope of this HsQTvs
269 -- See Note [Dependent LHsQTyVars] in TcHsType
270 }
271
272 deriving instance (DataId pass) => Data (LHsQTyVars pass)
273
274 mkHsQTvs :: [LHsTyVarBndr GhcPs] -> LHsQTyVars GhcPs
275 mkHsQTvs tvs = HsQTvs { hsq_implicit = PlaceHolder, hsq_explicit = tvs
276 , hsq_dependent = PlaceHolder }
277
278 hsQTvExplicit :: LHsQTyVars pass -> [LHsTyVarBndr pass]
279 hsQTvExplicit = hsq_explicit
280
281 emptyLHsQTvs :: LHsQTyVars GhcRn
282 emptyLHsQTvs = HsQTvs [] [] emptyNameSet
283
284 isEmptyLHsQTvs :: LHsQTyVars GhcRn -> Bool
285 isEmptyLHsQTvs (HsQTvs [] [] _) = True
286 isEmptyLHsQTvs _ = False
287
288 ------------------------------------------------
289 -- HsImplicitBndrs
290 -- Used to quantify the implicit binders of a type
291 -- * Implicit binders of a type signature (LHsSigType/LHsSigWcType)
292 -- * Patterns in a type/data family instance (HsTyPats)
293
294 -- | Haskell Implicit Binders
295 data HsImplicitBndrs pass thing -- See Note [HsType binders]
296 = HsIB { hsib_vars :: PostRn pass [Name] -- Implicitly-bound kind & type vars
297 , hsib_body :: thing -- Main payload (type or list of types)
298 , hsib_closed :: PostRn pass Bool -- Taking the hsib_vars into account,
299 -- is the payload closed? Used in
300 -- TcHsType.decideKindGeneralisationPlan
301 }
302 deriving instance (DataId pass, Data thing) => Data (HsImplicitBndrs pass thing)
303
304 -- | Haskell Wildcard Binders
305 data HsWildCardBndrs pass thing
306 -- See Note [HsType binders]
307 -- See Note [The wildcard story for types]
308 = HsWC { hswc_wcs :: PostRn pass [Name]
309 -- Wild cards, both named and anonymous
310 -- after the renamer
311
312 , hswc_body :: thing
313 -- Main payload (type or list of types)
314 -- If there is an extra-constraints wildcard,
315 -- it's still there in the hsc_body.
316 }
317
318 deriving instance (DataId pass, Data thing) => Data (HsWildCardBndrs pass thing)
319
320 -- | Located Haskell Signature Type
321 type LHsSigType pass = HsImplicitBndrs pass (LHsType pass) -- Implicit only
322
323 -- | Located Haskell Wildcard Type
324 type LHsWcType pass = HsWildCardBndrs pass (LHsType pass) -- Wildcard only
325
326 -- | Located Haskell Signature Wildcard Type
327 type LHsSigWcType pass = HsWildCardBndrs pass (LHsSigType pass) -- Both
328
329 -- See Note [Representing type signatures]
330
331 hsImplicitBody :: HsImplicitBndrs pass thing -> thing
332 hsImplicitBody (HsIB { hsib_body = body }) = body
333
334 hsSigType :: LHsSigType pass -> LHsType pass
335 hsSigType = hsImplicitBody
336
337 hsSigWcType :: LHsSigWcType pass -> LHsType pass
338 hsSigWcType sig_ty = hsib_body (hswc_body sig_ty)
339
340 dropWildCards :: LHsSigWcType pass -> LHsSigType pass
341 -- Drop the wildcard part of a LHsSigWcType
342 dropWildCards sig_ty = hswc_body sig_ty
343
344 {- Note [Representing type signatures]
345 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
346 HsSigType is used to represent an explicit user type signature
347 such as f :: a -> a
348 or g (x :: a -> a) = x
349
350 A HsSigType is just a HsImplicitBndrs wrapping a LHsType.
351 * The HsImplicitBndrs binds the /implicitly/ quantified tyvars
352 * The LHsType binds the /explicitly/ quantified tyvars
353
354 E.g. For a signature like
355 f :: forall (a::k). blah
356 we get
357 HsIB { hsib_vars = [k]
358 , hsib_body = HsForAllTy { hst_bndrs = [(a::*)]
359 , hst_body = blah }
360 The implicit kind variable 'k' is bound by the HsIB;
361 the explicitly forall'd tyvar 'a' is bound by the HsForAllTy
362 -}
363
364 mkHsImplicitBndrs :: thing -> HsImplicitBndrs GhcPs thing
365 mkHsImplicitBndrs x = HsIB { hsib_body = x
366 , hsib_vars = PlaceHolder
367 , hsib_closed = PlaceHolder }
368
369 mkHsWildCardBndrs :: thing -> HsWildCardBndrs GhcPs thing
370 mkHsWildCardBndrs x = HsWC { hswc_body = x
371 , hswc_wcs = PlaceHolder }
372
373 -- Add empty binders. This is a bit suspicious; what if
374 -- the wrapped thing had free type variables?
375 mkEmptyImplicitBndrs :: thing -> HsImplicitBndrs GhcRn thing
376 mkEmptyImplicitBndrs x = HsIB { hsib_body = x
377 , hsib_vars = []
378 , hsib_closed = False }
379
380 mkEmptyWildCardBndrs :: thing -> HsWildCardBndrs GhcRn thing
381 mkEmptyWildCardBndrs x = HsWC { hswc_body = x
382 , hswc_wcs = [] }
383
384
385 --------------------------------------------------
386 -- | These names are used early on to store the names of implicit
387 -- parameters. They completely disappear after type-checking.
388 newtype HsIPName = HsIPName FastString
389 deriving( Eq, Data )
390
391 hsIPNameFS :: HsIPName -> FastString
392 hsIPNameFS (HsIPName n) = n
393
394 instance Outputable HsIPName where
395 ppr (HsIPName n) = char '?' <> ftext n -- Ordinary implicit parameters
396
397 instance OutputableBndr HsIPName where
398 pprBndr _ n = ppr n -- Simple for now
399 pprInfixOcc n = ppr n
400 pprPrefixOcc n = ppr n
401
402 --------------------------------------------------
403
404 -- | Haskell Type Variable Binder
405 data HsTyVarBndr pass
406 = UserTyVar -- no explicit kinding
407 (Located (IdP pass))
408 -- See Note [Located RdrNames] in HsExpr
409 | KindedTyVar
410 (Located (IdP pass))
411 (LHsKind pass) -- The user-supplied kind signature
412 -- ^
413 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
414 -- 'ApiAnnotation.AnnDcolon', 'ApiAnnotation.AnnClose'
415
416 -- For details on above see note [Api annotations] in ApiAnnotation
417 deriving instance (DataId pass) => Data (HsTyVarBndr pass)
418
419 -- | Does this 'HsTyVarBndr' come with an explicit kind annotation?
420 isHsKindedTyVar :: HsTyVarBndr pass -> Bool
421 isHsKindedTyVar (UserTyVar {}) = False
422 isHsKindedTyVar (KindedTyVar {}) = True
423
424 -- | Do all type variables in this 'LHsQTyVars' come with kind annotations?
425 hsTvbAllKinded :: LHsQTyVars pass -> Bool
426 hsTvbAllKinded = all (isHsKindedTyVar . unLoc) . hsQTvExplicit
427
428 -- | Haskell Type
429 data HsType pass
430 = HsForAllTy -- See Note [HsType binders]
431 { hst_bndrs :: [LHsTyVarBndr pass]
432 -- Explicit, user-supplied 'forall a b c'
433 , hst_body :: LHsType pass -- body type
434 }
435 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnForall',
436 -- 'ApiAnnotation.AnnDot','ApiAnnotation.AnnDarrow'
437 -- For details on above see note [Api annotations] in ApiAnnotation
438
439 | HsQualTy -- See Note [HsType binders]
440 { hst_ctxt :: LHsContext pass -- Context C => blah
441 , hst_body :: LHsType pass }
442
443 | HsTyVar Promoted -- whether explicitly promoted, for the pretty
444 -- printer
445 (Located (IdP pass))
446 -- Type variable, type constructor, or data constructor
447 -- see Note [Promotions (HsTyVar)]
448 -- See Note [Located RdrNames] in HsExpr
449 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
450
451 -- For details on above see note [Api annotations] in ApiAnnotation
452
453 | HsAppsTy [LHsAppType pass] -- Used only before renaming,
454 -- Note [HsAppsTy]
455 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
456
457 | HsAppTy (LHsType pass)
458 (LHsType pass)
459 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
460
461 -- For details on above see note [Api annotations] in ApiAnnotation
462
463 | HsFunTy (LHsType pass) -- function type
464 (LHsType pass)
465 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow',
466
467 -- For details on above see note [Api annotations] in ApiAnnotation
468
469 | HsListTy (LHsType pass) -- Element type
470 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
471 -- 'ApiAnnotation.AnnClose' @']'@
472
473 -- For details on above see note [Api annotations] in ApiAnnotation
474
475 | HsPArrTy (LHsType pass) -- Elem. type of parallel array: [:t:]
476 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
477 -- 'ApiAnnotation.AnnClose' @':]'@
478
479 -- For details on above see note [Api annotations] in ApiAnnotation
480
481 | HsTupleTy HsTupleSort
482 [LHsType pass] -- Element types (length gives arity)
483 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(' or '(#'@,
484 -- 'ApiAnnotation.AnnClose' @')' or '#)'@
485
486 -- For details on above see note [Api annotations] in ApiAnnotation
487
488 | HsSumTy [LHsType pass] -- Element types (length gives arity)
489 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(#'@,
490 -- 'ApiAnnotation.AnnClose' '#)'@
491
492 -- For details on above see note [Api annotations] in ApiAnnotation
493
494 | HsOpTy (LHsType pass) (Located (IdP pass)) (LHsType pass)
495 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
496
497 -- For details on above see note [Api annotations] in ApiAnnotation
498
499 | HsParTy (LHsType pass) -- See Note [Parens in HsSyn] in HsExpr
500 -- Parenthesis preserved for the precedence re-arrangement in RnTypes
501 -- It's important that a * (b + c) doesn't get rearranged to (a*b) + c!
502 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
503 -- 'ApiAnnotation.AnnClose' @')'@
504
505 -- For details on above see note [Api annotations] in ApiAnnotation
506
507 | HsIParamTy (Located HsIPName) -- (?x :: ty)
508 (LHsType pass) -- Implicit parameters as they occur in
509 -- contexts
510 -- ^
511 -- > (?x :: ty)
512 --
513 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
514
515 -- For details on above see note [Api annotations] in ApiAnnotation
516
517 | HsEqTy (LHsType pass) -- ty1 ~ ty2
518 (LHsType pass) -- Always allowed even without
519 -- TypeOperators, and has special
520 -- kinding rule
521 -- ^
522 -- > ty1 ~ ty2
523 --
524 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde'
525
526 -- For details on above see note [Api annotations] in ApiAnnotation
527
528 | HsKindSig (LHsType pass) -- (ty :: kind)
529 (LHsKind pass) -- A type with a kind signature
530 -- ^
531 -- > (ty :: kind)
532 --
533 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
534 -- 'ApiAnnotation.AnnDcolon','ApiAnnotation.AnnClose' @')'@
535
536 -- For details on above see note [Api annotations] in ApiAnnotation
537
538 | HsSpliceTy (HsSplice pass) -- Includes quasi-quotes
539 (PostTc pass Kind)
540 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'$('@,
541 -- 'ApiAnnotation.AnnClose' @')'@
542
543 -- For details on above see note [Api annotations] in ApiAnnotation
544
545 | HsDocTy (LHsType pass) LHsDocString -- A documented type
546 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
547
548 -- For details on above see note [Api annotations] in ApiAnnotation
549
550 | HsBangTy HsSrcBang (LHsType pass) -- Bang-style type annotations
551 -- ^ - 'ApiAnnotation.AnnKeywordId' :
552 -- 'ApiAnnotation.AnnOpen' @'{-\# UNPACK' or '{-\# NOUNPACK'@,
553 -- 'ApiAnnotation.AnnClose' @'#-}'@
554 -- 'ApiAnnotation.AnnBang' @\'!\'@
555
556 -- For details on above see note [Api annotations] in ApiAnnotation
557
558 | HsRecTy [LConDeclField pass] -- Only in data type declarations
559 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
560 -- 'ApiAnnotation.AnnClose' @'}'@
561
562 -- For details on above see note [Api annotations] in ApiAnnotation
563
564 | HsCoreTy Type -- An escape hatch for tunnelling a *closed*
565 -- Core Type through HsSyn.
566 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
567
568 -- For details on above see note [Api annotations] in ApiAnnotation
569
570 | HsExplicitListTy -- A promoted explicit list
571 Promoted -- whether explcitly promoted, for pretty printer
572 (PostTc pass Kind) -- See Note [Promoted lists and tuples]
573 [LHsType pass]
574 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @"'["@,
575 -- 'ApiAnnotation.AnnClose' @']'@
576
577 -- For details on above see note [Api annotations] in ApiAnnotation
578
579 | HsExplicitTupleTy -- A promoted explicit tuple
580 [PostTc pass Kind] -- See Note [Promoted lists and tuples]
581 [LHsType pass]
582 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @"'("@,
583 -- 'ApiAnnotation.AnnClose' @')'@
584
585 -- For details on above see note [Api annotations] in ApiAnnotation
586
587 | HsTyLit HsTyLit -- A promoted numeric literal.
588 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
589
590 -- For details on above see note [Api annotations] in ApiAnnotation
591
592 | HsWildCardTy (HsWildCardInfo pass) -- A type wildcard
593 -- See Note [The wildcard story for types]
594 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
595
596 -- For details on above see note [Api annotations] in ApiAnnotation
597 deriving instance (DataId pass) => Data (HsType pass)
598
599 -- Note [Literal source text] in BasicTypes for SourceText fields in
600 -- the following
601 -- | Haskell Type Literal
602 data HsTyLit
603 = HsNumTy SourceText Integer
604 | HsStrTy SourceText FastString
605 deriving Data
606
607 newtype HsWildCardInfo pass -- See Note [The wildcard story for types]
608 = AnonWildCard (PostRn pass (Located Name))
609 -- A anonymous wild card ('_'). A fresh Name is generated for
610 -- each individual anonymous wildcard during renaming
611 deriving instance (DataId pass) => Data (HsWildCardInfo pass)
612
613 -- | Located Haskell Application Type
614 type LHsAppType pass = Located (HsAppType pass)
615 -- ^ 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSimpleQuote'
616
617 -- | Haskell Application Type
618 data HsAppType pass
619 = HsAppInfix (Located (IdP pass)) -- either a symbol or an id in backticks
620 | HsAppPrefix (LHsType pass) -- anything else, including things like (+)
621 deriving instance (DataId pass) => Data (HsAppType pass)
622
623 instance (SourceTextX pass, OutputableBndrId pass)
624 => Outputable (HsAppType pass) where
625 ppr = ppr_app_ty
626
627 {-
628 Note [HsForAllTy tyvar binders]
629 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
630 After parsing:
631 * Implicit => empty
632 Explicit => the variables the user wrote
633
634 After renaming
635 * Implicit => the *type* variables free in the type
636 Explicit => the variables the user wrote (renamed)
637
638 Qualified currently behaves exactly as Implicit,
639 but it is deprecated to use it for implicit quantification.
640 In this case, GHC 7.10 gives a warning; see
641 Note [Context quantification] in RnTypes, and Trac #4426.
642 In GHC 8.0, Qualified will no longer bind variables
643 and this will become an error.
644
645 The kind variables bound in the hsq_implicit field come both
646 a) from the kind signatures on the kind vars (eg k1)
647 b) from the scope of the forall (eg k2)
648 Example: f :: forall (a::k1) b. T a (b::k2)
649
650
651 Note [Unit tuples]
652 ~~~~~~~~~~~~~~~~~~
653 Consider the type
654 type instance F Int = ()
655 We want to parse that "()"
656 as HsTupleTy HsBoxedOrConstraintTuple [],
657 NOT as HsTyVar unitTyCon
658
659 Why? Because F might have kind (* -> Constraint), so we when parsing we
660 don't know if that tuple is going to be a constraint tuple or an ordinary
661 unit tuple. The HsTupleSort flag is specifically designed to deal with
662 that, but it has to work for unit tuples too.
663
664 Note [Promotions (HsTyVar)]
665 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
666 HsTyVar: A name in a type or kind.
667 Here are the allowed namespaces for the name.
668 In a type:
669 Var: not allowed
670 Data: promoted data constructor
671 Tv: type variable
672 TcCls before renamer: type constructor, class constructor, or promoted data constructor
673 TcCls after renamer: type constructor or class constructor
674 In a kind:
675 Var, Data: not allowed
676 Tv: kind variable
677 TcCls: kind constructor or promoted type constructor
678
679 The 'Promoted' field in an HsTyVar captures whether the type was promoted in
680 the source code by prefixing an apostrophe.
681
682 Note [HsAppsTy]
683 ~~~~~~~~~~~~~~~
684 How to parse
685
686 Foo * Int
687
688 ? Is it `(*) Foo Int` or `Foo GHC.Types.* Int`? There's no way to know until renaming.
689 So we just take type expressions like this and put each component in a list, so be
690 sorted out in the renamer. The sorting out is done by RnTypes.mkHsOpTyRn. This means
691 that the parser should never produce HsAppTy or HsOpTy.
692
693 Note [Promoted lists and tuples]
694 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
695 Notice the difference between
696 HsListTy HsExplicitListTy
697 HsTupleTy HsExplicitListTupleTy
698
699 E.g. f :: [Int] HsListTy
700
701 g3 :: T '[] All these use
702 g2 :: T '[True] HsExplicitListTy
703 g1 :: T '[True,False]
704 g1a :: T [True,False] (can omit ' where unambiguous)
705
706 kind of T :: [Bool] -> * This kind uses HsListTy!
707
708 E.g. h :: (Int,Bool) HsTupleTy; f is a pair
709 k :: S '(True,False) HsExplicitTypleTy; S is indexed by
710 a type-level pair of booleans
711 kind of S :: (Bool,Bool) -> * This kind uses HsExplicitTupleTy
712
713 Note [Distinguishing tuple kinds]
714 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
715
716 Apart from promotion, tuples can have one of three different kinds:
717
718 x :: (Int, Bool) -- Regular boxed tuples
719 f :: Int# -> (# Int#, Int# #) -- Unboxed tuples
720 g :: (Eq a, Ord a) => a -- Constraint tuples
721
722 For convenience, internally we use a single constructor for all of these,
723 namely HsTupleTy, but keep track of the tuple kind (in the first argument to
724 HsTupleTy, a HsTupleSort). We can tell if a tuple is unboxed while parsing,
725 because of the #. However, with -XConstraintKinds we can only distinguish
726 between constraint and boxed tuples during type checking, in general. Hence the
727 four constructors of HsTupleSort:
728
729 HsUnboxedTuple -> Produced by the parser
730 HsBoxedTuple -> Certainly a boxed tuple
731 HsConstraintTuple -> Certainly a constraint tuple
732 HsBoxedOrConstraintTuple -> Could be a boxed or a constraint
733 tuple. Produced by the parser only,
734 disappears after type checking
735 -}
736
737 -- | Haskell Tuple Sort
738 data HsTupleSort = HsUnboxedTuple
739 | HsBoxedTuple
740 | HsConstraintTuple
741 | HsBoxedOrConstraintTuple
742 deriving Data
743
744
745 -- | Promoted data types.
746 data Promoted = Promoted
747 | NotPromoted
748 deriving (Data, Eq, Show)
749
750 -- | Located Constructor Declaration Field
751 type LConDeclField pass = Located (ConDeclField pass)
752 -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when
753 -- in a list
754
755 -- For details on above see note [Api annotations] in ApiAnnotation
756
757 -- | Constructor Declaration Field
758 data ConDeclField pass -- Record fields have Haddoc docs on them
759 = ConDeclField { cd_fld_names :: [LFieldOcc pass],
760 -- ^ See Note [ConDeclField passs]
761 cd_fld_type :: LBangType pass,
762 cd_fld_doc :: Maybe LHsDocString }
763 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
764
765 -- For details on above see note [Api annotations] in ApiAnnotation
766 deriving instance (DataId pass) => Data (ConDeclField pass)
767
768 instance (SourceTextX pass, OutputableBndrId pass)
769 => Outputable (ConDeclField pass) where
770 ppr (ConDeclField fld_n fld_ty _) = ppr fld_n <+> dcolon <+> ppr fld_ty
771
772 -- HsConDetails is used for patterns/expressions *and* for data type
773 -- declarations
774 -- | Haskell Constructor Details
775 data HsConDetails arg rec
776 = PrefixCon [arg] -- C p1 p2 p3
777 | RecCon rec -- C { x = p1, y = p2 }
778 | InfixCon arg arg -- p1 `C` p2
779 deriving Data
780
781 instance (Outputable arg, Outputable rec)
782 => Outputable (HsConDetails arg rec) where
783 ppr (PrefixCon args) = text "PrefixCon" <+> ppr args
784 ppr (RecCon rec) = text "RecCon:" <+> ppr rec
785 ppr (InfixCon l r) = text "InfixCon:" <+> ppr [l, r]
786
787 {-
788 Note [ConDeclField passs]
789 ~~~~~~~~~~~~~~~~~~~~~~~~~
790
791 A ConDeclField contains a list of field occurrences: these always
792 include the field label as the user wrote it. After the renamer, it
793 will additionally contain the identity of the selector function in the
794 second component.
795
796 Due to DuplicateRecordFields, the OccName of the selector function
797 may have been mangled, which is why we keep the original field label
798 separately. For example, when DuplicateRecordFields is enabled
799
800 data T = MkT { x :: Int }
801
802 gives
803
804 ConDeclField { cd_fld_names = [L _ (FieldOcc "x" $sel:x:MkT)], ... }.
805 -}
806
807 -----------------------
808 -- A valid type must have a for-all at the top of the type, or of the fn arg
809 -- types
810
811 ---------------------
812 hsWcScopedTvs :: LHsSigWcType GhcRn -> [Name]
813 -- Get the lexically-scoped type variables of a HsSigType
814 -- - the explicitly-given forall'd type variables
815 -- - the implicitly-bound kind variables
816 -- - the named wildcars; see Note [Scoping of named wildcards]
817 -- because they scope in the same way
818 hsWcScopedTvs sig_ty
819 | HsWC { hswc_wcs = nwcs, hswc_body = sig_ty1 } <- sig_ty
820 , HsIB { hsib_vars = vars, hsib_body = sig_ty2 } <- sig_ty1
821 = case sig_ty2 of
822 L _ (HsForAllTy { hst_bndrs = tvs }) -> vars ++ nwcs ++
823 map hsLTyVarName tvs
824 -- include kind variables only if the type is headed by forall
825 -- (this is consistent with GHC 7 behaviour)
826 _ -> nwcs
827
828 hsScopedTvs :: LHsSigType GhcRn -> [Name]
829 -- Same as hsWcScopedTvs, but for a LHsSigType
830 hsScopedTvs sig_ty
831 | HsIB { hsib_vars = vars, hsib_body = sig_ty2 } <- sig_ty
832 , L _ (HsForAllTy { hst_bndrs = tvs }) <- sig_ty2
833 = vars ++ map hsLTyVarName tvs
834 | otherwise
835 = []
836
837 {- Note [Scoping of named wildcards]
838 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
839 Consider
840 f :: _a -> _a
841 f x = let g :: _a -> _a
842 g = ...
843 in ...
844
845 Currently, for better or worse, the "_a" variables are all the same. So
846 although there is no explicit forall, the "_a" scopes over the definition.
847 I don't know if this is a good idea, but there it is.
848 -}
849
850 ---------------------
851 hsTyVarName :: HsTyVarBndr pass -> IdP pass
852 hsTyVarName (UserTyVar (L _ n)) = n
853 hsTyVarName (KindedTyVar (L _ n) _) = n
854
855 hsLTyVarName :: LHsTyVarBndr pass -> IdP pass
856 hsLTyVarName = hsTyVarName . unLoc
857
858 hsExplicitLTyVarNames :: LHsQTyVars pass -> [IdP pass]
859 -- Explicit variables only
860 hsExplicitLTyVarNames qtvs = map hsLTyVarName (hsQTvExplicit qtvs)
861
862 hsAllLTyVarNames :: LHsQTyVars GhcRn -> [Name]
863 -- All variables
864 hsAllLTyVarNames (HsQTvs { hsq_implicit = kvs, hsq_explicit = tvs })
865 = kvs ++ map hsLTyVarName tvs
866
867 hsLTyVarLocName :: LHsTyVarBndr pass -> Located (IdP pass)
868 hsLTyVarLocName = fmap hsTyVarName
869
870 hsLTyVarLocNames :: LHsQTyVars pass -> [Located (IdP pass)]
871 hsLTyVarLocNames qtvs = map hsLTyVarLocName (hsQTvExplicit qtvs)
872
873 -- | Convert a LHsTyVarBndr to an equivalent LHsType.
874 hsLTyVarBndrToType :: LHsTyVarBndr pass -> LHsType pass
875 hsLTyVarBndrToType = fmap cvt
876 where cvt (UserTyVar n) = HsTyVar NotPromoted n
877 cvt (KindedTyVar (L name_loc n) kind)
878 = HsKindSig (L name_loc (HsTyVar NotPromoted (L name_loc n))) kind
879
880 -- | Convert a LHsTyVarBndrs to a list of types.
881 -- Works on *type* variable only, no kind vars.
882 hsLTyVarBndrsToTypes :: LHsQTyVars pass -> [LHsType pass]
883 hsLTyVarBndrsToTypes (HsQTvs { hsq_explicit = tvbs }) = map hsLTyVarBndrToType tvbs
884
885 ---------------------
886 wildCardName :: HsWildCardInfo GhcRn -> Name
887 wildCardName (AnonWildCard (L _ n)) = n
888
889 -- Two wild cards are the same when they have the same location
890 sameWildCard :: Located (HsWildCardInfo pass)
891 -> Located (HsWildCardInfo pass) -> Bool
892 sameWildCard (L l1 (AnonWildCard _)) (L l2 (AnonWildCard _)) = l1 == l2
893
894 ignoreParens :: LHsType pass -> LHsType pass
895 ignoreParens (L _ (HsParTy ty)) = ignoreParens ty
896 ignoreParens ty = ty
897
898 isLHsForAllTy :: LHsType p -> Bool
899 isLHsForAllTy (L _ (HsForAllTy {})) = True
900 isLHsForAllTy _ = False
901
902 {-
903 ************************************************************************
904 * *
905 Building types
906 * *
907 ************************************************************************
908 -}
909
910 mkAnonWildCardTy :: HsType GhcPs
911 mkAnonWildCardTy = HsWildCardTy (AnonWildCard PlaceHolder)
912
913 mkHsOpTy :: LHsType pass -> Located (IdP pass) -> LHsType pass -> HsType pass
914 mkHsOpTy ty1 op ty2 = HsOpTy ty1 op ty2
915
916 mkHsAppTy :: LHsType pass -> LHsType pass -> LHsType pass
917 mkHsAppTy t1 t2 = addCLoc t1 t2 (HsAppTy t1 (parenthesizeCompoundHsType t2))
918
919 mkHsAppTys :: LHsType pass -> [LHsType pass] -> LHsType pass
920 mkHsAppTys = foldl mkHsAppTy
921
922 mkHsAppsTy :: [LHsAppType GhcPs] -> HsType GhcPs
923 -- In the common case of a singleton non-operator,
924 -- avoid the clutter of wrapping in a HsAppsTy
925 mkHsAppsTy [L _ (HsAppPrefix (L _ ty))] = ty
926 mkHsAppsTy app_tys = HsAppsTy app_tys
927
928 {-
929 ************************************************************************
930 * *
931 Decomposing HsTypes
932 * *
933 ************************************************************************
934 -}
935
936 ---------------------------------
937 -- splitHsFunType decomposes a type (t1 -> t2 ... -> tn)
938 -- Breaks up any parens in the result type:
939 -- splitHsFunType (a -> (b -> c)) = ([a,b], c)
940 -- Also deals with (->) t1 t2; that is why it only works on LHsType Name
941 -- (see Trac #9096)
942 splitHsFunType :: LHsType GhcRn -> ([LHsType GhcRn], LHsType GhcRn)
943 splitHsFunType (L _ (HsParTy ty))
944 = splitHsFunType ty
945
946 splitHsFunType (L _ (HsFunTy x y))
947 | (args, res) <- splitHsFunType y
948 = (x:args, res)
949
950 splitHsFunType orig_ty@(L _ (HsAppTy t1 t2))
951 = go t1 [t2]
952 where -- Look for (->) t1 t2, possibly with parenthesisation
953 go (L _ (HsTyVar _ (L _ fn))) tys | fn == funTyConName
954 , [t1,t2] <- tys
955 , (args, res) <- splitHsFunType t2
956 = (t1:args, res)
957 go (L _ (HsAppTy t1 t2)) tys = go t1 (t2:tys)
958 go (L _ (HsParTy ty)) tys = go ty tys
959 go _ _ = ([], orig_ty) -- Failure to match
960
961 splitHsFunType other = ([], other)
962
963 --------------------------------
964 -- | Retrieves the head of an HsAppsTy, if this can be done unambiguously,
965 -- without consulting fixities.
966 getAppsTyHead_maybe :: [LHsAppType pass]
967 -> Maybe (LHsType pass, [LHsType pass], LexicalFixity)
968 getAppsTyHead_maybe tys = case splitHsAppsTy tys of
969 ([app1:apps], []) -> -- no symbols, some normal types
970 Just (mkHsAppTys app1 apps, [], Prefix)
971 ([app1l:appsl, app1r:appsr], [L loc op]) -> -- one operator
972 Just ( L loc (HsTyVar NotPromoted (L loc op))
973 , [mkHsAppTys app1l appsl, mkHsAppTys app1r appsr], Infix)
974 _ -> -- can't figure it out
975 Nothing
976
977 -- | Splits a [HsAppType pass] (the payload of an HsAppsTy) into regions of
978 -- prefix types (normal types) and infix operators.
979 -- If @splitHsAppsTy tys = (non_syms, syms)@, then @tys@ starts with the first
980 -- element of @non_syms@ followed by the first element of @syms@ followed by
981 -- the next element of @non_syms@, etc. It is guaranteed that the non_syms list
982 -- has one more element than the syms list.
983 splitHsAppsTy :: [LHsAppType pass] -> ([[LHsType pass]], [Located (IdP pass)])
984 splitHsAppsTy = go [] [] []
985 where
986 go acc acc_non acc_sym [] = (reverse (reverse acc : acc_non), reverse acc_sym)
987 go acc acc_non acc_sym (L _ (HsAppPrefix ty) : rest)
988 = go (ty : acc) acc_non acc_sym rest
989 go acc acc_non acc_sym (L _ (HsAppInfix op) : rest)
990 = go [] (reverse acc : acc_non) (op : acc_sym) rest
991
992 -- Retrieve the name of the "head" of a nested type application
993 -- somewhat like splitHsAppTys, but a little more thorough
994 -- used to examine the result of a GADT-like datacon, so it doesn't handle
995 -- *all* cases (like lists, tuples, (~), etc.)
996 hsTyGetAppHead_maybe :: LHsType pass
997 -> Maybe (Located (IdP pass), [LHsType pass])
998 hsTyGetAppHead_maybe = go []
999 where
1000 go tys (L _ (HsTyVar _ ln)) = Just (ln, tys)
1001 go tys (L _ (HsAppsTy apps))
1002 | Just (head, args, _) <- getAppsTyHead_maybe apps
1003 = go (args ++ tys) head
1004 go tys (L _ (HsAppTy l r)) = go (r : tys) l
1005 go tys (L _ (HsOpTy l (L loc n) r)) = Just (L loc n, l : r : tys)
1006 go tys (L _ (HsParTy t)) = go tys t
1007 go tys (L _ (HsKindSig t _)) = go tys t
1008 go _ _ = Nothing
1009
1010 splitHsAppTys :: LHsType GhcRn -> [LHsType GhcRn]
1011 -> (LHsType GhcRn, [LHsType GhcRn])
1012 -- no need to worry about HsAppsTy here
1013 splitHsAppTys (L _ (HsAppTy f a)) as = splitHsAppTys f (a:as)
1014 splitHsAppTys (L _ (HsParTy f)) as = splitHsAppTys f as
1015 splitHsAppTys f as = (f,as)
1016
1017 --------------------------------
1018 splitLHsPatSynTy :: LHsType pass
1019 -> ( [LHsTyVarBndr pass] -- universals
1020 , LHsContext pass -- required constraints
1021 , [LHsTyVarBndr pass] -- existentials
1022 , LHsContext pass -- provided constraints
1023 , LHsType pass) -- body type
1024 splitLHsPatSynTy ty = (univs, reqs, exis, provs, ty4)
1025 where
1026 (univs, ty1) = splitLHsForAllTy ty
1027 (reqs, ty2) = splitLHsQualTy ty1
1028 (exis, ty3) = splitLHsForAllTy ty2
1029 (provs, ty4) = splitLHsQualTy ty3
1030
1031 splitLHsSigmaTy :: LHsType pass
1032 -> ([LHsTyVarBndr pass], LHsContext pass, LHsType pass)
1033 splitLHsSigmaTy ty
1034 | (tvs, ty1) <- splitLHsForAllTy ty
1035 , (ctxt, ty2) <- splitLHsQualTy ty1
1036 = (tvs, ctxt, ty2)
1037
1038 splitLHsForAllTy :: LHsType pass -> ([LHsTyVarBndr pass], LHsType pass)
1039 splitLHsForAllTy (L _ (HsParTy ty)) = splitLHsForAllTy ty
1040 splitLHsForAllTy (L _ (HsForAllTy { hst_bndrs = tvs, hst_body = body })) = (tvs, body)
1041 splitLHsForAllTy body = ([], body)
1042
1043 splitLHsQualTy :: LHsType pass -> (LHsContext pass, LHsType pass)
1044 splitLHsQualTy (L _ (HsParTy ty)) = splitLHsQualTy ty
1045 splitLHsQualTy (L _ (HsQualTy { hst_ctxt = ctxt, hst_body = body })) = (ctxt, body)
1046 splitLHsQualTy body = (noLoc [], body)
1047
1048 splitLHsInstDeclTy :: LHsSigType GhcRn
1049 -> ([Name], LHsContext GhcRn, LHsType GhcRn)
1050 -- Split up an instance decl type, returning the pieces
1051 splitLHsInstDeclTy (HsIB { hsib_vars = itkvs
1052 , hsib_body = inst_ty })
1053 | (tvs, cxt, body_ty) <- splitLHsSigmaTy inst_ty
1054 = (itkvs ++ map hsLTyVarName tvs, cxt, body_ty)
1055 -- Return implicitly bound type and kind vars
1056 -- For an instance decl, all of them are in scope
1057
1058 getLHsInstDeclHead :: LHsSigType pass -> LHsType pass
1059 getLHsInstDeclHead inst_ty
1060 | (_tvs, _cxt, body_ty) <- splitLHsSigmaTy (hsSigType inst_ty)
1061 = body_ty
1062
1063 getLHsInstDeclClass_maybe :: LHsSigType pass -> Maybe (Located (IdP pass))
1064 -- Works on (HsSigType RdrName)
1065 getLHsInstDeclClass_maybe inst_ty
1066 = do { let head_ty = getLHsInstDeclHead inst_ty
1067 ; (cls, _) <- hsTyGetAppHead_maybe head_ty
1068 ; return cls }
1069
1070 {-
1071 ************************************************************************
1072 * *
1073 FieldOcc
1074 * *
1075 ************************************************************************
1076 -}
1077
1078 -- | Located Field Occurrence
1079 type LFieldOcc pass = Located (FieldOcc pass)
1080
1081 -- | Field Occurrence
1082 --
1083 -- Represents an *occurrence* of an unambiguous field. We store
1084 -- both the 'RdrName' the user originally wrote, and after the
1085 -- renamer, the selector function.
1086 data FieldOcc pass = FieldOcc { rdrNameFieldOcc :: Located RdrName
1087 -- ^ See Note [Located RdrNames] in HsExpr
1088 , selectorFieldOcc :: PostRn pass (IdP pass)
1089 }
1090 deriving instance Eq (PostRn pass (IdP pass)) => Eq (FieldOcc pass)
1091 deriving instance Ord (PostRn pass (IdP pass)) => Ord (FieldOcc pass)
1092 deriving instance (DataId pass) => Data (FieldOcc pass)
1093
1094 instance Outputable (FieldOcc pass) where
1095 ppr = ppr . rdrNameFieldOcc
1096
1097 mkFieldOcc :: Located RdrName -> FieldOcc GhcPs
1098 mkFieldOcc rdr = FieldOcc rdr PlaceHolder
1099
1100
1101 -- | Ambiguous Field Occurrence
1102 --
1103 -- Represents an *occurrence* of a field that is potentially
1104 -- ambiguous after the renamer, with the ambiguity resolved by the
1105 -- typechecker. We always store the 'RdrName' that the user
1106 -- originally wrote, and store the selector function after the renamer
1107 -- (for unambiguous occurrences) or the typechecker (for ambiguous
1108 -- occurrences).
1109 --
1110 -- See Note [HsRecField and HsRecUpdField] in HsPat and
1111 -- Note [Disambiguating record fields] in TcExpr.
1112 -- See Note [Located RdrNames] in HsExpr
1113 data AmbiguousFieldOcc pass
1114 = Unambiguous (Located RdrName) (PostRn pass (IdP pass))
1115 | Ambiguous (Located RdrName) (PostTc pass (IdP pass))
1116 deriving instance DataId pass => Data (AmbiguousFieldOcc pass)
1117
1118 instance Outputable (AmbiguousFieldOcc pass) where
1119 ppr = ppr . rdrNameAmbiguousFieldOcc
1120
1121 instance OutputableBndr (AmbiguousFieldOcc pass) where
1122 pprInfixOcc = pprInfixOcc . rdrNameAmbiguousFieldOcc
1123 pprPrefixOcc = pprPrefixOcc . rdrNameAmbiguousFieldOcc
1124
1125 mkAmbiguousFieldOcc :: Located RdrName -> AmbiguousFieldOcc GhcPs
1126 mkAmbiguousFieldOcc rdr = Unambiguous rdr PlaceHolder
1127
1128 rdrNameAmbiguousFieldOcc :: AmbiguousFieldOcc pass -> RdrName
1129 rdrNameAmbiguousFieldOcc (Unambiguous (L _ rdr) _) = rdr
1130 rdrNameAmbiguousFieldOcc (Ambiguous (L _ rdr) _) = rdr
1131
1132 selectorAmbiguousFieldOcc :: AmbiguousFieldOcc GhcTc -> Id
1133 selectorAmbiguousFieldOcc (Unambiguous _ sel) = sel
1134 selectorAmbiguousFieldOcc (Ambiguous _ sel) = sel
1135
1136 unambiguousFieldOcc :: AmbiguousFieldOcc GhcTc -> FieldOcc GhcTc
1137 unambiguousFieldOcc (Unambiguous rdr sel) = FieldOcc rdr sel
1138 unambiguousFieldOcc (Ambiguous rdr sel) = FieldOcc rdr sel
1139
1140 ambiguousFieldOcc :: FieldOcc pass -> AmbiguousFieldOcc pass
1141 ambiguousFieldOcc (FieldOcc rdr sel) = Unambiguous rdr sel
1142
1143 {-
1144 ************************************************************************
1145 * *
1146 \subsection{Pretty printing}
1147 * *
1148 ************************************************************************
1149 -}
1150
1151 instance (SourceTextX pass, OutputableBndrId pass)
1152 => Outputable (HsType pass) where
1153 ppr ty = pprHsType ty
1154
1155 instance Outputable HsTyLit where
1156 ppr = ppr_tylit
1157
1158 instance (SourceTextX pass, OutputableBndrId pass)
1159 => Outputable (LHsQTyVars pass) where
1160 ppr (HsQTvs { hsq_explicit = tvs }) = interppSP tvs
1161
1162 instance (SourceTextX pass, OutputableBndrId pass)
1163 => Outputable (HsTyVarBndr pass) where
1164 ppr (UserTyVar n) = ppr n
1165 ppr (KindedTyVar n k) = parens $ hsep [ppr n, dcolon, ppr k]
1166
1167 instance (Outputable thing) => Outputable (HsImplicitBndrs pass thing) where
1168 ppr (HsIB { hsib_body = ty }) = ppr ty
1169
1170 instance (Outputable thing) => Outputable (HsWildCardBndrs pass thing) where
1171 ppr (HsWC { hswc_body = ty }) = ppr ty
1172
1173 instance Outputable (HsWildCardInfo pass) where
1174 ppr (AnonWildCard _) = char '_'
1175
1176 pprHsForAll :: (SourceTextX pass, OutputableBndrId pass)
1177 => [LHsTyVarBndr pass] -> LHsContext pass -> SDoc
1178 pprHsForAll = pprHsForAllExtra Nothing
1179
1180 -- | Version of 'pprHsForAll' that can also print an extra-constraints
1181 -- wildcard, e.g. @_ => a -> Bool@ or @(Show a, _) => a -> String@. This
1182 -- underscore will be printed when the 'Maybe SrcSpan' argument is a 'Just'
1183 -- containing the location of the extra-constraints wildcard. A special
1184 -- function for this is needed, as the extra-constraints wildcard is removed
1185 -- from the actual context and type, and stored in a separate field, thus just
1186 -- printing the type will not print the extra-constraints wildcard.
1187 pprHsForAllExtra :: (SourceTextX pass, OutputableBndrId pass)
1188 => Maybe SrcSpan -> [LHsTyVarBndr pass] -> LHsContext pass
1189 -> SDoc
1190 pprHsForAllExtra extra qtvs cxt
1191 = pprHsForAllTvs qtvs <+> pprHsContextExtra show_extra (unLoc cxt)
1192 where
1193 show_extra = isJust extra
1194
1195 pprHsForAllTvs :: (SourceTextX pass, OutputableBndrId pass)
1196 => [LHsTyVarBndr pass] -> SDoc
1197 pprHsForAllTvs qtvs
1198 | null qtvs = whenPprDebug (forAllLit <+> dot)
1199 | otherwise = forAllLit <+> interppSP qtvs <> dot
1200
1201 pprHsContext :: (SourceTextX pass, OutputableBndrId pass)
1202 => HsContext pass -> SDoc
1203 pprHsContext = maybe empty (<+> darrow) . pprHsContextMaybe
1204
1205 pprHsContextNoArrow :: (SourceTextX pass, OutputableBndrId pass)
1206 => HsContext pass -> SDoc
1207 pprHsContextNoArrow = fromMaybe empty . pprHsContextMaybe
1208
1209 pprHsContextMaybe :: (SourceTextX pass, OutputableBndrId pass)
1210 => HsContext pass -> Maybe SDoc
1211 pprHsContextMaybe [] = Nothing
1212 pprHsContextMaybe [L _ pred] = Just $ ppr_mono_ty pred
1213 pprHsContextMaybe cxt = Just $ parens (interpp'SP cxt)
1214
1215 -- For use in a HsQualTy, which always gets printed if it exists.
1216 pprHsContextAlways :: (SourceTextX pass, OutputableBndrId pass)
1217 => HsContext pass -> SDoc
1218 pprHsContextAlways [] = parens empty <+> darrow
1219 pprHsContextAlways [L _ ty] = ppr_mono_ty ty <+> darrow
1220 pprHsContextAlways cxt = parens (interpp'SP cxt) <+> darrow
1221
1222 -- True <=> print an extra-constraints wildcard, e.g. @(Show a, _) =>@
1223 pprHsContextExtra :: (SourceTextX pass, OutputableBndrId pass)
1224 => Bool -> HsContext pass -> SDoc
1225 pprHsContextExtra show_extra ctxt
1226 | not show_extra
1227 = pprHsContext ctxt
1228 | null ctxt
1229 = char '_' <+> darrow
1230 | otherwise
1231 = parens (sep (punctuate comma ctxt')) <+> darrow
1232 where
1233 ctxt' = map ppr ctxt ++ [char '_']
1234
1235 pprConDeclFields :: (SourceTextX pass, OutputableBndrId pass)
1236 => [LConDeclField pass] -> SDoc
1237 pprConDeclFields fields = braces (sep (punctuate comma (map ppr_fld fields)))
1238 where
1239 ppr_fld (L _ (ConDeclField { cd_fld_names = ns, cd_fld_type = ty,
1240 cd_fld_doc = doc }))
1241 = ppr_names ns <+> dcolon <+> ppr ty <+> ppr_mbDoc doc
1242 ppr_names [n] = ppr n
1243 ppr_names ns = sep (punctuate comma (map ppr ns))
1244
1245 {-
1246 Note [Printing KindedTyVars]
1247 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1248 Trac #3830 reminded me that we should really only print the kind
1249 signature on a KindedTyVar if the kind signature was put there by the
1250 programmer. During kind inference GHC now adds a PostTcKind to UserTyVars,
1251 rather than converting to KindedTyVars as before.
1252
1253 (As it happens, the message in #3830 comes out a different way now,
1254 and the problem doesn't show up; but having the flag on a KindedTyVar
1255 seems like the Right Thing anyway.)
1256 -}
1257
1258 -- Printing works more-or-less as for Types
1259
1260 pprHsType :: (SourceTextX pass, OutputableBndrId pass) => HsType pass -> SDoc
1261 pprHsType ty = ppr_mono_ty ty
1262
1263 ppr_mono_lty :: (SourceTextX pass, OutputableBndrId pass)
1264 => LHsType pass -> SDoc
1265 ppr_mono_lty ty = ppr_mono_ty (unLoc ty)
1266
1267 ppr_mono_ty :: (SourceTextX pass, OutputableBndrId pass)
1268 => HsType pass -> SDoc
1269 ppr_mono_ty (HsForAllTy { hst_bndrs = tvs, hst_body = ty })
1270 = sep [pprHsForAllTvs tvs, ppr_mono_lty ty]
1271
1272 ppr_mono_ty (HsQualTy { hst_ctxt = L _ ctxt, hst_body = ty })
1273 = sep [pprHsContextAlways ctxt, ppr_mono_lty ty]
1274
1275 ppr_mono_ty (HsBangTy b ty) = ppr b <> ppr_mono_lty ty
1276 ppr_mono_ty (HsRecTy flds) = pprConDeclFields flds
1277 ppr_mono_ty (HsTyVar NotPromoted (L _ name))= pprPrefixOcc name
1278 ppr_mono_ty (HsTyVar Promoted (L _ name))
1279 = space <> quote (pprPrefixOcc name)
1280 -- We need a space before the ' above, so the parser
1281 -- does not attach it to the previous symbol
1282 ppr_mono_ty (HsFunTy ty1 ty2) = ppr_fun_ty ty1 ty2
1283 ppr_mono_ty (HsTupleTy con tys) = tupleParens std_con (pprWithCommas ppr tys)
1284 where std_con = case con of
1285 HsUnboxedTuple -> UnboxedTuple
1286 _ -> BoxedTuple
1287 ppr_mono_ty (HsSumTy tys) = tupleParens UnboxedTuple (pprWithBars ppr tys)
1288 ppr_mono_ty (HsKindSig ty kind) = parens (ppr_mono_lty ty <+> dcolon <+> ppr kind)
1289 ppr_mono_ty (HsListTy ty) = brackets (ppr_mono_lty ty)
1290 ppr_mono_ty (HsPArrTy ty) = paBrackets (ppr_mono_lty ty)
1291 ppr_mono_ty (HsIParamTy n ty) = (ppr n <+> dcolon <+> ppr_mono_lty ty)
1292 ppr_mono_ty (HsSpliceTy s _) = pprSplice s
1293 ppr_mono_ty (HsCoreTy ty) = ppr ty
1294 ppr_mono_ty (HsExplicitListTy Promoted _ tys)
1295 = quote $ brackets (interpp'SP tys)
1296 ppr_mono_ty (HsExplicitListTy NotPromoted _ tys)
1297 = brackets (interpp'SP tys)
1298 ppr_mono_ty (HsExplicitTupleTy _ tys) = quote $ parens (interpp'SP tys)
1299 ppr_mono_ty (HsTyLit t) = ppr_tylit t
1300 ppr_mono_ty (HsWildCardTy {}) = char '_'
1301
1302 ppr_mono_ty (HsEqTy ty1 ty2)
1303 = ppr_mono_lty ty1 <+> char '~' <+> ppr_mono_lty ty2
1304
1305 ppr_mono_ty (HsAppsTy tys)
1306 = hsep (map (ppr_app_ty . unLoc) tys)
1307
1308 ppr_mono_ty (HsAppTy fun_ty arg_ty)
1309 = hsep [ppr_mono_lty fun_ty, ppr_mono_lty arg_ty]
1310
1311 ppr_mono_ty (HsOpTy ty1 (L _ op) ty2)
1312 = sep [ ppr_mono_lty ty1
1313 , sep [pprInfixOcc op, ppr_mono_lty ty2 ] ]
1314
1315 ppr_mono_ty (HsParTy ty)
1316 = parens (ppr_mono_lty ty)
1317 -- Put the parens in where the user did
1318 -- But we still use the precedence stuff to add parens because
1319 -- toHsType doesn't put in any HsParTys, so we may still need them
1320
1321 ppr_mono_ty (HsDocTy ty doc)
1322 -- AZ: Should we add parens? Should we introduce "-- ^"?
1323 = ppr_mono_lty ty <+> ppr (unLoc doc)
1324 -- we pretty print Haddock comments on types as if they were
1325 -- postfix operators
1326
1327 --------------------------
1328 ppr_fun_ty :: (SourceTextX pass, OutputableBndrId pass)
1329 => LHsType pass -> LHsType pass -> SDoc
1330 ppr_fun_ty ty1 ty2
1331 = let p1 = ppr_mono_lty ty1
1332 p2 = ppr_mono_lty ty2
1333 in
1334 sep [p1, text "->" <+> p2]
1335
1336 --------------------------
1337 ppr_app_ty :: (SourceTextX pass, OutputableBndrId pass)
1338 => HsAppType pass -> SDoc
1339 ppr_app_ty (HsAppInfix (L _ n)) = pprInfixOcc n
1340 ppr_app_ty (HsAppPrefix (L _ (HsTyVar NotPromoted (L _ n))))
1341 = pprPrefixOcc n
1342 ppr_app_ty (HsAppPrefix (L _ (HsTyVar Promoted (L _ n))))
1343 = space <> quote (pprPrefixOcc n) -- We need a space before the ' above, so
1344 -- the parser does not attach it to the
1345 -- previous symbol
1346 ppr_app_ty (HsAppPrefix ty) = ppr_mono_lty ty
1347
1348 --------------------------
1349 ppr_tylit :: HsTyLit -> SDoc
1350 ppr_tylit (HsNumTy _ i) = integer i
1351 ppr_tylit (HsStrTy _ s) = text (show s)
1352
1353
1354 -- | Return 'True' for compound types that will need parentheses when used in
1355 -- an argument position.
1356 isCompoundHsType :: LHsType pass -> Bool
1357 isCompoundHsType (L _ HsAppTy{} ) = True
1358 isCompoundHsType (L _ HsAppsTy{}) = True
1359 isCompoundHsType (L _ HsEqTy{} ) = True
1360 isCompoundHsType (L _ HsFunTy{} ) = True
1361 isCompoundHsType (L _ HsOpTy{} ) = True
1362 isCompoundHsType _ = False
1363
1364 -- | @'parenthesizeCompoundHsType' ty@ checks if @'isCompoundHsType' ty@ is
1365 -- true, and if so, surrounds @ty@ with an 'HsParTy'. Otherwise, it simply
1366 -- returns @ty@.
1367 parenthesizeCompoundHsType :: LHsType pass -> LHsType pass
1368 parenthesizeCompoundHsType ty@(L loc _)
1369 | isCompoundHsType ty = L loc (HsParTy ty)
1370 | otherwise = ty