HsTypes.hs 52.3 KB
Newer Older
Austin Seipp's avatar
Austin Seipp committed
1 2 3 4
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998

5 6

HsTypes: Abstract syntax: user-defined types
Austin Seipp's avatar
Austin Seipp committed
7
-}
8

9
{-# LANGUAGE DeriveDataTypeable #-}
10 11 12 13 14 15 16
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
                                      -- in module PlaceHolder
{-# LANGUAGE ConstraintKinds #-}
17
{-# LANGUAGE CPP #-}
18

19
module HsTypes (
Simon Peyton Jones's avatar
Simon Peyton Jones committed
20
        HsType(..), LHsType, HsKind, LHsKind,
Austin Seipp's avatar
Austin Seipp committed
21
        HsTyVarBndr(..), LHsTyVarBndr,
22 23 24 25 26
        LHsQTyVars(..),
        HsImplicitBndrs(..),
        HsWildCardBndrs(..),
        LHsSigType, LHsSigWcType, LHsWcType,
        HsTupleSort(..),
Alan Zimmerman's avatar
Alan Zimmerman committed
27
        Promoted(..),
Simon Peyton Jones's avatar
Simon Peyton Jones committed
28
        HsContext, LHsContext,
29
        HsTyLit(..),
30
        HsIPName(..), hsIPNameFS,
31
        HsAppType(..),LHsAppType,
32

33 34
        LBangType, BangType,
        HsSrcBang(..), HsImplBang(..),
35
        SrcStrictness(..), SrcUnpackedness(..),
Austin Seipp's avatar
Austin Seipp committed
36
        getBangType, getBangStrictness,
37

38 39 40
        ConDeclField(..), LConDeclField, pprConDeclFields, updateGadtResult,

        HsConDetails(..),
Austin Seipp's avatar
Austin Seipp committed
41

Adam Gundry's avatar
Adam Gundry committed
42 43 44 45 46
        FieldOcc(..), LFieldOcc, mkFieldOcc,
        AmbiguousFieldOcc(..), mkAmbiguousFieldOcc,
        rdrNameAmbiguousFieldOcc, selectorAmbiguousFieldOcc,
        unambiguousFieldOcc, ambiguousFieldOcc,

47 48
        HsWildCardInfo(..), mkAnonWildCardTy,
        wildCardName, sameWildCard,
thomasw's avatar
thomasw committed
49

50 51
        mkHsImplicitBndrs, mkHsWildCardBndrs, hsImplicitBody,
        mkEmptyImplicitBndrs, mkEmptyWildCardBndrs,
52 53
        mkHsQTvs, hsQTvExplicit, emptyLHsQTvs, isEmptyLHsQTvs,
        isHsKindedTyVar, hsTvbAllKinded,
54
        hsScopedTvs, hsWcScopedTvs, dropWildCards,
55 56
        hsTyVarName, hsAllLTyVarNames, hsLTyVarLocNames,
        hsLTyVarName, hsLTyVarLocName, hsExplicitLTyVarNames,
57
        splitLHsInstDeclTy, getLHsInstDeclHead, getLHsInstDeclClass_maybe,
58 59
        splitLHsPatSynTy,
        splitLHsForAllTy, splitLHsQualTy, splitLHsSigmaTy,
60 61 62
        splitHsFunType, splitHsAppsTy,
        splitHsAppTys, getAppsTyHead_maybe, hsTyGetAppHead_maybe,
        mkHsOpTy, mkHsAppTy, mkHsAppTys,
63
        ignoreParens, hsSigType, hsSigWcType,
64
        hsLTyVarBndrToType, hsLTyVarBndrsToTypes,
65

Simon Peyton Jones's avatar
Simon Peyton Jones committed
66
        -- Printing
67
        pprHsType, pprHsForAll, pprHsForAllTvs, pprHsForAllExtra,
68
        pprHsContext, pprHsContextNoArrow, pprHsContextMaybe
69 70
    ) where

71
import {-# SOURCE #-} HsExpr ( HsSplice, pprSplice )
72

73 74
import PlaceHolder ( PlaceHolder(..) )
import HsExtension
dreixel's avatar
dreixel committed
75

76
import Id ( Id )
77
import Name( Name )
78
import RdrName ( RdrName )
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
79
import NameSet ( NameSet, emptyNameSet )
80
import DataCon( HsSrcBang(..), HsImplBang(..),
81
                SrcStrictness(..), SrcUnpackedness(..) )
82
import TysPrim( funTyConName )
83 84 85 86
import Type
import HsDoc
import BasicTypes
import SrcLoc
87
import Outputable
88
import FastString
thomasw's avatar
thomasw committed
89
import Maybes( isJust )
90

91
import Data.Data hiding ( Fixity, Prefix, Infix )
92
import Data.Maybe ( fromMaybe )
93
import Control.Monad ( unless )
94

Austin Seipp's avatar
Austin Seipp committed
95 96 97
{-
************************************************************************
*                                                                      *
98
\subsection{Bang annotations}
Austin Seipp's avatar
Austin Seipp committed
99 100 101
*                                                                      *
************************************************************************
-}
102

103
-- | Located Bang Type
104
type LBangType pass = Located (BangType pass)
105 106

-- | Bang Type
107
type BangType pass  = HsType pass       -- Bangs are in the HsType data type
108 109 110 111 112

getBangType :: LHsType a -> LHsType a
getBangType (L _ (HsBangTy _ ty)) = ty
getBangType ty                    = ty

Simon Peyton Jones's avatar
Simon Peyton Jones committed
113
getBangStrictness :: LHsType a -> HsSrcBang
114
getBangStrictness (L _ (HsBangTy s _)) = s
Alan Zimmerman's avatar
Alan Zimmerman committed
115
getBangStrictness _ = (HsSrcBang NoSourceText NoSrcUnpack NoSrcStrict)
116

Austin Seipp's avatar
Austin Seipp committed
117 118 119
{-
************************************************************************
*                                                                      *
120
\subsection{Data types}
Austin Seipp's avatar
Austin Seipp committed
121 122
*                                                                      *
************************************************************************
123

124 125
This is the syntax for types as seen in type signatures.

126 127
Note [HsBSig binder lists]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Rik Steenkamp's avatar
Rik Steenkamp committed
128
Consider a binder (or pattern) decorated with a type or kind,
129 130 131 132 133 134 135
   \ (x :: a -> a). blah
   forall (a :: k -> *) (b :: k). blah
Then we use a LHsBndrSig on the binder, so that the
renamer can decorate it with the variables bound
by the pattern ('a' in the first example, 'k' in the second),
assuming that neither of them is in scope already
See also Note [Kind and type-variable binders] in RnTypes
136 137 138

Note [HsType binders]
~~~~~~~~~~~~~~~~~~~~~
Alan Zimmerman's avatar
Alan Zimmerman committed
139
The system for recording type and kind-variable binders in HsTypes
140 141 142 143 144
is a bit complicated.  Here's how it works.

* In a HsType,
     HsForAllTy   represents an /explicit, user-written/ 'forall'
                   e.g.   forall a b. ...
Rik Steenkamp's avatar
Rik Steenkamp committed
145
     HsQualTy     represents an /explicit, user-written/ context
146 147
                   e.g.   (Eq a, Show a) => ...
                  The context can be empty if that's what the user wrote
Alan Zimmerman's avatar
Alan Zimmerman committed
148
  These constructors represent what the user wrote, no more
149 150 151 152 153 154 155 156 157 158
  and no less.

* HsTyVarBndr describes a quantified type variable written by the
  user.  For example
     f :: forall a (b :: *).  blah
  here 'a' and '(b::*)' are each a HsTyVarBndr.  A HsForAllTy has
  a list of LHsTyVarBndrs.

* HsImplicitBndrs is a wrapper that gives the implicitly-quantified
  kind and type variables of the wrapped thing.  It is filled in by
Rik Steenkamp's avatar
Rik Steenkamp committed
159
  the renamer. For example, if the user writes
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
     f :: a -> a
  the HsImplicitBinders binds the 'a' (not a HsForAllTy!).
  NB: this implicit quantification is purely lexical: we bind any
      type or kind variables that are not in scope. The type checker
      may subsequently quantify over further kind variables.

* HsWildCardBndrs is a wrapper that binds the wildcard variables
  of the wrapped thing.  It is filled in by the renamer
     f :: _a -> _
  The enclosing HsWildCardBndrs binds the wildcards _a and _.

* The explicit presence of these wrappers specifies, in the HsSyn,
  exactly where implicit quantification is allowed, and where
  wildcards are allowed.

* LHsQTyVars is used in data/class declarations, where the user gives
  explicit *type* variable bindings, but we need to implicitly bind
  *kind* variables.  For example
      class C (a :: k -> *) where ...
  The 'k' is implicitly bound in the hsq_tvs field of LHsQTyVars

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
Note [The wildcard story for types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Types can have wildcards in them, to support partial type signatures,
like       f :: Int -> (_ , _a) -> _a

A wildcard in a type can be

  * An anonymous wildcard,
        written '_'
    In HsType this is represented by HsWildCardTy.
    After the renamer, this contains a Name which uniquely
    identifies this particular occurrence.

  * A named wildcard,
        written '_a', '_foo', etc
    In HsType this is represented by (HsTyVar "_a")
    i.e. a perfectly ordinary type variable that happens
         to start with an underscore

Note carefully:

* When NamedWildCards is off, type variables that start with an
  underscore really /are/ ordinary type variables.  And indeed, even
  when NamedWildCards is on you can bind _a explicitly as an ordinary
  type variable:
        data T _a _b = MkT _b _a
  Or even:
        f :: forall _a. _a -> _b
  Here _a is an ordinary forall'd binder, but (With NamedWildCards)
  _b is a named wildcard.  (See the comments in Trac #10982)

* All wildcards, whether named or anonymous, are bound by the
  HsWildCardBndrs construct, which wraps types that are allowed
  to have wildcards.

* After type checking is done, we report what types the wildcards
  got unified with.

Austin Seipp's avatar
Austin Seipp committed
219
-}
220

221
-- | Located Haskell Context
222
type LHsContext pass = Located (HsContext pass)
Alan Zimmerman's avatar
Alan Zimmerman committed
223
      -- ^ 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnUnit'
224

225 226
      -- For details on above see note [Api annotations] in ApiAnnotation

227
-- | Haskell Context
228
type HsContext pass = [LHsType pass]
229

230
-- | Located Haskell Type
231
type LHsType pass = Located (HsType pass)
Alan Zimmerman's avatar
Alan Zimmerman committed
232 233
      -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when
      --   in a list
234 235

      -- For details on above see note [Api annotations] in ApiAnnotation
236 237

-- | Haskell Kind
238
type HsKind pass = HsType pass
239 240

-- | Located Haskell Kind
241
type LHsKind pass = Located (HsKind pass)
242 243 244
      -- ^ 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'

      -- For details on above see note [Api annotations] in ApiAnnotation
245

246
--------------------------------------------------
247 248
--             LHsQTyVars
--  The explicitly-quantified binders in a data/type declaration
249

250
-- | Located Haskell Type Variable Binder
251
type LHsTyVarBndr pass = Located (HsTyVarBndr pass)
252
                         -- See Note [HsType binders]
253

254
-- | Located Haskell Quantified Type Variables
255 256
data LHsQTyVars pass   -- See Note [HsType binders]
  = HsQTvs { hsq_implicit :: PostRn pass [Name]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
257 258 259 260 261 262
                -- Implicit (dependent) variables

           , hsq_explicit :: [LHsTyVarBndr pass]
                -- Explicit variables, written by the user
                -- See Note [HsForAllTy tyvar binders]

263
           , hsq_dependent :: PostRn pass NameSet
Simon Peyton Jones's avatar
Simon Peyton Jones committed
264 265 266
               -- Which members of hsq_explicit are dependent; that is,
               -- mentioned in the kind of a later hsq_explicit,
               -- or mentioned in a kind in the scope of this HsQTvs
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
267
               -- See Note [Dependent LHsQTyVars] in TcHsType
268 269
    }

270
deriving instance (DataId pass) => Data (LHsQTyVars pass)
271

272
mkHsQTvs :: [LHsTyVarBndr GhcPs] -> LHsQTyVars GhcPs
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
273 274
mkHsQTvs tvs = HsQTvs { hsq_implicit = PlaceHolder, hsq_explicit = tvs
                      , hsq_dependent = PlaceHolder }
275

276
hsQTvExplicit :: LHsQTyVars pass -> [LHsTyVarBndr pass]
277
hsQTvExplicit = hsq_explicit
278

279
emptyLHsQTvs :: LHsQTyVars GhcRn
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
280
emptyLHsQTvs = HsQTvs [] [] emptyNameSet
281

282
isEmptyLHsQTvs :: LHsQTyVars GhcRn -> Bool
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
283 284
isEmptyLHsQTvs (HsQTvs [] [] _) = True
isEmptyLHsQTvs _                = False
285

286
------------------------------------------------
287
--            HsImplicitBndrs
288 289
-- Used to quantify the implicit binders of a type
--    * Implicit binders of a type signature (LHsSigType/LHsSigWcType)
290 291
--    * Patterns in a type/data family instance (HsTyPats)

292
-- | Haskell Implicit Binders
293 294
data HsImplicitBndrs pass thing   -- See Note [HsType binders]
  = HsIB { hsib_vars :: PostRn pass [Name] -- Implicitly-bound kind & type vars
295
         , hsib_body :: thing              -- Main payload (type or list of types)
296
         , hsib_closed :: PostRn pass Bool -- Taking the hsib_vars into account,
Richard Eisenberg's avatar
Richard Eisenberg committed
297 298
                                           -- is the payload closed? Used in
                                           -- TcHsType.decideKindGeneralisationPlan
299
    }
300
deriving instance (DataId pass, Data thing) => Data (HsImplicitBndrs pass thing)
301

302
-- | Haskell Wildcard Binders
303
data HsWildCardBndrs pass thing
304 305
    -- See Note [HsType binders]
    -- See Note [The wildcard story for types]
306
  = HsWC { hswc_wcs :: PostRn pass [Name]
307
                -- Wild cards, both named and anonymous
308
                -- after the renamer
309

310 311 312 313
         , hswc_body :: thing
                -- Main payload (type or list of types)
                -- If there is an extra-constraints wildcard,
                -- it's still there in the hsc_body.
314 315
    }

316
deriving instance (DataId pass, Data thing) => Data (HsWildCardBndrs pass thing)
317

318
-- | Located Haskell Signature Type
319
type LHsSigType   pass = HsImplicitBndrs pass (LHsType pass)    -- Implicit only
320 321

-- | Located Haskell Wildcard Type
322
type LHsWcType    pass = HsWildCardBndrs pass (LHsType pass)    -- Wildcard only
323 324

-- | Located Haskell Signature Wildcard Type
325
type LHsSigWcType pass = HsWildCardBndrs pass (LHsSigType pass) -- Both
326 327 328

-- See Note [Representing type signatures]

329
hsImplicitBody :: HsImplicitBndrs pass thing -> thing
330 331
hsImplicitBody (HsIB { hsib_body = body }) = body

332
hsSigType :: LHsSigType pass -> LHsType pass
333 334
hsSigType = hsImplicitBody

335
hsSigWcType :: LHsSigWcType pass -> LHsType pass
336
hsSigWcType sig_ty = hsib_body (hswc_body sig_ty)
337

338
dropWildCards :: LHsSigWcType pass -> LHsSigType pass
339
-- Drop the wildcard part of a LHsSigWcType
340
dropWildCards sig_ty = hswc_body sig_ty
341 342 343 344 345 346 347 348 349

{- Note [Representing type signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HsSigType is used to represent an explicit user type signature
such as   f :: a -> a
     or   g (x :: a -> a) = x

A HsSigType is just a HsImplicitBndrs wrapping a LHsType.
 * The HsImplicitBndrs binds the /implicitly/ quantified tyvars
350
 * The LHsType binds the /explicitly/ quantified tyvars
351 352 353 354

E.g. For a signature like
   f :: forall (a::k). blah
we get
355
   HsIB { hsib_vars = [k]
356 357 358
        , hsib_body = HsForAllTy { hst_bndrs = [(a::*)]
                                 , hst_body = blah }
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 GhcPs thing
Richard Eisenberg's avatar
Richard Eisenberg committed
363 364 365
mkHsImplicitBndrs x = HsIB { hsib_body   = x
                           , hsib_vars   = PlaceHolder
                           , hsib_closed = PlaceHolder }
366

367
mkHsWildCardBndrs :: thing -> HsWildCardBndrs GhcPs thing
368
mkHsWildCardBndrs x = HsWC { hswc_body = x
369
                           , hswc_wcs  = PlaceHolder }
370 371 372

-- Add empty binders.  This is a bit suspicious; what if
-- the wrapped thing had free type variables?
373
mkEmptyImplicitBndrs :: thing -> HsImplicitBndrs GhcRn thing
Richard Eisenberg's avatar
Richard Eisenberg committed
374 375 376
mkEmptyImplicitBndrs x = HsIB { hsib_body   = x
                              , hsib_vars   = []
                              , hsib_closed = False }
377

378
mkEmptyWildCardBndrs :: thing -> HsWildCardBndrs GhcRn thing
379
mkEmptyWildCardBndrs x = HsWC { hswc_body = x
380
                              , hswc_wcs  = [] }
381

382

383
--------------------------------------------------
Mateusz Kowalczyk's avatar
Typo  
Mateusz Kowalczyk committed
384
-- | These names are used early on to store the names of implicit
385
-- parameters.  They completely disappear after type-checking.
Jan Stolarek's avatar
Jan Stolarek committed
386
newtype HsIPName = HsIPName FastString
387
  deriving( Eq, Data )
388 389 390 391 392 393 394 395 396 397 398 399

hsIPNameFS :: HsIPName -> FastString
hsIPNameFS (HsIPName n) = n

instance Outputable HsIPName where
    ppr (HsIPName n) = char '?' <> ftext n -- Ordinary implicit parameters

instance OutputableBndr HsIPName where
    pprBndr _ n   = ppr n         -- Simple for now
    pprInfixOcc  n = ppr n
    pprPrefixOcc n = ppr n

400
--------------------------------------------------
401 402

-- | Haskell Type Variable Binder
403
data HsTyVarBndr pass
404
  = UserTyVar        -- no explicit kinding
405
         (Located (IdP pass))
406
        -- See Note [Located RdrNames] in HsExpr
407
  | KindedTyVar
408 409
         (Located (IdP pass))
         (LHsKind pass)  -- The user-supplied kind signature
Alan Zimmerman's avatar
Alan Zimmerman committed
410 411 412
        -- ^
        --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
        --          'ApiAnnotation.AnnDcolon', 'ApiAnnotation.AnnClose'
413 414

        -- For details on above see note [Api annotations] in ApiAnnotation
415
deriving instance (DataId pass) => Data (HsTyVarBndr pass)
416

417
-- | Does this 'HsTyVarBndr' come with an explicit kind annotation?
418
isHsKindedTyVar :: HsTyVarBndr pass -> Bool
419 420 421
isHsKindedTyVar (UserTyVar {})   = False
isHsKindedTyVar (KindedTyVar {}) = True

422
-- | Do all type variables in this 'LHsQTyVars' come with kind annotations?
423
hsTvbAllKinded :: LHsQTyVars pass -> Bool
424
hsTvbAllKinded = all (isHsKindedTyVar . unLoc) . hsQTvExplicit
425

426
-- | Haskell Type
427
data HsType pass
428
  = HsForAllTy   -- See Note [HsType binders]
429 430 431
      { hst_bndrs :: [LHsTyVarBndr pass]
                                       -- Explicit, user-supplied 'forall a b c'
      , hst_body  :: LHsType pass      -- body type
432
      }
Alan Zimmerman's avatar
Alan Zimmerman committed
433 434
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnForall',
      --         'ApiAnnotation.AnnDot','ApiAnnotation.AnnDarrow'
435 436
      -- For details on above see note [Api annotations] in ApiAnnotation

437
  | HsQualTy   -- See Note [HsType binders]
438 439
      { hst_ctxt :: LHsContext pass       -- Context C => blah
      , hst_body :: LHsType pass }
440

441
  | HsTyVar             Promoted -- whether explicitly promoted, for the pretty
Alan Zimmerman's avatar
Alan Zimmerman committed
442
                                 -- printer
443
                        (Located (IdP pass))
444 445
                  -- Type variable, type constructor, or data constructor
                  -- see Note [Promotions (HsTyVar)]
446
                  -- See Note [Located RdrNames] in HsExpr
Alan Zimmerman's avatar
Alan Zimmerman committed
447
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None
448

449 450
      -- For details on above see note [Api annotations] in ApiAnnotation

451
  | HsAppsTy            [LHsAppType pass] -- Used only before renaming,
452 453 454
                                          -- Note [HsAppsTy]
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None

455 456
  | HsAppTy             (LHsType pass)
                        (LHsType pass)
Alan Zimmerman's avatar
Alan Zimmerman committed
457
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None
458

459 460
      -- For details on above see note [Api annotations] in ApiAnnotation

461 462
  | HsFunTy             (LHsType pass)   -- function type
                        (LHsType pass)
463
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow',
464

465 466
      -- For details on above see note [Api annotations] in ApiAnnotation

467
  | HsListTy            (LHsType pass)  -- Element type
Alan Zimmerman's avatar
Alan Zimmerman committed
468 469
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
      --         'ApiAnnotation.AnnClose' @']'@
470

471 472
      -- For details on above see note [Api annotations] in ApiAnnotation

473
  | HsPArrTy            (LHsType pass)  -- Elem. type of parallel array: [:t:]
Alan Zimmerman's avatar
Alan Zimmerman committed
474 475
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
      --         'ApiAnnotation.AnnClose' @':]'@
chak's avatar
chak committed
476

477 478
      -- For details on above see note [Api annotations] in ApiAnnotation

Simon Peyton Jones's avatar
Simon Peyton Jones committed
479
  | HsTupleTy           HsTupleSort
480
                        [LHsType pass]  -- Element types (length gives arity)
Alan Zimmerman's avatar
Alan Zimmerman committed
481 482
    -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(' or '(#'@,
    --         'ApiAnnotation.AnnClose' @')' or '#)'@
483

484 485
    -- For details on above see note [Api annotations] in ApiAnnotation

486
  | HsSumTy             [LHsType pass]  -- Element types (length gives arity)
487 488 489 490 491
    -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(#'@,
    --         'ApiAnnotation.AnnClose' '#)'@

    -- For details on above see note [Api annotations] in ApiAnnotation

492
  | HsOpTy              (LHsType pass) (Located (IdP pass)) (LHsType pass)
Alan Zimmerman's avatar
Alan Zimmerman committed
493
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None
chak's avatar
chak committed
494

495 496
      -- For details on above see note [Api annotations] in ApiAnnotation

497
  | HsParTy             (LHsType pass)   -- See Note [Parens in HsSyn] in HsExpr
Simon Peyton Jones's avatar
Simon Peyton Jones committed
498 499
        -- Parenthesis preserved for the precedence re-arrangement in RnTypes
        -- It's important that a * (b + c) doesn't get rearranged to (a*b) + c!
Alan Zimmerman's avatar
Alan Zimmerman committed
500 501
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
      --         'ApiAnnotation.AnnClose' @')'@
chak's avatar
chak committed
502

503 504
      -- For details on above see note [Api annotations] in ApiAnnotation

505
  | HsIParamTy          (Located HsIPName) -- (?x :: ty)
506 507
                        (LHsType pass)   -- Implicit parameters as they occur in
                                         -- contexts
Alan Zimmerman's avatar
Alan Zimmerman committed
508 509 510 511
      -- ^
      -- > (?x :: ty)
      --
      -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
batterseapower's avatar
batterseapower committed
512

513 514
      -- For details on above see note [Api annotations] in ApiAnnotation

515 516 517 518
  | HsEqTy              (LHsType pass)   -- ty1 ~ ty2
                        (LHsType pass)   -- Always allowed even without
                                         -- TypeOperators, and has special
                                         -- kinding rule
Alan Zimmerman's avatar
Alan Zimmerman committed
519 520 521 522
      -- ^
      -- > ty1 ~ ty2
      --
      -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde'
523

524 525
      -- For details on above see note [Api annotations] in ApiAnnotation

526 527
  | HsKindSig           (LHsType pass)  -- (ty :: kind)
                        (LHsKind pass)  -- A type with a kind signature
Alan Zimmerman's avatar
Alan Zimmerman committed
528 529 530 531 532
      -- ^
      -- > (ty :: kind)
      --
      -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
      --         'ApiAnnotation.AnnDcolon','ApiAnnotation.AnnClose' @')'@
533

534 535
      -- For details on above see note [Api annotations] in ApiAnnotation

536 537
  | HsSpliceTy          (HsSplice pass)   -- Includes quasi-quotes
                        (PostTc pass Kind)
Alan Zimmerman's avatar
Alan Zimmerman committed
538 539
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'$('@,
      --         'ApiAnnotation.AnnClose' @')'@
540

541 542
      -- For details on above see note [Api annotations] in ApiAnnotation

543
  | HsDocTy             (LHsType pass) LHsDocString -- A documented type
Alan Zimmerman's avatar
Alan Zimmerman committed
544
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None
545

546 547
      -- For details on above see note [Api annotations] in ApiAnnotation

548
  | HsBangTy    HsSrcBang (LHsType pass)   -- Bang-style type annotations
Alan Zimmerman's avatar
Alan Zimmerman committed
549 550 551 552 553
      -- ^ - 'ApiAnnotation.AnnKeywordId' :
      --         'ApiAnnotation.AnnOpen' @'{-\# UNPACK' or '{-\# NOUNPACK'@,
      --         'ApiAnnotation.AnnClose' @'#-}'@
      --         'ApiAnnotation.AnnBang' @\'!\'@

554 555
      -- For details on above see note [Api annotations] in ApiAnnotation

556
  | HsRecTy     [LConDeclField pass]    -- Only in data type declarations
Alan Zimmerman's avatar
Alan Zimmerman committed
557 558
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
      --         'ApiAnnotation.AnnClose' @'}'@
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
559

560 561
      -- For details on above see note [Api annotations] in ApiAnnotation

Austin Seipp's avatar
Austin Seipp committed
562 563
  | HsCoreTy Type       -- An escape hatch for tunnelling a *closed*
                        -- Core Type through HsSyn.
Alan Zimmerman's avatar
Alan Zimmerman committed
564
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None
dreixel's avatar
dreixel committed
565

566 567
      -- For details on above see note [Api annotations] in ApiAnnotation

568
  | HsExplicitListTy       -- A promoted explicit list
Alan Zimmerman's avatar
Alan Zimmerman committed
569
        Promoted           -- whether explcitly promoted, for pretty printer
570 571
        (PostTc pass Kind) -- See Note [Promoted lists and tuples]
        [LHsType pass]
Alan Zimmerman's avatar
Alan Zimmerman committed
572 573
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @"'["@,
      --         'ApiAnnotation.AnnClose' @']'@
574

575 576
      -- For details on above see note [Api annotations] in ApiAnnotation

577
  | HsExplicitTupleTy      -- A promoted explicit tuple
578 579
        [PostTc pass Kind] -- See Note [Promoted lists and tuples]
        [LHsType pass]
Alan Zimmerman's avatar
Alan Zimmerman committed
580 581
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @"'("@,
      --         'ApiAnnotation.AnnClose' @')'@
dreixel's avatar
dreixel committed
582

583 584
      -- For details on above see note [Api annotations] in ApiAnnotation

585
  | HsTyLit HsTyLit      -- A promoted numeric literal.
Alan Zimmerman's avatar
Alan Zimmerman committed
586
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None
587

588 589
      -- For details on above see note [Api annotations] in ApiAnnotation

590
  | HsWildCardTy (HsWildCardInfo pass)  -- A type wildcard
591
      -- See Note [The wildcard story for types]
Alan Zimmerman's avatar
Alan Zimmerman committed
592
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None
593 594

      -- For details on above see note [Api annotations] in ApiAnnotation
595
deriving instance (DataId pass) => Data (HsType pass)
dreixel's avatar
dreixel committed
596

597
-- Note [Literal source text] in BasicTypes for SourceText fields in
Alan Zimmerman's avatar
Alan Zimmerman committed
598
-- the following
599
-- | Haskell Type Literal
600
data HsTyLit
Alan Zimmerman's avatar
Alan Zimmerman committed
601 602
  = HsNumTy SourceText Integer
  | HsStrTy SourceText FastString
603
    deriving Data
604

605 606
newtype HsWildCardInfo pass      -- See Note [The wildcard story for types]
    = AnonWildCard (PostRn pass (Located Name))
607 608
      -- A anonymous wild card ('_'). A fresh Name is generated for
      -- each individual anonymous wildcard during renaming
609
deriving instance (DataId pass) => Data (HsWildCardInfo pass)
thomasw's avatar
thomasw committed
610

611
-- | Located Haskell Application Type
612
type LHsAppType pass = Located (HsAppType pass)
613 614
      -- ^ 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSimpleQuote'

615
-- | Haskell Application Type
616 617 618 619
data HsAppType pass
  = HsAppInfix (Located (IdP pass)) -- either a symbol or an id in backticks
  | HsAppPrefix (LHsType pass)      -- anything else, including things like (+)
deriving instance (DataId pass) => Data (HsAppType pass)
620

621 622
instance (SourceTextX pass, OutputableBndrId pass)
       => Outputable (HsAppType pass) where
623
  ppr = ppr_app_ty
624

Austin Seipp's avatar
Austin Seipp committed
625
{-
626 627 628 629
Note [HsForAllTy tyvar binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
After parsing:
  * Implicit => empty
630
    Explicit => the variables the user wrote
631 632 633 634 635

After renaming
  * Implicit => the *type* variables free in the type
    Explicit => the variables the user wrote (renamed)

636 637 638
Qualified currently behaves exactly as Implicit,
but it is deprecated to use it for implicit quantification.
In this case, GHC 7.10 gives a warning; see
Simon Peyton Jones's avatar
Simon Peyton Jones committed
639
Note [Context quantification] in RnTypes, and Trac #4426.
640
In GHC 8.0, Qualified will no longer bind variables
641 642
and this will become an error.

643
The kind variables bound in the hsq_implicit field come both
644 645 646 647
  a) from the kind signatures on the kind vars (eg k1)
  b) from the scope of the forall (eg k2)
Example:   f :: forall (a::k1) b. T a (b::k2)

648

649 650 651 652
Note [Unit tuples]
~~~~~~~~~~~~~~~~~~
Consider the type
    type instance F Int = ()
Austin Seipp's avatar
Austin Seipp committed
653 654
We want to parse that "()"
    as HsTupleTy HsBoxedOrConstraintTuple [],
655 656 657 658 659 660 661
NOT as HsTyVar unitTyCon

Why? Because F might have kind (* -> Constraint), so we when parsing we
don't know if that tuple is going to be a constraint tuple or an ordinary
unit tuple.  The HsTupleSort flag is specifically designed to deal with
that, but it has to work for unit tuples too.

dreixel's avatar
dreixel committed
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
Note [Promotions (HsTyVar)]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
HsTyVar: A name in a type or kind.
  Here are the allowed namespaces for the name.
    In a type:
      Var: not allowed
      Data: promoted data constructor
      Tv: type variable
      TcCls before renamer: type constructor, class constructor, or promoted data constructor
      TcCls after renamer: type constructor or class constructor
    In a kind:
      Var, Data: not allowed
      Tv: kind variable
      TcCls: kind constructor or promoted type constructor

Alan Zimmerman's avatar
Alan Zimmerman committed
677 678 679
  The 'Promoted' field in an HsTyVar captures whether the type was promoted in
  the source code by prefixing an apostrophe.

680 681 682 683 684 685 686 687 688 689
Note [HsAppsTy]
~~~~~~~~~~~~~~~
How to parse

  Foo * Int

? Is it `(*) Foo Int` or `Foo GHC.Types.* Int`? There's no way to know until renaming.
So we just take type expressions like this and put each component in a list, so be
sorted out in the renamer. The sorting out is done by RnTypes.mkHsOpTyRn. This means
that the parser should never produce HsAppTy or HsOpTy.
dreixel's avatar
dreixel committed
690 691 692 693 694 695 696

Note [Promoted lists and tuples]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Notice the difference between
   HsListTy    HsExplicitListTy
   HsTupleTy   HsExplicitListTupleTy

Austin Seipp's avatar
Austin Seipp committed
697
E.g.    f :: [Int]                      HsListTy
dreixel's avatar
dreixel committed
698

Austin Seipp's avatar
Austin Seipp committed
699 700 701
        g3  :: T '[]                   All these use
        g2  :: T '[True]                  HsExplicitListTy
        g1  :: T '[True,False]
dreixel's avatar
dreixel committed
702 703 704 705
        g1a :: T [True,False]             (can omit ' where unambiguous)

  kind of T :: [Bool] -> *        This kind uses HsListTy!

Austin Seipp's avatar
Austin Seipp committed
706 707 708
E.g.    h :: (Int,Bool)                 HsTupleTy; f is a pair
        k :: S '(True,False)            HsExplicitTypleTy; S is indexed by
                                           a type-level pair of booleans
dreixel's avatar
dreixel committed
709 710
        kind of S :: (Bool,Bool) -> *   This kind uses HsExplicitTupleTy

dreixel's avatar
dreixel committed
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
Note [Distinguishing tuple kinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Apart from promotion, tuples can have one of three different kinds:

        x :: (Int, Bool)                -- Regular boxed tuples
        f :: Int# -> (# Int#, Int# #)   -- Unboxed tuples
        g :: (Eq a, Ord a) => a         -- Constraint tuples

For convenience, internally we use a single constructor for all of these,
namely HsTupleTy, but keep track of the tuple kind (in the first argument to
HsTupleTy, a HsTupleSort). We can tell if a tuple is unboxed while parsing,
because of the #. However, with -XConstraintKinds we can only distinguish
between constraint and boxed tuples during type checking, in general. Hence the
four constructors of HsTupleSort:
Austin Seipp's avatar
Austin Seipp committed
726

dreixel's avatar
dreixel committed
727 728 729
        HsUnboxedTuple                  -> Produced by the parser
        HsBoxedTuple                    -> Certainly a boxed tuple
        HsConstraintTuple               -> Certainly a constraint tuple
Austin Seipp's avatar
Austin Seipp committed
730
        HsBoxedOrConstraintTuple        -> Could be a boxed or a constraint
dreixel's avatar
dreixel committed
731 732
                                        tuple. Produced by the parser only,
                                        disappears after type checking
Austin Seipp's avatar
Austin Seipp committed
733
-}
dreixel's avatar
dreixel committed
734

735
-- | Haskell Tuple Sort
batterseapower's avatar
batterseapower committed
736
data HsTupleSort = HsUnboxedTuple
dreixel's avatar
dreixel committed
737 738 739
                 | HsBoxedTuple
                 | HsConstraintTuple
                 | HsBoxedOrConstraintTuple
740
                 deriving Data
batterseapower's avatar
batterseapower committed
741

742

Alan Zimmerman's avatar
Alan Zimmerman committed
743 744 745 746 747
-- | Promoted data types.
data Promoted = Promoted
              | NotPromoted
              deriving (Data, Eq, Show)

748
-- | Located Constructor Declaration Field
749
type LConDeclField pass = Located (ConDeclField pass)
Alan Zimmerman's avatar
Alan Zimmerman committed
750 751
      -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when
      --   in a list
752 753

      -- For details on above see note [Api annotations] in ApiAnnotation
754 755

-- | Constructor Declaration Field
756 757 758 759
data ConDeclField pass  -- Record fields have Haddoc docs on them
  = ConDeclField { cd_fld_names :: [LFieldOcc pass],
                                   -- ^ See Note [ConDeclField passs]
                   cd_fld_type :: LBangType pass,
Adam Gundry's avatar
Adam Gundry committed
760
                   cd_fld_doc  :: Maybe LHsDocString }
Alan Zimmerman's avatar
Alan Zimmerman committed
761
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
762 763

      -- For details on above see note [Api annotations] in ApiAnnotation
764
deriving instance (DataId pass) => Data (ConDeclField pass)
765

766 767
instance (SourceTextX pass, OutputableBndrId pass)
       => Outputable (ConDeclField pass) where
768 769 770 771
  ppr (ConDeclField fld_n fld_ty _) = ppr fld_n <+> dcolon <+> ppr fld_ty

-- HsConDetails is used for patterns/expressions *and* for data type
-- declarations
772
-- | Haskell Constructor Details
773 774 775 776
data HsConDetails arg rec
  = PrefixCon [arg]             -- C p1 p2 p3
  | RecCon    rec               -- C { x = p1, y = p2 }
  | InfixCon  arg arg           -- p1 `C` p2
777
  deriving Data
778 779 780 781 782 783

instance (Outputable arg, Outputable rec)
         => Outputable (HsConDetails arg rec) where
  ppr (PrefixCon args) = text "PrefixCon" <+> ppr args
  ppr (RecCon rec)     = text "RecCon:" <+> ppr rec
  ppr (InfixCon l r)   = text "InfixCon:" <+> ppr [l, r]
Adam Gundry's avatar
Adam Gundry committed
784

785 786 787 788 789 790 791
-- Takes details and result type of a GADT data constructor as created by the
-- parser and rejigs them using information about fixities from the renamer.
-- See Note [Sorting out the result type] in RdrHsSyn
updateGadtResult
  :: (Monad m)
     => (SDoc -> m ())
     -> SDoc
792
     -> HsConDetails (LHsType GhcRn) (Located [LConDeclField GhcRn])
793
                     -- ^ Original details
794 795 796
     -> LHsType GhcRn -- ^ Original result type
     -> m (HsConDetails (LHsType GhcRn) (Located [LConDeclField GhcRn]),
           LHsType GhcRn)
797 798 799 800 801 802 803 804 805 806 807 808
updateGadtResult failWith doc details ty
  = do { let (arg_tys, res_ty) = splitHsFunType ty
             badConSig         = text "Malformed constructor signature"
       ; case details of
           InfixCon {}  -> pprPanic "updateGadtResult" (ppr ty)

           RecCon {}    -> do { unless (null arg_tys)
                                       (failWith (doc <+> badConSig))
                              ; return (details, res_ty) }

           PrefixCon {} -> return (PrefixCon arg_tys, res_ty)}

Adam Gundry's avatar
Adam Gundry committed
809
{-
810
Note [ConDeclField passs]
Adam Gundry's avatar
Adam Gundry committed
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
~~~~~~~~~~~~~~~~~~~~~~~~~

A ConDeclField contains a list of field occurrences: these always
include the field label as the user wrote it.  After the renamer, it
will additionally contain the identity of the selector function in the
second component.

Due to DuplicateRecordFields, the OccName of the selector function
may have been mangled, which is why we keep the original field label
separately.  For example, when DuplicateRecordFields is enabled

    data T = MkT { x :: Int }

gives

    ConDeclField { cd_fld_names = [L _ (FieldOcc "x" $sel:x:MkT)], ... }.
-}

829
-----------------------
830 831 832 833
-- A valid type must have a for-all at the top of the type, or of the fn arg
-- types

---------------------
834
hsWcScopedTvs :: LHsSigWcType GhcRn -> [Name]
835 836 837 838 839 840
-- Get the lexically-scoped type variables of a HsSigType
--  - the explicitly-given forall'd type variables
--  - the implicitly-bound kind variables
--  - the named wildcars; see Note [Scoping of named wildcards]
-- because they scope in the same way
hsWcScopedTvs sig_ty
841 842
  | HsWC { hswc_wcs = nwcs, hswc_body = sig_ty1 }  <- sig_ty
  , HsIB { hsib_vars = vars, hsib_body = sig_ty2 } <- sig_ty1
843 844 845 846 847 848
  = case sig_ty2 of
      L _ (HsForAllTy { hst_bndrs = tvs }) -> vars ++ nwcs ++
                                              map hsLTyVarName tvs
               -- include kind variables only if the type is headed by forall
               -- (this is consistent with GHC 7 behaviour)
      _                                    -> nwcs
849

850
hsScopedTvs :: LHsSigType GhcRn -> [Name]
851 852
-- Same as hsWcScopedTvs, but for a LHsSigType
hsScopedTvs sig_ty
853 854 855 856 857
  | HsIB { hsib_vars = vars,  hsib_body = sig_ty2 } <- sig_ty
  , L _ (HsForAllTy { hst_bndrs = tvs }) <- sig_ty2
  = vars ++ map hsLTyVarName tvs
  | otherwise
  = []
858 859 860 861 862 863 864 865 866 867 868 869 870

{- Note [Scoping of named wildcards]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
  f :: _a -> _a
  f x = let g :: _a -> _a
            g = ...
        in ...

Currently, for better or worse, the "_a" variables are all the same. So
although there is no explicit forall, the "_a" scopes over the definition.
I don't know if this is a good idea, but there it is.
-}
871 872

---------------------
873
hsTyVarName :: HsTyVarBndr pass -> IdP pass
874
hsTyVarName (UserTyVar (L _ n))     = n
Alan Zimmerman's avatar
Alan Zimmerman committed
875
hsTyVarName (KindedTyVar (L _ n) _) = n
876

877
hsLTyVarName :: LHsTyVarBndr pass -> IdP pass
878 879
hsLTyVarName = hsTyVarName . unLoc

880