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