HsTypes.hs 51.8 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
        pprParendHsType, pprHsForAll, pprHsForAllTvs, pprHsForAllExtra,
68
        pprHsContext, pprHsContextNoArrow, pprHsContextMaybe
69 70
    ) where

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

73
import PlaceHolder ( PostTc,PostRn,DataId,PlaceHolder(..),
74
                     OutputableBndrId )
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 name = Located (BangType name)
105 106

-- | Bang Type
Simon Peyton Jones's avatar
Simon Peyton Jones committed
107
type BangType name  = HsType name       -- 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 name = Located (HsContext name)
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
batterseapower's avatar
batterseapower committed
228
type HsContext name = [LHsType name]
229

230
-- | Located Haskell Type
231
type LHsType name = Located (HsType name)
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
dreixel's avatar
dreixel committed
238
type HsKind name = HsType name
239 240

-- | Located Haskell Kind
dreixel's avatar
dreixel committed
241
type LHsKind name = Located (HsKind name)
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 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 257
  = HsQTvs { hsq_implicit :: PostRn name [Name]      -- implicit (dependent) variables
           , hsq_explicit :: [LHsTyVarBndr name]     -- explicit variables
258
             -- See Note [HsForAllTy tyvar binders]
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
259 260 261
           , hsq_dependent :: PostRn name NameSet
               -- which explicit vars are dependent
               -- See Note [Dependent LHsQTyVars] in TcHsType
262 263
    }

264
deriving instance (DataId name) => Data (LHsQTyVars name)
265

266
mkHsQTvs :: [LHsTyVarBndr RdrName] -> LHsQTyVars RdrName
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
267 268
mkHsQTvs tvs = HsQTvs { hsq_implicit = PlaceHolder, hsq_explicit = tvs
                      , hsq_dependent = PlaceHolder }
269

270 271
hsQTvExplicit :: LHsQTyVars name -> [LHsTyVarBndr name]
hsQTvExplicit = hsq_explicit
272

273
emptyLHsQTvs :: LHsQTyVars Name
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
274
emptyLHsQTvs = HsQTvs [] [] emptyNameSet
275 276

isEmptyLHsQTvs :: LHsQTyVars Name -> Bool
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
277 278
isEmptyLHsQTvs (HsQTvs [] [] _) = True
isEmptyLHsQTvs _                = False
279

280
------------------------------------------------
281
--            HsImplicitBndrs
282 283 284 285 286 287 288
-- Used to quantify the binders of a type in cases
-- when a HsForAll isn't appropriate:
--    * Patterns in a type/data family instance (HsTyPats)
--    * Type of a rule binder (RuleBndr)
--    * Pattern type signatures (SigPatIn)
-- In the last of these, wildcards can happen, so we must accommodate them

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
    }
294

295
-- | Haskell Wildcard Binders
296 297 298
data HsWildCardBndrs name thing
    -- See Note [HsType binders]
    -- See Note [The wildcard story for types]
299 300
  = HsWC { hswc_wcs :: PostRn name [Name]
                -- Wild cards, both named and anonymous
301
                -- after the renamer
302

303 304 305 306
         , 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.
307 308
    }

309
deriving instance (Data name, Data thing, Data (PostRn name [Name]))
310
  => Data (HsImplicitBndrs name thing)
311

312 313 314
deriving instance (Data name, Data thing, Data (PostRn name [Name]))
  => Data (HsWildCardBndrs name thing)

315
-- | Located Haskell Signature Type
316
type LHsSigType   name = HsImplicitBndrs name (LHsType name)    -- Implicit only
317 318

-- | Located Haskell Wildcard Type
319
type LHsWcType    name = HsWildCardBndrs name (LHsType name)    -- Wildcard only
320 321

-- | Located Haskell Signature Wildcard Type
322
type LHsSigWcType name = HsWildCardBndrs name (LHsSigType name) -- Both
323 324 325 326 327 328 329 330 331 332

