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