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