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