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