-- See Note [Representing type signatures]

hsImplicitBody :: HsImplicitBndrs name thing -> thing
hsImplicitBody (HsIB { hsib_body = body }) = body

hsSigType :: LHsSigType name -> LHsType name
hsSigType = hsImplicitBody

hsSigWcType :: LHsSigWcType name -> LHsType name
333
hsSigWcType sig_ty = hsib_body (hswc_body sig_ty)
334 335 336

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

{- 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
347
 * The LHsType binds the /explicitly/ quantified tyvars
348 349 350 351

E.g. For a signature like
   f :: forall (a::k). blah
we get
352
   HsIB { hsib_vars = [k]
353 354 355
        , hsib_body = HsForAllTy { hst_bndrs = [(a::*)]
                                 , hst_body = blah }
The implicit kind variable 'k' is bound by the HsIB;
356
the explicitly forall'd tyvar 'a' is bound by the HsForAllTy
357 358 359 360
-}

mkHsImplicitBndrs :: thing -> HsImplicitBndrs RdrName thing
mkHsImplicitBndrs x = HsIB { hsib_body = x
361
                           , hsib_vars = PlaceHolder }
362 363 364

mkHsWildCardBndrs :: thing -> HsWildCardBndrs RdrName thing
mkHsWildCardBndrs x = HsWC { hswc_body = x
365
                           , hswc_wcs  = PlaceHolder }
366 367 368 369 370

-- Add empty binders.  This is a bit suspicious; what if
-- the wrapped thing had free type variables?
mkEmptyImplicitBndrs :: thing -> HsImplicitBndrs Name thing
mkEmptyImplicitBndrs x = HsIB { hsib_body = x
371
                              , hsib_vars = [] }
372 373 374

mkEmptyWildCardBndrs :: thing -> HsWildCardBndrs Name thing
mkEmptyWildCardBndrs x = HsWC { hswc_body = x
375
                              , hswc_wcs  = [] }
376

377

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

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

395
--------------------------------------------------
396 397

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

        -- For details on above see note [Api annotations] in ApiAnnotation
410
deriving instance (DataId name) => Data (HsTyVarBndr name)
411

412 413 414 415 416
-- | Does this 'HsTyVarBndr' come with an explicit kind annotation?
isHsKindedTyVar :: HsTyVarBndr name -> Bool
isHsKindedTyVar (UserTyVar {})   = False
isHsKindedTyVar (KindedTyVar {}) = True

417
-- | Do all type variables in this 'LHsQTyVars' come with kind annotations?
418
hsTvbAllKinded :: LHsQTyVars name -> Bool
419
hsTvbAllKinded = all (isHsKindedTyVar . unLoc) . hsQTvExplicit
420

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

431 432 433 434
  | HsQualTy   -- See Note [HsType binders]
      { hst_ctxt :: LHsContext name       -- Context C => blah
      , hst_body :: LHsType name }

435
  | HsTyVar             Promoted -- whether explicitly promoted, for the pretty
Alan Zimmerman's avatar
Alan Zimmerman committed
436 437
                                 -- printer
                        (Located name)
438 439
                  -- Type variable, type constructor, or data constructor
                  -- see Note [Promotions (HsTyVar)]
440
                  -- See Note [Located RdrNames] in HsExpr
Alan Zimmerman's avatar
Alan Zimmerman committed
441
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None
442

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

Alan Zimmerman's avatar
Alan Zimmerman committed
445
  | HsAppsTy            [LHsAppType name] -- Used only before renaming,
446 447 448
                                          -- Note [HsAppsTy]
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None

Simon Peyton Jones's avatar
Simon Peyton Jones committed
449 450
  | HsAppTy             (LHsType name)
                        (LHsType name)
Alan Zimmerman's avatar
Alan Zimmerman committed
451
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None
452

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
455 456
  | HsFunTy             (LHsType name)   -- function type
                        (LHsType name)
457
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow',
458

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
461
  | HsListTy            (LHsType name)  -- Element type
Alan Zimmerman's avatar
Alan Zimmerman committed
462 463
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
      --         'ApiAnnotation.AnnClose' @']'@
464

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
467
  | HsPArrTy            (LHsType name)  -- Elem. type of parallel array: [:t:]
Alan Zimmerman's avatar
Alan Zimmerman committed
468 469
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
      --         'ApiAnnotation.AnnClose' @':]'@
chak's avatar
chak committed
470

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
473 474
  | HsTupleTy           HsTupleSort
                        [LHsType name]  -- Element types (length gives arity)
Alan Zimmerman's avatar
Alan Zimmerman committed
475 476
    -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(' or '(#'@,
    --         'ApiAnnotation.AnnClose' @')' or '#)'@
477

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

480 481 482 483 484 485
  | HsSumTy             [LHsType name]  -- Element types (length gives arity)
    -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(#'@,
    --         'ApiAnnotation.AnnClose' '#)'@

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

486
  | HsOpTy              (LHsType name) (Located name) (LHsType name)
Alan Zimmerman's avatar
Alan Zimmerman committed
487
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None
chak's avatar
chak committed
488

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
491 492 493
  | HsParTy             (LHsType name)   -- See Note [Parens in HsSyn] in HsExpr
        -- 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
494 495
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
      --         'ApiAnnotation.AnnClose' @')'@
chak's avatar
chak committed
496

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

499
  | HsIParamTy          (Located HsIPName) -- (?x :: ty)
batterseapower's avatar
batterseapower committed
500
                        (LHsType name)   -- Implicit parameters as they occur in contexts
Alan Zimmerman's avatar
Alan Zimmerman committed
501 502 503 504
      -- ^
      -- > (?x :: ty)
      --
      -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
batterseapower's avatar
batterseapower committed
505

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

batterseapower's avatar
batterseapower committed
508 509
  | HsEqTy              (LHsType name)   -- ty1 ~ ty2
                        (LHsType name)   -- Always allowed even without TypeOperators, and has special kinding rule
Alan Zimmerman's avatar
Alan Zimmerman committed
510 511 512 513
      -- ^
      -- > ty1 ~ ty2
      --
      -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde'
514

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
517 518
  | HsKindSig           (LHsType name)  -- (ty :: kind)
                        (LHsKind name)  -- A type with a kind signature
Alan Zimmerman's avatar
Alan Zimmerman committed
519 520 521 522 523
      -- ^
      -- > (ty :: kind)
      --
      -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
      --         'ApiAnnotation.AnnDcolon','ApiAnnotation.AnnClose' @')'@
524

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

527
  | HsSpliceTy          (HsSplice name)   -- Includes quasi-quotes
528
                        (PostTc name Kind)
Alan Zimmerman's avatar
Alan Zimmerman committed
529 530
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'$('@,
      --         'ApiAnnotation.AnnClose' @')'@
531

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

534
  | HsDocTy             (LHsType name) LHsDocString -- A documented type
Alan Zimmerman's avatar
Alan Zimmerman committed
535
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None
536

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
539
  | HsBangTy    HsSrcBang (LHsType name)   -- Bang-style type annotations
Alan Zimmerman's avatar
Alan Zimmerman committed
540 541 542 543 544
      -- ^ - 'ApiAnnotation.AnnKeywordId' :
      --         'ApiAnnotation.AnnOpen' @'{-\# UNPACK' or '{-\# NOUNPACK'@,
      --         'ApiAnnotation.AnnClose' @'#-}'@
      --         'ApiAnnotation.AnnBang' @\'!\'@

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

Alan Zimmerman's avatar
Alan Zimmerman committed
547 548 549
  | HsRecTy     [LConDeclField name]    -- Only in data type declarations
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
      --         'ApiAnnotation.AnnClose' @'}'@
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
550

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

Austin Seipp's avatar
Austin Seipp committed
553 554
  | HsCoreTy Type       -- An escape hatch for tunnelling a *closed*
                        -- Core Type through HsSyn.
Alan Zimmerman's avatar
Alan Zimmerman committed
555
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None
dreixel's avatar
dreixel committed
556

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

559
  | HsExplicitListTy       -- A promoted explicit list
Alan Zimmerman's avatar
Alan Zimmerman committed
560
        Promoted           -- whether explcitly promoted, for pretty printer
561
        (PostTc name Kind) -- See Note [Promoted lists and tuples]
562
        [LHsType name]
Alan Zimmerman's avatar
Alan Zimmerman committed
563 564
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @"'["@,
      --         'ApiAnnotation.AnnClose' @']'@
565

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

568 569
  | HsExplicitTupleTy      -- A promoted explicit tuple
        [PostTc name Kind] -- See Note [Promoted lists and tuples]
570
        [LHsType name]
Alan Zimmerman's avatar
Alan Zimmerman committed
571 572
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @"'("@,
      --         'ApiAnnotation.AnnClose' @')'@
dreixel's avatar
dreixel committed
573

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

576
  | HsTyLit HsTyLit      -- A promoted numeric literal.
Alan Zimmerman's avatar
Alan Zimmerman committed
577
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None
578

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

thomasw's avatar
thomasw committed
581
  | HsWildCardTy (HsWildCardInfo name)  -- A type wildcard
582
      -- See Note [The wildcard story for types]
Alan Zimmerman's avatar
Alan Zimmerman committed
583
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None
584 585

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

588
-- Note [Literal source text] in BasicTypes for SourceText fields in
Alan Zimmerman's avatar
Alan Zimmerman committed
589
-- the following
590
-- | Haskell Type Literal
591
data HsTyLit
Alan Zimmerman's avatar
Alan Zimmerman committed
592 593
  = HsNumTy SourceText Integer
  | HsStrTy SourceText FastString
594
    deriving Data
595

596
newtype HsWildCardInfo name      -- See Note [The wildcard story for types]
597
    = AnonWildCard (PostRn name (Located Name))
598 599
      -- A anonymous wild card ('_'). A fresh Name is generated for
      -- each individual anonymous wildcard during renaming
thomasw's avatar
thomasw committed
600 601
deriving instance (DataId name) => Data (HsWildCardInfo name)

602
-- | Located Haskell Application Type
603 604 605
type LHsAppType name = Located (HsAppType name)
      -- ^ 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSimpleQuote'

606
-- | Haskell Application Type
607 608 609 610 611
data HsAppType name
  = HsAppInfix (Located name)       -- either a symbol or an id in backticks
  | HsAppPrefix (LHsType name)      -- anything else, including things like (+)
deriving instance (DataId name) => Data (HsAppType name)

612
instance (OutputableBndrId name) => Outputable (HsAppType name) where
613 614
  ppr = ppr_app_ty TopPrec

Austin Seipp's avatar
Austin Seipp committed
615
{-
616 617 618 619
Note [HsForAllTy tyvar binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
After parsing:
  * Implicit => empty
620
    Explicit => the variables the user wrote
621 622 623 624 625

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

626 627 628
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
629
Note [Context quantification] in RnTypes, and Trac #4426.
630
In GHC 8.0, Qualified will no longer bind variables
631 632
and this will become an error.

633
The kind variables bound in the hsq_implicit field come both
634 635 636 637
  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)

638

639 640 641 642
Note [Unit tuples]
~~~~~~~~~~~~~~~~~~
Consider the type
    type instance F Int = ()
Austin Seipp's avatar
Austin Seipp committed
643 644
We want to parse that "()"
    as HsTupleTy HsBoxedOrConstraintTuple [],
645 646 647 648 649 650 651
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
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
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
667 668 669
  The 'Promoted' field in an HsTyVar captures whether the type was promoted in
  the source code by prefixing an apostrophe.

670 671 672 673 674 675 676 677 678 679
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
680 681 682 683 684 685 686

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

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

Austin Seipp's avatar
Austin Seipp committed
689 690 691
        g3  :: T '[]                   All these use
        g2  :: T '[True]                  HsExplicitListTy
        g1  :: T '[True,False]
dreixel's avatar
dreixel committed
692 693 694 695
        g1a :: T [True,False]             (can omit ' where unambiguous)

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

Austin Seipp's avatar
Austin Seipp committed
696 697 698
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
699 700
        kind of S :: (Bool,Bool) -> *   This kind uses HsExplicitTupleTy

dreixel's avatar
dreixel committed
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
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
716

dreixel's avatar
dreixel committed
717 718 719
        HsUnboxedTuple                  -> Produced by the parser
        HsBoxedTuple                    -> Certainly a boxed tuple
        HsConstraintTuple               -> Certainly a constraint tuple
Austin Seipp's avatar
Austin Seipp committed
720
        HsBoxedOrConstraintTuple        -> Could be a boxed or a constraint
dreixel's avatar
dreixel committed
721 722
                                        tuple. Produced by the parser only,
                                        disappears after type checking
Austin Seipp's avatar
Austin Seipp committed
723
-}
dreixel's avatar
dreixel committed
724

725
-- | Haskell Tuple Sort
batterseapower's avatar
batterseapower committed
726
data HsTupleSort = HsUnboxedTuple
dreixel's avatar
dreixel committed
727 728 729
                 | HsBoxedTuple
                 | HsConstraintTuple
                 | HsBoxedOrConstraintTuple
730
                 deriving Data
batterseapower's avatar
batterseapower committed
731

732

Alan Zimmerman's avatar
Alan Zimmerman committed
733 734 735 736 737
-- | Promoted data types.
data Promoted = Promoted
              | NotPromoted
              deriving (Data, Eq, Show)

738
-- | Located Constructor Declaration Field
739
type LConDeclField name = Located (ConDeclField name)
Alan Zimmerman's avatar
Alan Zimmerman committed
740 741
      -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when
      --   in a list
742 743

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

-- | Constructor Declaration Field
Simon Peyton Jones's avatar
Simon Peyton Jones committed
746
data ConDeclField name  -- Record fields have Haddoc docs on them
Adam Gundry's avatar
Adam Gundry committed
747 748 749 750
  = ConDeclField { cd_fld_names :: [LFieldOcc name],
                                   -- ^ See Note [ConDeclField names]
                   cd_fld_type :: LBangType name,
                   cd_fld_doc  :: Maybe LHsDocString }
Alan Zimmerman's avatar
Alan Zimmerman committed
751
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
752 753

      -- For details on above see note [Api annotations] in ApiAnnotation
754
deriving instance (DataId name) => Data (ConDeclField name)
755

756
instance (OutputableBndrId name) => Outputable (ConDeclField name) where
757 758 759 760
  ppr (ConDeclField fld_n fld_ty _) = ppr fld_n <+> dcolon <+> ppr fld_ty

-- HsConDetails is used for patterns/expressions *and* for data type
-- declarations
761
-- | Haskell Constructor Details
762 763 764 765
data HsConDetails arg rec
  = PrefixCon [arg]             -- C p1 p2 p3
  | RecCon    rec               -- C { x = p1, y = p2 }
  | InfixCon  arg arg           -- p1 `C` p2
766
  deriving Data
767 768 769 770 771 772

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
773

774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
-- 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
     -> HsConDetails (LHsType Name) (Located [LConDeclField Name])
                     -- ^ Original details
     -> LHsType Name -- ^ Original result type
     -> m (HsConDetails (LHsType Name) (Located [LConDeclField Name]),
           LHsType Name)
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
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
{-
Note [ConDeclField names]
~~~~~~~~~~~~~~~~~~~~~~~~~

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)], ... }.
-}

818
-----------------------
819 820 821 822
-- A valid type must have a for-all at the top of the type, or of the fn arg
-- types

---------------------
823 824 825 826 827 828 829
hsWcScopedTvs :: LHsSigWcType Name -> [Name]
-- 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
830 831
  | HsWC { hswc_wcs = nwcs, hswc_body = sig_ty1 }  <- sig_ty
  , HsIB { hsib_vars = vars, hsib_body = sig_ty2 } <- sig_ty1
832 833 834 835 836 837
  = 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
838 839 840 841

hsScopedTvs :: LHsSigType Name -> [Name]
-- Same as hsWcScopedTvs, but for a LHsSigType
hsScopedTvs sig_ty
842 843 844 845 846
  | HsIB { hsib_vars = vars,  hsib_body = sig_ty2 } <- sig_ty
  , L _ (HsForAllTy { hst_bndrs = tvs }) <- sig_ty2
  = vars ++ map hsLTyVarName tvs
  | otherwise
  = []
847 848 849 850 851 852 853 854 855 856 857 858 859

{- 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.
-}
860 861

---------------------
862
hsTyVarName :: HsTyVarBndr name -> name
863
hsTyVarName (UserTyVar (L _ n))     = n
Alan Zimmerman's avatar
Alan Zimmerman committed
864
hsTyVarName (KindedTyVar (L _ n) _) = n
865

866 867 868
hsLTyVarName :: LHsTyVarBndr name -> name
hsLTyVarName = hsTyVarName . unLoc

869 870 871
hsExplicitLTyVarNames :: LHsQTyVars name -> [name]
-- Explicit variables only
hsExplicitLTyVarNames qtvs = map hsLTyVarName (hsQTvExplicit qtvs)
872

873 874 875
hsAllLTyVarNames :: LHsQTyVars Name -> [Name]
-- All variables
hsAllLTyVarNames (HsQTvs { hsq_implicit = kvs, hsq_explicit = tvs })
876 877
  = kvs ++ map hsLTyVarName tvs

878 879 880
hsLTyVarLocName :: LHsTyVarBndr name -> Located name
hsLTyVarLocName = fmap hsTyVarName

881 882 883 884
hsLTyVarLocNames :: LHsQTyVars name -> [Located name]
hsLTyVarLocNames qtvs = map hsLTyVarLocName (hsQTvExplicit qtvs)

-- | Convert a LHsTyVarBndr to an equivalent LHsType.
885 886
hsLTyVarBndrToType :: LHsTyVarBndr name -> LHsType name
hsLTyVarBndrToType = fmap cvt
Alan Zimmerman's avatar
Alan Zimmerman committed
887
  where cvt (UserTyVar n) = HsTyVar NotPromoted n
888
        cvt (KindedTyVar (L name_loc n) kind)
Alan Zimmerman's avatar
Alan Zimmerman committed
889
          = HsKindSig (L name_loc (HsTyVar NotPromoted (L name_loc n))) kind
890

891 892
-- | Convert a LHsTyVarBndrs to a list of types.
-- Works on *type* variable only, no kind vars.
893
hsLTyVarBndrsToTypes :: LHsQTyVars name -> [LHsType name]
894
hsLTyVarBndrsToTypes (HsQTvs { hsq_explicit = tvbs }) = map hsLTyVarBndrToType tvbs
895

thomasw's avatar
thomasw committed
896
---------------------
thomasw's avatar
thomasw committed
897
wildCardName :: HsWildCardInfo Name -> Name
898
wildCardName (AnonWildCard  (L _ n)) = n
thomasw's avatar
thomasw committed
899

900 901
-- Two wild cards are the same when they have the same location
sameWildCard :: Located (HsWildCardInfo name)
thomasw's avatar
thomasw committed
902 903
             -> Located (HsWildCardInfo name) -> Bool
sameWildCard (L l1 (AnonWildCard _))   (L l2 (AnonWildCard _))   = l1 == l2
thomasw's avatar
thomasw committed
904

905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937