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
72
import GhcPrelude

73
import {-# SOURCE #-} HsExpr ( HsSplice, pprSplice )
74

75
76
import PlaceHolder ( PlaceHolder(..) )
import HsExtension
dreixel's avatar
dreixel committed
77

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

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

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

105
-- | Located Bang Type
106
type LBangType pass = Located (BangType pass)
107
108

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

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

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

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

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

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

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

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

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

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

229
-- | Haskell Context
230
type HsContext pass = [LHsType pass]
231

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

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

-- | Haskell Kind
240
type HsKind pass = HsType pass
241
242

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

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

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

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

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

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

265
           , hsq_dependent :: PostRn pass NameSet
Simon Peyton Jones's avatar
Simon Peyton Jones committed
266
267
268
               -- 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
269
               -- See Note [Dependent LHsQTyVars] in TcHsType
270
271
    }

272
deriving instance (DataId pass) => Data (LHsQTyVars pass)
273

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

278
hsQTvExplicit :: LHsQTyVars pass -> [LHsTyVarBndr pass]
279
hsQTvExplicit = hsq_explicit
280

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

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

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

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

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

312
313
314
315
         , 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.
316
317
    }

318
deriving instance (DataId pass, Data thing) => Data (HsWildCardBndrs pass thing)
319

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

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

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

-- See Note [Representing type signatures]

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

334
hsSigType :: LHsSigType pass -> LHsType pass
335
336
hsSigType = hsImplicitBody

337
hsSigWcType :: LHsSigWcType pass -> LHsType pass
338
hsSigWcType sig_ty = hsib_body (hswc_body sig_ty)
339

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

{- 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
352
 * The LHsType binds the /explicitly/ quantified tyvars
353
354
355
356

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

364
mkHsImplicitBndrs :: thing -> HsImplicitBndrs GhcPs thing
Richard Eisenberg's avatar
Richard Eisenberg committed
365
366
367
mkHsImplicitBndrs x = HsIB { hsib_body   = x
                           , hsib_vars   = PlaceHolder
                           , hsib_closed = PlaceHolder }
368

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

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

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

384

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

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

402
--------------------------------------------------
403
404

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

499
  | HsParTy             (LHsType pass)   -- See Note [Parens in HsSyn] in HsExpr
Simon Peyton Jones's avatar
Simon Peyton Jones committed
500
501
        -- 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
502
503
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
      --         'ApiAnnotation.AnnClose' @')'@
chak's avatar
chak committed
504

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

617
-- | Haskell Application Type
618
619
620
621
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)
622

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

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

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

638
639
640
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
641
Note [Context quantification] in RnTypes, and Trac #4426.
642
In GHC 8.0, Qualified will no longer bind variables
643
644
and this will become an error.

645
The kind variables bound in the hsq_implicit field come both
646
647
648
649
  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)

650

651
652
653
654
Note [Unit tuples]
~~~~~~~~~~~~~~~~~~
Consider the type
    type instance F Int = ()
Austin Seipp's avatar
Austin Seipp committed
655
656
We want to parse that "()"
    as HsTupleTy HsBoxedOrConstraintTuple [],
657
658
659
660
661
662
663
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
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
679
680
681
  The 'Promoted' field in an HsTyVar captures whether the type was promoted in
  the source code by prefixing an apostrophe.

682
683
684
685
686
687
688
689
690
691
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
692
693
694
695
696
697
698

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

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

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

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

Austin Seipp's avatar
Austin Seipp committed
708
709
710
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
711
712
        kind of S :: (Bool,Bool) -> *   This kind uses HsExplicitTupleTy

dreixel's avatar
dreixel committed
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
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
728

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

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

744

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

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

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

-- | Constructor Declaration Field
758
759
760
761
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
762
                   cd_fld_doc  :: Maybe LHsDocString }
Alan Zimmerman's avatar
Alan Zimmerman committed
763
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
764
765

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

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

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

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
786

787
788
789
790
791
792
793
-- 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
794
     -> HsConDetails (LHsType GhcRn) (Located [LConDeclField GhcRn])
795
                     -- ^ Original details
796
797
798
     -> LHsType GhcRn -- ^ Original result type
     -> m (HsConDetails (LHsType GhcRn) (Located [LConDeclField GhcRn]),
           LHsType GhcRn)
