HsTypes.hs 51.9 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 87
import Type
import HsDoc
import BasicTypes
import SrcLoc
import StaticFlags
88
import Outputable
89
import FastString
thomasw's avatar
thomasw committed
90
import Maybes( isJust )
91

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

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

104
-- | Located Bang Type
105
type LBangType name = Located (BangType name)
106 107

-- | Bang Type
Simon Peyton Jones's avatar
Simon Peyton Jones committed
108
type BangType name  = HsType name       -- Bangs are in the HsType data type
109 110 111 112 113

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

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

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

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

127 128
Note [HsBSig binder lists]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Rik Steenkamp's avatar
Rik Steenkamp committed
129
Consider a binder (or pattern) decorated with a type or kind,
130 131 132 133 134 135 136
   \ (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
137 138 139

Note [HsType binders]
~~~~~~~~~~~~~~~~~~~~~
Alan Zimmerman's avatar
Alan Zimmerman committed
140
The system for recording type and kind-variable binders in HsTypes
141 142 143 144 145
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
146
     HsQualTy     represents an /explicit, user-written/ context
147 148
                   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
149
  These constructors represent what the user wrote, no more
150 151 152 153 154 155 156 157 158 159
  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
160
  the renamer. For example, if the user writes
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
     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

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 219
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
220
-}
221

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

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

228
-- | Haskell Context
batterseapower's avatar
batterseapower committed
229
type HsContext name = [LHsType name]
230

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

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

-- | Haskell Kind
dreixel's avatar
dreixel committed
239
type HsKind name = HsType name
240 241

-- | Located Haskell Kind
dreixel's avatar
dreixel committed
242
type LHsKind name = Located (HsKind name)
243 244 245
      -- ^ 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'

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

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

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

255
-- | Located Haskell Quantified Type Variables
256
data LHsQTyVars name   -- See Note [HsType binders]
257 258
  = HsQTvs { hsq_implicit :: PostRn name [Name]      -- implicit (dependent) variables
           , hsq_explicit :: [LHsTyVarBndr name]     -- explicit variables
259
             -- See Note [HsForAllTy tyvar binders]
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
260 261 262
           , hsq_dependent :: PostRn name NameSet
               -- which explicit vars are dependent
               -- See Note [Dependent LHsQTyVars] in TcHsType
263 264
    }

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

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

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

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

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

281
------------------------------------------------
282
--            HsImplicitBndrs
283 284 285 286 287 288 289
-- 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

290
-- | Haskell Implicit Binders
291
data HsImplicitBndrs name thing   -- See Note [HsType binders]
292
  = HsIB { hsib_vars :: PostRn name [Name] -- Implicitly-bound kind & type vars
293
         , hsib_body :: thing              -- Main payload (type or list of types)
294
    }
295

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

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

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

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

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

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

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

-- 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
334
hsSigWcType sig_ty = hsib_body (hswc_body sig_ty)
335 336 337

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

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

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

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

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

-- 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
372
                              , hsib_vars = [] }
373 374 375

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

378

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

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

396
--------------------------------------------------
397 398

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

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

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

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

422
-- | Haskell Type
423
data HsType name
424 425 426 427
  = 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
428 429
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnForall',
      --         'ApiAnnotation.AnnDot','ApiAnnotation.AnnDarrow'
430 431
      -- For details on above see note [Api annotations] in ApiAnnotation

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
492 493 494
  | 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
495 496
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
      --         'ApiAnnotation.AnnClose' @')'@
chak's avatar
chak committed
497

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

607
-- | Haskell Application Type
608 609 610 611 612
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)

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

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

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

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

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

639

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

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

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

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

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

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

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

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

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

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

733

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

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

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

-- | Constructor Declaration Field
Simon Peyton Jones's avatar
Simon Peyton Jones committed
747
data ConDeclField name  -- Record fields have Haddoc docs on them
Adam Gundry's avatar
Adam Gundry committed
748 749 750 751
  = 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
752
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
753 754

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

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

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

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
774

775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
-- 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
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
{-
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)], ... }.
-}

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

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

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

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

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

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

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

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

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

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

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

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

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

901 902
-- Two wild cards are the same when they have the same location
sameWildCard :: Located (HsWildCardInfo name)
thomasw's avatar
thomasw committed
903 904
             -> Located (HsWildCardInfo name) -> Bool
sameWildCard (L l1 (AnonWildCard _))   (L l2 (AnonWildCard _))   = l1 == l2
thomasw's avatar
thomasw committed
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 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
ignoreParens :: LHsType name -> LHsType name
ignoreParens (L _ (HsParTy ty))                      = ignoreParens ty
ignoreParens (L _ (HsAppsTy [L _ (HsAppPrefix ty)])) = ignoreParens ty
ignoreParens ty                                      = ty

{-
************************************************************************
*                                                                      *
                Building types
*                                                                      *
************************************************************************
-}

mkAnonWildCardTy :: HsType RdrName
mkAnonWildCardTy = HsWildCardTy (AnonWildCard PlaceHolder)

mkHsOpTy :: LHsType name -> Located name -> LHsType name -> HsType name
mkHsOpTy ty1 op ty2 = HsOpTy ty1 op ty2

mkHsAppTy :: LHsType name -> LHsType name -> LHsType name
mkHsAppTy t1 t2 = addCLoc t1 t2 (HsAppTy t1 t2)

mkHsAppTys :: LHsType name -> [LHsType name] -> LHsType name
mkHsAppTys = foldl mkHsAppTy


{-
************************************************************************
*                                                                      *
                Decomposing HsTypes
*                                                                      *
************************************************************************
-}

---------------------------------
-- splitHsFunType decomposes a type (t1 -> t2 ... -> tn)
-- Breaks up any parens in the result type:
--      splitHsFunType (a -> (b -> c)) = ([a,b], c)
-- Also deals with (->) t1 t2; that is why it only works on LHsType Name
--   (see Trac #9096)
splitHsFunType :: LHsType Name -> ([LHsType Name], LHsType Name)
splitHsFunType (L _ (HsParTy ty))
  = splitHsFunType ty

splitHsFunType (L _ (HsFunTy x y))
  | (args, res) <- splitHsFunType y
  = (x:args, res)

splitHsFunType orig_ty@(L _ (HsAppTy t1 t2))
  = go t1 [t2]
  where  -- Look for (->) t1 t2, possibly with parenthesisation
Alan Zimmerman's avatar
Alan Zimmerman committed
957
    go (L _ (HsTyVar _ (L _ fn))) tys | fn == funTyConName
958 959 960 961 962 963 964 965 966 967 968 969
                                 , [t1,t2] <- tys
                                 , (args, res) <- splitHsFunType t2
                                 = (t1:args, res)
    go (L _ (HsAppTy t1 t2)) tys = go t1 (t2:tys)
    go (L _ (HsParTy ty))    tys = go ty tys
    go _                     _   = ([], orig_ty)  -- Failure to match

splitHsFunType other = ([], other)

--------------------------------
-- | Retrieves the head of an HsAppsTy, if this can be done unambiguously,
-- without consulting fixities.
970 971
getAppsTyHead_maybe :: [LHsAppType name]
                    -> Maybe (LHsType name, [LHsType name], LexicalFixity)
972 973
getAppsTyHead_maybe tys = case splitHsAppsTy tys of
  ([app1:apps], []) ->  -- no symbols, some normal types
974
    Just (mkHsAppTys app1 apps, [], Prefix)