Remove HsContext from ppr_mono_ty, and remove ppParendHsType
[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 ( PostTc,PostRn,DataId,PlaceHolder(..),
74 OutputableBndrId )
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 name = Located (BangType name)
105
106 -- | Bang Type
107 type BangType name = HsType name -- 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 name = Located (HsContext name)
223 -- ^ 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnUnit'
224
225 -- For details on above see note [Api annotations] in ApiAnnotation
226
227 -- | Haskell Context
228 type HsContext name = [LHsType name]
229
230 -- | Located Haskell Type
231 type LHsType name = Located (HsType name)
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 name = HsType name
239
240 -- | Located Haskell Kind
241 type LHsKind name = Located (HsKind name)
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 name = Located (HsTyVarBndr name)
252 -- See Note [HsType binders]
253
254 -- | Located Haskell Quantified Type Variables
255 data LHsQTyVars name -- See Note [HsType binders]
256 = HsQTvs { hsq_implicit :: PostRn name [Name] -- implicit (dependent) variables
257 , hsq_explicit :: [LHsTyVarBndr name] -- explicit variables
258 -- See Note [HsForAllTy tyvar binders]
259 , hsq_dependent :: PostRn name NameSet
260 -- which explicit vars are dependent
261 -- See Note [Dependent LHsQTyVars] in TcHsType
262 }
263
264 deriving instance (DataId name) => Data (LHsQTyVars name)
265
266 mkHsQTvs :: [LHsTyVarBndr RdrName] -> LHsQTyVars RdrName
267 mkHsQTvs tvs = HsQTvs { hsq_implicit = PlaceHolder, hsq_explicit = tvs
268 , hsq_dependent = PlaceHolder }
269
270 hsQTvExplicit :: LHsQTyVars name -> [LHsTyVarBndr name]
271 hsQTvExplicit = hsq_explicit
272
273 emptyLHsQTvs :: LHsQTyVars Name
274 emptyLHsQTvs = HsQTvs [] [] emptyNameSet
275
276 isEmptyLHsQTvs :: LHsQTyVars Name -> Bool
277 isEmptyLHsQTvs (HsQTvs [] [] _) = True
278 isEmptyLHsQTvs _ = False
279
280 ------------------------------------------------
281 -- HsImplicitBndrs
282 -- Used to quantify the binders of a type in cases
283 -- when a HsForAll isn't appropriate:
284 -- * Patterns in a type/data family instance (HsTyPats)
285 -- * Type of a rule binder (RuleBndr)
286 -- * Pattern type signatures (SigPatIn)
287 -- In the last of these, wildcards can happen, so we must accommodate them
288
289 -- | Haskell Implicit Binders
290 data HsImplicitBndrs name thing -- See Note [HsType binders]
291 = HsIB { hsib_vars :: PostRn name [Name] -- Implicitly-bound kind & type vars
292 , hsib_body :: thing -- Main payload (type or list of types)
293 , hsib_closed :: PostRn name Bool -- Taking the hsib_vars into account,
294 -- is the payload closed? Used in
295 -- TcHsType.decideKindGeneralisationPlan
296 }
297
298 -- | Haskell Wildcard Binders
299 data HsWildCardBndrs name thing
300 -- See Note [HsType binders]
301 -- See Note [The wildcard story for types]
302 = HsWC { hswc_wcs :: PostRn name [Name]
303 -- Wild cards, both named and anonymous
304 -- after the renamer
305
306 , hswc_body :: thing
307 -- Main payload (type or list of types)
308 -- If there is an extra-constraints wildcard,
309 -- it's still there in the hsc_body.
310 }
311
312 deriving instance (Data name, Data thing, Data (PostRn name [Name]), Data (PostRn name Bool))
313 => Data (HsImplicitBndrs name thing)
314
315 deriving instance (Data name, Data thing, Data (PostRn name [Name]))
316 => Data (HsWildCardBndrs name thing)
317
318 -- | Located Haskell Signature Type
319 type LHsSigType name = HsImplicitBndrs name (LHsType name) -- Implicit only
320
321 -- | Located Haskell Wildcard Type
322 type LHsWcType name = HsWildCardBndrs name (LHsType name) -- Wildcard only
323
324 -- | Located Haskell Signature Wildcard Type
325 type LHsSigWcType name = HsWildCardBndrs name (LHsSigType name) -- Both
326
327 -- See Note [Representing type signatures]
328
329 hsImplicitBody :: HsImplicitBndrs name thing -> thing
330 hsImplicitBody (HsIB { hsib_body = body }) = body
331
332 hsSigType :: LHsSigType name -> LHsType name
333 hsSigType = hsImplicitBody
334
335 hsSigWcType :: LHsSigWcType name -> LHsType name
336 hsSigWcType sig_ty = hsib_body (hswc_body sig_ty)
337
338 dropWildCards :: LHsSigWcType name -> LHsSigType name
339 -- Drop the wildcard part of a LHsSigWcType
340 dropWildCards sig_ty = hswc_body sig_ty
341
342 {- Note [Representing type signatures]
343 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
344 HsSigType is used to represent an explicit user type signature
345 such as f :: a -> a
346 or g (x :: a -> a) = x
347
348 A HsSigType is just a HsImplicitBndrs wrapping a LHsType.
349 * The HsImplicitBndrs binds the /implicitly/ quantified tyvars
350 * The LHsType binds the /explicitly/ quantified tyvars
351
352 E.g. For a signature like
353 f :: forall (a::k). blah
354 we get
355 HsIB { hsib_vars = [k]
356 , hsib_body = HsForAllTy { hst_bndrs = [(a::*)]
357 , hst_body = blah }
358 The implicit kind variable 'k' is bound by the HsIB;
359 the explicitly forall'd tyvar 'a' is bound by the HsForAllTy
360 -}
361
362 mkHsImplicitBndrs :: thing -> HsImplicitBndrs RdrName thing
363 mkHsImplicitBndrs x = HsIB { hsib_body = x
364 , hsib_vars = PlaceHolder
365 , hsib_closed = PlaceHolder }
366
367 mkHsWildCardBndrs :: thing -> HsWildCardBndrs RdrName thing
368 mkHsWildCardBndrs x = HsWC { hswc_body = x
369 , hswc_wcs = PlaceHolder }
370
371 -- Add empty binders. This is a bit suspicious; what if
372 -- the wrapped thing had free type variables?
373 mkEmptyImplicitBndrs :: thing -> HsImplicitBndrs Name thing
374 mkEmptyImplicitBndrs x = HsIB { hsib_body = x
375 , hsib_vars = []
376 , hsib_closed = False }
377
378 mkEmptyWildCardBndrs :: thing -> HsWildCardBndrs Name thing
379 mkEmptyWildCardBndrs x = HsWC { hswc_body = x
380 , hswc_wcs = [] }
381
382
383 --------------------------------------------------
384 -- | These names are used early on to store the names of implicit
385 -- parameters. They completely disappear after type-checking.
386 newtype HsIPName = HsIPName FastString
387 deriving( Eq, Data )
388
389 hsIPNameFS :: HsIPName -> FastString
390 hsIPNameFS (HsIPName n) = n
391
392 instance Outputable HsIPName where
393 ppr (HsIPName n) = char '?' <> ftext n -- Ordinary implicit parameters
394
395 instance OutputableBndr HsIPName where
396 pprBndr _ n = ppr n -- Simple for now
397 pprInfixOcc n = ppr n
398 pprPrefixOcc n = ppr n
399
400 --------------------------------------------------
401
402 -- | Haskell Type Variable Binder
403 data HsTyVarBndr name
404 = UserTyVar -- no explicit kinding
405 (Located name)
406 -- See Note [Located RdrNames] in HsExpr
407 | KindedTyVar
408 (Located name)
409 (LHsKind name) -- The user-supplied kind signature
410 -- ^
411 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
412 -- 'ApiAnnotation.AnnDcolon', 'ApiAnnotation.AnnClose'
413
414 -- For details on above see note [Api annotations] in ApiAnnotation
415 deriving instance (DataId name) => Data (HsTyVarBndr name)
416
417 -- | Does this 'HsTyVarBndr' come with an explicit kind annotation?
418 isHsKindedTyVar :: HsTyVarBndr name -> Bool
419 isHsKindedTyVar (UserTyVar {}) = False
420 isHsKindedTyVar (KindedTyVar {}) = True
421
422 -- | Do all type variables in this 'LHsQTyVars' come with kind annotations?
423 hsTvbAllKinded :: LHsQTyVars name -> Bool
424 hsTvbAllKinded = all (isHsKindedTyVar . unLoc) . hsQTvExplicit
425
426 -- | Haskell Type
427 data HsType name
428 = HsForAllTy -- See Note [HsType binders]
429 { hst_bndrs :: [LHsTyVarBndr name] -- Explicit, user-supplied 'forall a b c'
430 , hst_body :: LHsType name -- body type
431 }
432 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnForall',
433 -- 'ApiAnnotation.AnnDot','ApiAnnotation.AnnDarrow'
434 -- For details on above see note [Api annotations] in ApiAnnotation
435
436 | HsQualTy -- See Note [HsType binders]
437 { hst_ctxt :: LHsContext name -- Context C => blah
438 , hst_body :: LHsType name }
439
440 | HsTyVar Promoted -- whether explicitly promoted, for the pretty
441 -- printer
442 (Located name)
443 -- Type variable, type constructor, or data constructor
444 -- see Note [Promotions (HsTyVar)]
445 -- See Note [Located RdrNames] in HsExpr
446 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
447
448 -- For details on above see note [Api annotations] in ApiAnnotation
449
450 | HsAppsTy [LHsAppType name] -- Used only before renaming,
451 -- Note [HsAppsTy]
452 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
453
454 | HsAppTy (LHsType name)
455 (LHsType name)
456 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
457
458 -- For details on above see note [Api annotations] in ApiAnnotation
459
460 | HsFunTy (LHsType name) -- function type
461 (LHsType name)
462 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow',
463
464 -- For details on above see note [Api annotations] in ApiAnnotation
465
466 | HsListTy (LHsType name) -- Element type
467 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
468 -- 'ApiAnnotation.AnnClose' @']'@
469
470 -- For details on above see note [Api annotations] in ApiAnnotation
471
472 | HsPArrTy (LHsType name) -- Elem. type of parallel array: [:t:]
473 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
474 -- 'ApiAnnotation.AnnClose' @':]'@
475
476 -- For details on above see note [Api annotations] in ApiAnnotation
477
478 | HsTupleTy HsTupleSort
479 [LHsType name] -- Element types (length gives arity)
480 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(' or '(#'@,
481 -- 'ApiAnnotation.AnnClose' @')' or '#)'@
482
483 -- For details on above see note [Api annotations] in ApiAnnotation
484
485 | HsSumTy [LHsType name] -- Element types (length gives arity)
486 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(#'@,
487 -- 'ApiAnnotation.AnnClose' '#)'@
488
489 -- For details on above see note [Api annotations] in ApiAnnotation
490
491 | HsOpTy (LHsType name) (Located name) (LHsType name)
492 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
493
494 -- For details on above see note [Api annotations] in ApiAnnotation
495
496 | HsParTy (LHsType name) -- See Note [Parens in HsSyn] in HsExpr
497 -- Parenthesis preserved for the precedence re-arrangement in RnTypes
498 -- It's important that a * (b + c) doesn't get rearranged to (a*b) + c!
499 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
500 -- 'ApiAnnotation.AnnClose' @')'@
501
502 -- For details on above see note [Api annotations] in ApiAnnotation
503
504 | HsIParamTy (Located HsIPName) -- (?x :: ty)
505 (LHsType name) -- Implicit parameters as they occur in contexts
506 -- ^
507 -- > (?x :: ty)
508 --
509 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
510
511 -- For details on above see note [Api annotations] in ApiAnnotation
512
513 | HsEqTy (LHsType name) -- ty1 ~ ty2
514 (LHsType name) -- Always allowed even without TypeOperators, and has special kinding rule
515 -- ^
516 -- > ty1 ~ ty2
517 --
518 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde'
519
520 -- For details on above see note [Api annotations] in ApiAnnotation
521
522 | HsKindSig (LHsType name) -- (ty :: kind)
523 (LHsKind name) -- A type with a kind signature
524 -- ^
525 -- > (ty :: kind)
526 --
527 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
528 -- 'ApiAnnotation.AnnDcolon','ApiAnnotation.AnnClose' @')'@
529
530 -- For details on above see note [Api annotations] in ApiAnnotation
531
532 | HsSpliceTy (HsSplice name) -- Includes quasi-quotes
533 (PostTc name Kind)
534 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'$('@,
535 -- 'ApiAnnotation.AnnClose' @')'@
536
537 -- For details on above see note [Api annotations] in ApiAnnotation
538
539 | HsDocTy (LHsType name) LHsDocString -- A documented type
540 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
541
542 -- For details on above see note [Api annotations] in ApiAnnotation
543
544 | HsBangTy HsSrcBang (LHsType name) -- Bang-style type annotations
545 -- ^ - 'ApiAnnotation.AnnKeywordId' :
546 -- 'ApiAnnotation.AnnOpen' @'{-\# UNPACK' or '{-\# NOUNPACK'@,
547 -- 'ApiAnnotation.AnnClose' @'#-}'@
548 -- 'ApiAnnotation.AnnBang' @\'!\'@
549
550 -- For details on above see note [Api annotations] in ApiAnnotation
551
552 | HsRecTy [LConDeclField name] -- Only in data type declarations
553 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
554 -- 'ApiAnnotation.AnnClose' @'}'@
555
556 -- For details on above see note [Api annotations] in ApiAnnotation
557
558 | HsCoreTy Type -- An escape hatch for tunnelling a *closed*
559 -- Core Type through HsSyn.
560 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
561
562 -- For details on above see note [Api annotations] in ApiAnnotation
563
564 | HsExplicitListTy -- A promoted explicit list
565 Promoted -- whether explcitly promoted, for pretty printer
566 (PostTc name Kind) -- See Note [Promoted lists and tuples]
567 [LHsType name]
568 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @"'["@,
569 -- 'ApiAnnotation.AnnClose' @']'@
570
571 -- For details on above see note [Api annotations] in ApiAnnotation
572
573 | HsExplicitTupleTy -- A promoted explicit tuple
574 [PostTc name Kind] -- See Note [Promoted lists and tuples]
575 [LHsType name]
576 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @"'("@,
577 -- 'ApiAnnotation.AnnClose' @')'@
578
579 -- For details on above see note [Api annotations] in ApiAnnotation
580
581 | HsTyLit HsTyLit -- A promoted numeric literal.
582 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
583
584 -- For details on above see note [Api annotations] in ApiAnnotation
585
586 | HsWildCardTy (HsWildCardInfo name) -- A type wildcard
587 -- See Note [The wildcard story for types]
588 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
589
590 -- For details on above see note [Api annotations] in ApiAnnotation
591 deriving instance (DataId name) => Data (HsType name)
592
593 -- Note [Literal source text] in BasicTypes for SourceText fields in
594 -- the following
595 -- | Haskell Type Literal
596 data HsTyLit
597 = HsNumTy SourceText Integer
598 | HsStrTy SourceText FastString
599 deriving Data
600
601 newtype HsWildCardInfo name -- See Note [The wildcard story for types]
602 = AnonWildCard (PostRn name (Located Name))
603 -- A anonymous wild card ('_'). A fresh Name is generated for
604 -- each individual anonymous wildcard during renaming
605 deriving instance (DataId name) => Data (HsWildCardInfo name)
606
607 -- | Located Haskell Application Type
608 type LHsAppType name = Located (HsAppType name)
609 -- ^ 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSimpleQuote'
610
611 -- | Haskell Application Type
612 data HsAppType name
613 = HsAppInfix (Located name) -- either a symbol or an id in backticks
614 | HsAppPrefix (LHsType name) -- anything else, including things like (+)
615 deriving instance (DataId name) => Data (HsAppType name)
616
617 instance (OutputableBndrId name) => Outputable (HsAppType name) 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 name = Located (ConDeclField name)
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 name -- Record fields have Haddoc docs on them
752 = ConDeclField { cd_fld_names :: [LFieldOcc name],
753 -- ^ See Note [ConDeclField names]
754 cd_fld_type :: LBangType name,
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 name) => Data (ConDeclField name)
760
761 instance (OutputableBndrId name) => Outputable (ConDeclField name) where
762 ppr (ConDeclField fld_n fld_ty _) = ppr fld_n <+> dcolon <+> ppr fld_ty
763
764 -- HsConDetails is used for patterns/expressions *and* for data type
765 -- declarations
766 -- | Haskell Constructor Details
767 data HsConDetails arg rec
768 = PrefixCon [arg] -- C p1 p2 p3
769 | RecCon rec -- C { x = p1, y = p2 }
770 | InfixCon arg arg -- p1 `C` p2
771 deriving Data
772
773 instance (Outputable arg, Outputable rec)
774 => Outputable (HsConDetails arg rec) where
775 ppr (PrefixCon args) = text "PrefixCon" <+> ppr args
776 ppr (RecCon rec) = text "RecCon:" <+> ppr rec
777 ppr (InfixCon l r) = text "InfixCon:" <+> ppr [l, r]
778
779 -- Takes details and result type of a GADT data constructor as created by the
780 -- parser and rejigs them using information about fixities from the renamer.
781 -- See Note [Sorting out the result type] in RdrHsSyn
782 updateGadtResult
783 :: (Monad m)
784 => (SDoc -> m ())
785 -> SDoc
786 -> HsConDetails (LHsType Name) (Located [LConDeclField Name])
787 -- ^ Original details
788 -> LHsType Name -- ^ Original result type
789 -> m (HsConDetails (LHsType Name) (Located [LConDeclField Name]),
790 LHsType Name)
791 updateGadtResult failWith doc details ty
792 = do { let (arg_tys, res_ty) = splitHsFunType ty
793 badConSig = text "Malformed constructor signature"
794 ; case details of
795 InfixCon {} -> pprPanic "updateGadtResult" (ppr ty)
796
797 RecCon {} -> do { unless (null arg_tys)
798 (failWith (doc <+> badConSig))
799 ; return (details, res_ty) }
800
801 PrefixCon {} -> return (PrefixCon arg_tys, res_ty)}
802
803 {-
804 Note [ConDeclField names]
805 ~~~~~~~~~~~~~~~~~~~~~~~~~
806
807 A ConDeclField contains a list of field occurrences: these always
808 include the field label as the user wrote it. After the renamer, it
809 will additionally contain the identity of the selector function in the
810 second component.
811
812 Due to DuplicateRecordFields, the OccName of the selector function
813 may have been mangled, which is why we keep the original field label
814 separately. For example, when DuplicateRecordFields is enabled
815
816 data T = MkT { x :: Int }
817
818 gives
819
820 ConDeclField { cd_fld_names = [L _ (FieldOcc "x" $sel:x:MkT)], ... }.
821 -}
822
823 -----------------------
824 -- A valid type must have a for-all at the top of the type, or of the fn arg
825 -- types
826
827 ---------------------
828 hsWcScopedTvs :: LHsSigWcType Name -> [Name]
829 -- Get the lexically-scoped type variables of a HsSigType
830 -- - the explicitly-given forall'd type variables
831 -- - the implicitly-bound kind variables
832 -- - the named wildcars; see Note [Scoping of named wildcards]
833 -- because they scope in the same way
834 hsWcScopedTvs sig_ty
835 | HsWC { hswc_wcs = nwcs, hswc_body = sig_ty1 } <- sig_ty
836 , HsIB { hsib_vars = vars, hsib_body = sig_ty2 } <- sig_ty1
837 = case sig_ty2 of
838 L _ (HsForAllTy { hst_bndrs = tvs }) -> vars ++ nwcs ++
839 map hsLTyVarName tvs
840 -- include kind variables only if the type is headed by forall
841 -- (this is consistent with GHC 7 behaviour)
842 _ -> nwcs
843
844 hsScopedTvs :: LHsSigType Name -> [Name]
845 -- Same as hsWcScopedTvs, but for a LHsSigType
846 hsScopedTvs sig_ty
847 | HsIB { hsib_vars = vars, hsib_body = sig_ty2 } <- sig_ty
848 , L _ (HsForAllTy { hst_bndrs = tvs }) <- sig_ty2
849 = vars ++ map hsLTyVarName tvs
850 | otherwise
851 = []
852
853 {- Note [Scoping of named wildcards]
854 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
855 Consider
856 f :: _a -> _a
857 f x = let g :: _a -> _a
858 g = ...
859 in ...
860
861 Currently, for better or worse, the "_a" variables are all the same. So
862 although there is no explicit forall, the "_a" scopes over the definition.
863 I don't know if this is a good idea, but there it is.
864 -}
865
866 ---------------------
867 hsTyVarName :: HsTyVarBndr name -> name
868 hsTyVarName (UserTyVar (L _ n)) = n
869 hsTyVarName (KindedTyVar (L _ n) _) = n
870
871 hsLTyVarName :: LHsTyVarBndr name -> name
872 hsLTyVarName = hsTyVarName . unLoc
873
874 hsExplicitLTyVarNames :: LHsQTyVars name -> [name]
875 -- Explicit variables only
876 hsExplicitLTyVarNames qtvs = map hsLTyVarName (hsQTvExplicit qtvs)
877
878 hsAllLTyVarNames :: LHsQTyVars Name -> [Name]
879 -- All variables
880 hsAllLTyVarNames (HsQTvs { hsq_implicit = kvs, hsq_explicit = tvs })
881 = kvs ++ map hsLTyVarName tvs
882
883 hsLTyVarLocName :: LHsTyVarBndr name -> Located name
884 hsLTyVarLocName = fmap hsTyVarName
885
886 hsLTyVarLocNames :: LHsQTyVars name -> [Located name]
887 hsLTyVarLocNames qtvs = map hsLTyVarLocName (hsQTvExplicit qtvs)
888
889 -- | Convert a LHsTyVarBndr to an equivalent LHsType.
890 hsLTyVarBndrToType :: LHsTyVarBndr name -> LHsType name
891 hsLTyVarBndrToType = fmap cvt
892 where cvt (UserTyVar n) = HsTyVar NotPromoted n
893 cvt (KindedTyVar (L name_loc n) kind)
894 = HsKindSig (L name_loc (HsTyVar NotPromoted (L name_loc n))) kind
895
896 -- | Convert a LHsTyVarBndrs to a list of types.
897 -- Works on *type* variable only, no kind vars.
898 hsLTyVarBndrsToTypes :: LHsQTyVars name -> [LHsType name]
899 hsLTyVarBndrsToTypes (HsQTvs { hsq_explicit = tvbs }) = map hsLTyVarBndrToType tvbs
900
901 ---------------------
902 wildCardName :: HsWildCardInfo Name -> Name
903 wildCardName (AnonWildCard (L _ n)) = n
904
905 -- Two wild cards are the same when they have the same location
906 sameWildCard :: Located (HsWildCardInfo name)
907 -> Located (HsWildCardInfo name) -> Bool
908 sameWildCard (L l1 (AnonWildCard _)) (L l2 (AnonWildCard _)) = l1 == l2
909
910 ignoreParens :: LHsType name -> LHsType name
911 ignoreParens (L _ (HsParTy ty)) = ignoreParens ty
912 ignoreParens (L _ (HsAppsTy [L _ (HsAppPrefix ty)])) = ignoreParens ty
913 ignoreParens ty = ty
914
915 {-
916 ************************************************************************
917 * *
918 Building types
919 * *
920 ************************************************************************
921 -}
922
923 mkAnonWildCardTy :: HsType RdrName
924 mkAnonWildCardTy = HsWildCardTy (AnonWildCard PlaceHolder)
925
926 mkHsOpTy :: LHsType name -> Located name -> LHsType name -> HsType name
927 mkHsOpTy ty1 op ty2 = HsOpTy ty1 op ty2
928
929 mkHsAppTy :: LHsType name -> LHsType name -> LHsType name
930 mkHsAppTy t1 t2 = addCLoc t1 t2 (HsAppTy t1 t2)
931
932 mkHsAppTys :: LHsType name -> [LHsType name] -> LHsType name
933 mkHsAppTys = foldl mkHsAppTy
934
935
936 {-
937 ************************************************************************
938 * *
939 Decomposing HsTypes
940 * *
941 ************************************************************************
942 -}
943
944 ---------------------------------
945 -- splitHsFunType decomposes a type (t1 -> t2 ... -> tn)
946 -- Breaks up any parens in the result type:
947 -- splitHsFunType (a -> (b -> c)) = ([a,b], c)
948 -- Also deals with (->) t1 t2; that is why it only works on LHsType Name
949 -- (see Trac #9096)
950 splitHsFunType :: LHsType Name -> ([LHsType Name], LHsType Name)
951 splitHsFunType (L _ (HsParTy ty))
952 = splitHsFunType ty
953
954 splitHsFunType (L _ (HsFunTy x y))
955 | (args, res) <- splitHsFunType y
956 = (x:args, res)
957
958 splitHsFunType orig_ty@(L _ (HsAppTy t1 t2))
959 = go t1 [t2]
960 where -- Look for (->) t1 t2, possibly with parenthesisation
961 go (L _ (HsTyVar _ (L _ fn))) tys | fn == funTyConName
962 , [t1,t2] <- tys
963 , (args, res) <- splitHsFunType t2
964 = (t1:args, res)
965 go (L _ (HsAppTy t1 t2)) tys = go t1 (t2:tys)
966 go (L _ (HsParTy ty)) tys = go ty tys
967 go _ _ = ([], orig_ty) -- Failure to match
968
969 splitHsFunType other = ([], other)
970
971 --------------------------------
972 -- | Retrieves the head of an HsAppsTy, if this can be done unambiguously,
973 -- without consulting fixities.
974 getAppsTyHead_maybe :: [LHsAppType name]
975 -> Maybe (LHsType name, [LHsType name], LexicalFixity)
976 getAppsTyHead_maybe tys = case splitHsAppsTy tys of
977 ([app1:apps], []) -> -- no symbols, some normal types
978 Just (mkHsAppTys app1 apps, [], Prefix)
979 ([app1l:appsl, app1r:appsr], [L loc op]) -> -- one operator
980 Just ( L loc (HsTyVar NotPromoted (L loc op))
981 , [mkHsAppTys app1l appsl, mkHsAppTys app1r appsr], Infix)
982 _ -> -- can't figure it out
983 Nothing
984
985 -- | Splits a [HsAppType name] (the payload of an HsAppsTy) into regions of prefix
986 -- types (normal types) and infix operators.
987 -- If @splitHsAppsTy tys = (non_syms, syms)@, then @tys@ starts with the first
988 -- element of @non_syms@ followed by the first element of @syms@ followed by
989 -- the next element of @non_syms@, etc. It is guaranteed that the non_syms list
990 -- has one more element than the syms list.
991 splitHsAppsTy :: [LHsAppType name] -> ([[LHsType name]], [Located name])
992 splitHsAppsTy = go [] [] []
993 where
994 go acc acc_non acc_sym [] = (reverse (reverse acc : acc_non), reverse acc_sym)
995 go acc acc_non acc_sym (L _ (HsAppPrefix ty) : rest)
996 = go (ty : acc) acc_non acc_sym rest
997 go acc acc_non acc_sym (L _ (HsAppInfix op) : rest)
998 = go [] (reverse acc : acc_non) (op : acc_sym) rest
999
1000 -- Retrieve the name of the "head" of a nested type application
1001 -- somewhat like splitHsAppTys, but a little more thorough
1002 -- used to examine the result of a GADT-like datacon, so it doesn't handle
1003 -- *all* cases (like lists, tuples, (~), etc.)
1004 hsTyGetAppHead_maybe :: LHsType name -> Maybe (Located name, [LHsType name])
1005 hsTyGetAppHead_maybe = go []
1006 where
1007 go tys (L _ (HsTyVar _ ln)) = Just (ln, tys)
1008 go tys (L _ (HsAppsTy apps))
1009 | Just (head, args, _) <- getAppsTyHead_maybe apps
1010 = go (args ++ tys) head
1011 go tys (L _ (HsAppTy l r)) = go (r : tys) l
1012 go tys (L _ (HsOpTy l (L loc n) r)) = Just (L loc n, l : r : tys)
1013 go tys (L _ (HsParTy t)) = go tys t
1014 go tys (L _ (HsKindSig t _)) = go tys t
1015 go _ _ = Nothing
1016
1017 splitHsAppTys :: LHsType Name -> [LHsType Name] -> (LHsType Name, [LHsType Name])
1018 -- no need to worry about HsAppsTy here
1019 splitHsAppTys (L _ (HsAppTy f a)) as = splitHsAppTys f (a:as)
1020 splitHsAppTys (L _ (HsParTy f)) as = splitHsAppTys f as
1021 splitHsAppTys f as = (f,as)
1022
1023 --------------------------------
1024 splitLHsPatSynTy :: LHsType name
1025 -> ( [LHsTyVarBndr name] -- universals
1026 , LHsContext name -- required constraints
1027 , [LHsTyVarBndr name] -- existentials
1028 , LHsContext name -- provided constraints
1029 , LHsType name) -- body type
1030 splitLHsPatSynTy ty = (univs, reqs, exis, provs, ty4)
1031 where
1032 (univs, ty1) = splitLHsForAllTy ty
1033 (reqs, ty2) = splitLHsQualTy ty1
1034 (exis, ty3) = splitLHsForAllTy ty2
1035 (provs, ty4) = splitLHsQualTy ty3
1036
1037 splitLHsSigmaTy :: LHsType name -> ([LHsTyVarBndr name], LHsContext name, LHsType name)
1038 splitLHsSigmaTy ty
1039 | (tvs, ty1) <- splitLHsForAllTy ty
1040 , (ctxt, ty2) <- splitLHsQualTy ty1
1041 = (tvs, ctxt, ty2)
1042
1043 splitLHsForAllTy :: LHsType name -> ([LHsTyVarBndr name], LHsType name)
1044 splitLHsForAllTy (L _ (HsForAllTy { hst_bndrs = tvs, hst_body = body })) = (tvs, body)
1045 splitLHsForAllTy body = ([], body)
1046
1047 splitLHsQualTy :: LHsType name -> (LHsContext name, LHsType name)
1048 splitLHsQualTy (L _ (HsQualTy { hst_ctxt = ctxt, hst_body = body })) = (ctxt, body)
1049 splitLHsQualTy body = (noLoc [], body)
1050
1051 splitLHsInstDeclTy :: LHsSigType Name
1052 -> ([Name], LHsContext Name, LHsType Name)
1053 -- Split up an instance decl type, returning the pieces
1054 splitLHsInstDeclTy (HsIB { hsib_vars = itkvs
1055 , hsib_body = inst_ty })
1056 | (tvs, cxt, body_ty) <- splitLHsSigmaTy inst_ty
1057 = (itkvs ++ map hsLTyVarName tvs, cxt, body_ty)
1058 -- Return implicitly bound type and kind vars
1059 -- For an instance decl, all of them are in scope
1060
1061 getLHsInstDeclHead :: LHsSigType name -> LHsType name
1062 getLHsInstDeclHead inst_ty
1063 | (_tvs, _cxt, body_ty) <- splitLHsSigmaTy (hsSigType inst_ty)
1064 = body_ty
1065
1066 getLHsInstDeclClass_maybe :: LHsSigType name -> Maybe (Located name)
1067 -- Works on (HsSigType RdrName)
1068 getLHsInstDeclClass_maybe inst_ty
1069 = do { let head_ty = getLHsInstDeclHead inst_ty
1070 ; (cls, _) <- hsTyGetAppHead_maybe head_ty
1071 ; return cls }
1072
1073 {-
1074 ************************************************************************
1075 * *
1076 FieldOcc
1077 * *
1078 ************************************************************************
1079 -}
1080
1081 -- | Located Field Occurrence
1082 type LFieldOcc name = Located (FieldOcc name)
1083
1084 -- | Field Occurrence
1085 --
1086 -- Represents an *occurrence* of an unambiguous field. We store
1087 -- both the 'RdrName' the user originally wrote, and after the
1088 -- renamer, the selector function.
1089 data FieldOcc name = FieldOcc { rdrNameFieldOcc :: Located RdrName
1090 -- ^ See Note [Located RdrNames] in HsExpr
1091 , selectorFieldOcc :: PostRn name name
1092 }
1093 deriving instance Eq (PostRn name name) => Eq (FieldOcc name)
1094 deriving instance Ord (PostRn name name) => Ord (FieldOcc name)
1095 deriving instance (Data name, Data (PostRn name name)) => Data (FieldOcc name)
1096
1097 instance Outputable (FieldOcc name) where
1098 ppr = ppr . rdrNameFieldOcc
1099
1100 mkFieldOcc :: Located RdrName -> FieldOcc RdrName
1101 mkFieldOcc rdr = FieldOcc rdr PlaceHolder
1102
1103
1104 -- | Ambiguous Field Occurrence
1105 --
1106 -- Represents an *occurrence* of a field that is potentially
1107 -- ambiguous after the renamer, with the ambiguity resolved by the
1108 -- typechecker. We always store the 'RdrName' that the user
1109 -- originally wrote, and store the selector function after the renamer
1110 -- (for unambiguous occurrences) or the typechecker (for ambiguous
1111 -- occurrences).
1112 --
1113 -- See Note [HsRecField and HsRecUpdField] in HsPat and
1114 -- Note [Disambiguating record fields] in TcExpr.
1115 -- See Note [Located RdrNames] in HsExpr
1116 data AmbiguousFieldOcc name
1117 = Unambiguous (Located RdrName) (PostRn name name)
1118 | Ambiguous (Located RdrName) (PostTc name name)
1119 deriving instance ( Data name
1120 , Data (PostRn name name)
1121 , Data (PostTc name name))
1122 => Data (AmbiguousFieldOcc name)
1123
1124 instance Outputable (AmbiguousFieldOcc name) where
1125 ppr = ppr . rdrNameAmbiguousFieldOcc
1126
1127 instance OutputableBndr (AmbiguousFieldOcc name) where
1128 pprInfixOcc = pprInfixOcc . rdrNameAmbiguousFieldOcc
1129 pprPrefixOcc = pprPrefixOcc . rdrNameAmbiguousFieldOcc
1130
1131 mkAmbiguousFieldOcc :: Located RdrName -> AmbiguousFieldOcc RdrName
1132 mkAmbiguousFieldOcc rdr = Unambiguous rdr PlaceHolder
1133
1134 rdrNameAmbiguousFieldOcc :: AmbiguousFieldOcc name -> RdrName
1135 rdrNameAmbiguousFieldOcc (Unambiguous (L _ rdr) _) = rdr
1136 rdrNameAmbiguousFieldOcc (Ambiguous (L _ rdr) _) = rdr
1137
1138 selectorAmbiguousFieldOcc :: AmbiguousFieldOcc Id -> Id
1139 selectorAmbiguousFieldOcc (Unambiguous _ sel) = sel
1140 selectorAmbiguousFieldOcc (Ambiguous _ sel) = sel
1141
1142 unambiguousFieldOcc :: AmbiguousFieldOcc Id -> FieldOcc Id
1143 unambiguousFieldOcc (Unambiguous rdr sel) = FieldOcc rdr sel
1144 unambiguousFieldOcc (Ambiguous rdr sel) = FieldOcc rdr sel
1145
1146 ambiguousFieldOcc :: FieldOcc name -> AmbiguousFieldOcc name
1147 ambiguousFieldOcc (FieldOcc rdr sel) = Unambiguous rdr sel
1148
1149 {-
1150 ************************************************************************
1151 * *
1152 \subsection{Pretty printing}
1153 * *
1154 ************************************************************************
1155 -}
1156
1157 instance (OutputableBndrId name) => Outputable (HsType name) where
1158 ppr ty = pprHsType ty
1159
1160 instance Outputable HsTyLit where
1161 ppr = ppr_tylit
1162
1163 instance (OutputableBndrId name) => Outputable (LHsQTyVars name) where
1164 ppr (HsQTvs { hsq_explicit = tvs }) = interppSP tvs
1165
1166 instance (OutputableBndrId name) => Outputable (HsTyVarBndr name) where
1167 ppr (UserTyVar n) = ppr n
1168 ppr (KindedTyVar n k) = parens $ hsep [ppr n, dcolon, ppr k]
1169
1170 instance (Outputable thing) => Outputable (HsImplicitBndrs name thing) where
1171 ppr (HsIB { hsib_body = ty }) = ppr ty
1172
1173 instance (Outputable thing) => Outputable (HsWildCardBndrs name thing) where
1174 ppr (HsWC { hswc_body = ty }) = ppr ty
1175
1176 instance Outputable (HsWildCardInfo name) where
1177 ppr (AnonWildCard _) = char '_'
1178
1179 pprHsForAll :: (OutputableBndrId name)
1180 => [LHsTyVarBndr name] -> LHsContext name -> SDoc
1181 pprHsForAll = pprHsForAllExtra Nothing
1182
1183 -- | Version of 'pprHsForAll' that can also print an extra-constraints
1184 -- wildcard, e.g. @_ => a -> Bool@ or @(Show a, _) => a -> String@. This
1185 -- underscore will be printed when the 'Maybe SrcSpan' argument is a 'Just'
1186 -- containing the location of the extra-constraints wildcard. A special
1187 -- function for this is needed, as the extra-constraints wildcard is removed
1188 -- from the actual context and type, and stored in a separate field, thus just
1189 -- printing the type will not print the extra-constraints wildcard.
1190 pprHsForAllExtra :: (OutputableBndrId name)
1191 => Maybe SrcSpan -> [LHsTyVarBndr name] -> LHsContext name
1192 -> SDoc
1193 pprHsForAllExtra extra qtvs cxt
1194 = pprHsForAllTvs qtvs <+> pprHsContextExtra show_extra (unLoc cxt)
1195 where
1196 show_extra = isJust extra
1197
1198 pprHsForAllTvs :: (OutputableBndrId name) => [LHsTyVarBndr name] -> SDoc
1199 pprHsForAllTvs qtvs = sdocWithPprDebug $ \debug ->
1200 ppWhen (debug || not (null qtvs)) $ forAllLit <+> interppSP qtvs <> dot
1201
1202 pprHsContext :: (OutputableBndrId name) => HsContext name -> SDoc
1203 pprHsContext = maybe empty (<+> darrow) . pprHsContextMaybe
1204
1205 pprHsContextNoArrow :: (OutputableBndrId name) => HsContext name -> SDoc
1206 pprHsContextNoArrow = fromMaybe empty . pprHsContextMaybe
1207
1208 pprHsContextMaybe :: (OutputableBndrId name) => HsContext name -> Maybe SDoc
1209 pprHsContextMaybe [] = Nothing
1210 pprHsContextMaybe [L _ pred] = Just $ ppr_mono_ty pred
1211 pprHsContextMaybe cxt = Just $ parens (interpp'SP cxt)
1212
1213 -- For use in a HsQualTy, which always gets printed if it exists.
1214 pprHsContextAlways :: (OutputableBndrId name) => HsContext name -> SDoc
1215 pprHsContextAlways [] = parens empty <+> darrow
1216 pprHsContextAlways [L _ ty] = ppr_mono_ty ty <+> darrow
1217 pprHsContextAlways cxt = parens (interpp'SP cxt) <+> darrow
1218
1219 -- True <=> print an extra-constraints wildcard, e.g. @(Show a, _) =>@
1220 pprHsContextExtra :: (OutputableBndrId name) => Bool -> HsContext name -> SDoc
1221 pprHsContextExtra show_extra ctxt
1222 | not show_extra
1223 = pprHsContext ctxt
1224 | null ctxt
1225 = char '_' <+> darrow
1226 | otherwise
1227 = parens (sep (punctuate comma ctxt')) <+> darrow
1228 where
1229 ctxt' = map ppr ctxt ++ [char '_']
1230
1231 pprConDeclFields :: (OutputableBndrId name) => [LConDeclField name] -> SDoc
1232 pprConDeclFields fields = braces (sep (punctuate comma (map ppr_fld fields)))
1233 where
1234 ppr_fld (L _ (ConDeclField { cd_fld_names = ns, cd_fld_type = ty,
1235 cd_fld_doc = doc }))
1236 = ppr_names ns <+> dcolon <+> ppr ty <+> ppr_mbDoc doc
1237 ppr_names [n] = ppr n
1238 ppr_names ns = sep (punctuate comma (map ppr ns))
1239
1240 {-
1241 Note [Printing KindedTyVars]
1242 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1243 Trac #3830 reminded me that we should really only print the kind
1244 signature on a KindedTyVar if the kind signature was put there by the
1245 programmer. During kind inference GHC now adds a PostTcKind to UserTyVars,
1246 rather than converting to KindedTyVars as before.
1247
1248 (As it happens, the message in #3830 comes out a different way now,
1249 and the problem doesn't show up; but having the flag on a KindedTyVar
1250 seems like the Right Thing anyway.)
1251 -}
1252
1253 -- Printing works more-or-less as for Types
1254
1255 pprHsType :: (OutputableBndrId name) => HsType name -> SDoc
1256 pprHsType ty = ppr_mono_ty ty
1257
1258 ppr_mono_lty :: (OutputableBndrId name) => LHsType name -> SDoc
1259 ppr_mono_lty ty = ppr_mono_ty (unLoc ty)
1260
1261 ppr_mono_ty :: (OutputableBndrId name) => HsType name -> SDoc
1262 ppr_mono_ty (HsForAllTy { hst_bndrs = tvs, hst_body = ty })
1263 = sep [pprHsForAllTvs tvs, ppr_mono_lty ty]
1264
1265 ppr_mono_ty (HsQualTy { hst_ctxt = L _ ctxt, hst_body = ty })
1266 = sep [pprHsContextAlways ctxt, ppr_mono_lty ty]
1267
1268 ppr_mono_ty (HsBangTy b ty) = ppr b <> ppr_mono_lty ty
1269 ppr_mono_ty (HsRecTy flds) = pprConDeclFields flds
1270 ppr_mono_ty (HsTyVar NotPromoted (L _ name))= pprPrefixOcc name
1271 ppr_mono_ty (HsTyVar Promoted (L _ name))
1272 = space <> quote (pprPrefixOcc name)
1273 -- We need a space before the ' above, so the parser
1274 -- does not attach it to the previous symbol
1275 ppr_mono_ty (HsFunTy ty1 ty2) = ppr_fun_ty ty1 ty2
1276 ppr_mono_ty (HsTupleTy con tys) = tupleParens std_con (pprWithCommas ppr tys)
1277 where std_con = case con of
1278 HsUnboxedTuple -> UnboxedTuple
1279 _ -> BoxedTuple
1280 ppr_mono_ty (HsSumTy tys) = tupleParens UnboxedTuple (pprWithBars ppr tys)
1281 ppr_mono_ty (HsKindSig ty kind) = parens (ppr_mono_lty ty <+> dcolon <+> ppr kind)
1282 ppr_mono_ty (HsListTy ty) = brackets (ppr_mono_lty ty)
1283 ppr_mono_ty (HsPArrTy ty) = paBrackets (ppr_mono_lty ty)
1284 ppr_mono_ty (HsIParamTy n ty) = (ppr n <+> dcolon <+> ppr_mono_lty ty)
1285 ppr_mono_ty (HsSpliceTy s _) = pprSplice s
1286 ppr_mono_ty (HsCoreTy ty) = ppr ty
1287 ppr_mono_ty (HsExplicitListTy Promoted _ tys)
1288 = quote $ brackets (interpp'SP tys)
1289 ppr_mono_ty (HsExplicitListTy NotPromoted _ tys)
1290 = brackets (interpp'SP tys)
1291 ppr_mono_ty (HsExplicitTupleTy _ tys) = quote $ parens (interpp'SP tys)
1292 ppr_mono_ty (HsTyLit t) = ppr_tylit t
1293 ppr_mono_ty (HsWildCardTy {}) = char '_'
1294
1295 ppr_mono_ty (HsEqTy ty1 ty2)
1296 = ppr_mono_lty ty1 <+> char '~' <+> ppr_mono_lty ty2
1297
1298 ppr_mono_ty (HsAppsTy tys)
1299 = hsep (map (ppr_app_ty . unLoc) tys)
1300
1301 ppr_mono_ty (HsAppTy fun_ty arg_ty)
1302 = hsep [ppr_mono_lty fun_ty, ppr_mono_lty arg_ty]
1303
1304 ppr_mono_ty (HsOpTy ty1 (L _ op) ty2)
1305 = sep [ ppr_mono_lty ty1
1306 , sep [pprInfixOcc op, ppr_mono_lty ty2 ] ]
1307
1308 ppr_mono_ty (HsParTy ty)
1309 = parens (ppr_mono_lty ty)
1310 -- Put the parens in where the user did
1311 -- But we still use the precedence stuff to add parens because
1312 -- toHsType doesn't put in any HsParTys, so we may still need them
1313
1314 ppr_mono_ty (HsDocTy ty doc)
1315 -- AZ: Should we add parens? Should we introduce "-- ^"?
1316 = ppr_mono_lty ty <+> ppr (unLoc doc)
1317 -- we pretty print Haddock comments on types as if they were
1318 -- postfix operators
1319
1320 --------------------------
1321 ppr_fun_ty :: (OutputableBndrId name)
1322 => LHsType name -> LHsType name -> SDoc
1323 ppr_fun_ty ty1 ty2
1324 = let p1 = ppr_mono_lty ty1
1325 p2 = ppr_mono_lty ty2
1326 in
1327 sep [p1, text "->" <+> p2]
1328
1329 --------------------------
1330 ppr_app_ty :: (OutputableBndrId name) => HsAppType name -> SDoc
1331 ppr_app_ty (HsAppInfix (L _ n)) = pprInfixOcc n
1332 ppr_app_ty (HsAppPrefix (L _ (HsTyVar NotPromoted (L _ n))))
1333 = pprPrefixOcc n
1334 ppr_app_ty (HsAppPrefix (L _ (HsTyVar Promoted (L _ n))))
1335 = space <> quote (pprPrefixOcc n) -- We need a space before the ' above, so
1336 -- the parser does not attach it to the
1337 -- previous symbol
1338 ppr_app_ty (HsAppPrefix ty) = ppr_mono_lty ty
1339
1340 --------------------------
1341 ppr_tylit :: HsTyLit -> SDoc
1342 ppr_tylit (HsNumTy _ i) = integer i
1343 ppr_tylit (HsStrTy _ s) = text (show s)