799
800
801
802
803
804
805
806
807
808
809
810
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
811
{-
812
Note [ConDeclField passs]
Adam Gundry's avatar
Adam Gundry committed
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
~~~~~~~~~~~~~~~~~~~~~~~~~

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

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

---------------------
836
hsWcScopedTvs :: LHsSigWcType GhcRn -> [Name]
837
838
839
840
841
842
-- 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
843
844
  | HsWC { hswc_wcs = nwcs, hswc_body = sig_ty1 }  <- sig_ty
  , HsIB { hsib_vars = vars, hsib_body = sig_ty2 } <- sig_ty1
845
846
847
848
849
850
  = 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
851

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

{- 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.
-}
873
874

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

879
hsLTyVarName :: LHsTyVarBndr pass -> IdP pass
880
881
hsLTyVarName = hsTyVarName . unLoc

882
hsExplicitLTyVarNames :: LHsQTyVars pass -> [IdP pass]
883
884
-- Explicit variables only
hsExplicitLTyVarNames qtvs = map hsLTyVarName (hsQTvExplicit qtvs)
885

886
hsAllLTyVarNames :: LHsQTyVars GhcRn -> [Name]
887
888
-- All variables
hsAllLTyVarNames (HsQTvs { hsq_implicit = kvs, hsq_explicit = tvs })
889
890
  = kvs ++ map hsLTyVarName tvs

891
hsLTyVarLocName :: LHsTyVarBndr pass -> Located (IdP pass)
892
893
hsLTyVarLocName = fmap hsTyVarName

894
hsLTyVarLocNames :: LHsQTyVars pass -> [Located (IdP pass)]
895
896
897
hsLTyVarLocNames qtvs = map hsLTyVarLocName (hsQTvExplicit qtvs)

-- | Convert a LHsTyVarBndr to an equivalent LHsType.
898
hsLTyVarBndrToType :: LHsTyVarBndr pass -> LHsType pass
899
hsLTyVarBndrToType = fmap cvt
Alan Zimmerman's avatar
Alan Zimmerman committed
900
  where cvt (UserTyVar n) = HsTyVar NotPromoted n
901
        cvt (KindedTyVar (L name_loc n) kind)
Alan Zimmerman's avatar
Alan Zimmerman committed
902
          = HsKindSig (L name_loc (HsTyVar NotPromoted (L name_loc n))) kind
903

904
905
-- | Convert a LHsTyVarBndrs to a list of types.
-- Works on *type* variable only, no kind vars.
906
hsLTyVarBndrsToTypes :: LHsQTyVars pass -> [LHsType pass]
907
hsLTyVarBndrsToTypes (HsQTvs { hsq_explicit = tvbs }) = map hsLTyVarBndrToType tvbs
908

thomasw's avatar
thomasw committed
909
---------------------
910
wildCardName :: HsWildCardInfo GhcRn -> Name
911
wildCardName (AnonWildCard  (L _ n)) = n
thomasw's avatar
thomasw committed
912

913
-- Two wild cards are the same when they have the same location
914
915
sameWildCard :: Located (HsWildCardInfo pass)
             -> Located (HsWildCardInfo pass) -> Bool
thomasw's avatar
thomasw committed
916
sameWildCard (L l1 (AnonWildCard _))   (L l2 (AnonWildCard _))   = l1 == l2
thomasw's avatar
thomasw committed
917

918
ignoreParens :: LHsType pass -> LHsType pass
919
920
921
922
923
924
925
926
927
928
929
930
ignoreParens (L _ (HsParTy ty))                      = ignoreParens ty
ignoreParens (L _ (HsAppsTy [L _ (HsAppPrefix ty)])) = ignoreParens ty
ignoreParens ty                                      = ty

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

931
mkAnonWildCardTy :: HsType GhcPs
932
933
mkAnonWildCardTy = HsWildCardTy (AnonWildCard PlaceHolder)

934
mkHsOpTy :: LHsType pass -> Located (IdP pass) -> LHsType pass -> HsType pass
935
936
mkHsOpTy ty1 op ty2 = HsOpTy ty1 op ty2

937
mkHsAppTy :: LHsType pass -> LHsType pass -> LHsType pass
938
939
mkHsAppTy t1 t2 = addCLoc t1 t2 (HsAppTy t1 t2)

940
mkHsAppTys :: LHsType pass -> [LHsType pass] -> LHsType pass
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
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)
958
splitHsFunType :: LHsType GhcRn -> ([LHsType GhcRn], LHsType GhcRn)
959
960
961
962
963
964
965
966
967
968
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
969
    go (L _ (HsTyVar _ (L _ fn))) tys | fn == funTyConName
970
971
972
973
974
975
976
977
978
979
980
981
                                 , [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.
982
983
getAppsTyHead_maybe :: [LHsAppType pass]
                    -> Maybe (LHsType pass, [LHsType pass], LexicalFixity)
984
985