Type.hs 75.7 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
GHC.Hs.Type: Abstract syntax: user-defined types
Austin Seipp's avatar
Austin Seipp committed
7
-}
8

9
{-# LANGUAGE DeriveDataTypeable #-}
10
{-# LANGUAGE FlexibleContexts #-}
My Nguyen's avatar
My Nguyen committed
11
{-# LANGUAGE FlexibleInstances #-}
12
{-# LANGUAGE ScopedTypeVariables #-}
13
14
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeSynonymInstances #-}
15
16
{-# LANGUAGE UndecidableInstances #-} -- Wrinkle in Note [Trees That Grow]
                                      -- in module GHC.Hs.Extension
17
{-# LANGUAGE ConstraintKinds #-}
18
{-# LANGUAGE CPP #-}
19
{-# LANGUAGE TypeFamilies #-}
Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
20
21
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ViewPatterns #-}
22

23
module GHC.Hs.Type (
Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
24
25
26
27
28
        Mult, HsScaled(..),
        hsMult, hsScaledThing,
        HsArrow(..), arrowToHsType,
        hsLinear, hsUnrestricted, isUnrestricted,

29
        HsType(..), NewHsTypeX(..), LHsType, HsKind, LHsKind,
30
        HsForAllTelescope(..), HsTyVarBndr(..), LHsTyVarBndr,
31
        LHsQTyVars(..),
32
        HsImplicitBndrs(..),
33
        HsWildCardBndrs(..),
34
        HsPatSigType(..), HsPSRn(..),
35
36
        LHsSigType, LHsSigWcType, LHsWcType,
        HsTupleSort(..),
37
        HsContext, LHsContext, noLHsContext,
38
        HsTyLit(..),
39
        HsIPName(..), hsIPNameFS,
My Nguyen's avatar
My Nguyen committed
40
        HsArg(..), numVisibleArgs,
41
        LHsTypeArg, lhsTypeArgSrcSpan,
Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
42
        OutputableBndrFlag,
43

44
45
        LBangType, BangType,
        HsSrcBang(..), HsImplBang(..),
46
        SrcStrictness(..), SrcUnpackedness(..),
Austin Seipp's avatar
Austin Seipp committed
47
        getBangType, getBangStrictness,
48

49
        ConDeclField(..), LConDeclField, pprConDeclFields,
50
51

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

Adam Gundry's avatar
Adam Gundry committed
53
54
55
56
57
        FieldOcc(..), LFieldOcc, mkFieldOcc,
        AmbiguousFieldOcc(..), mkAmbiguousFieldOcc,
        rdrNameAmbiguousFieldOcc, selectorAmbiguousFieldOcc,
        unambiguousFieldOcc, ambiguousFieldOcc,

My Nguyen's avatar
My Nguyen committed
58
        mkAnonWildCardTy, pprAnonWildCard,
thomasw's avatar
thomasw committed
59

60
        mkHsImplicitBndrs, mkHsWildCardBndrs, mkHsPatSigType, hsImplicitBody,
61
        mkEmptyImplicitBndrs, mkEmptyWildCardBndrs,
62
        mkHsForAllVisTele, mkHsForAllInvisTele,
Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
63
        mkHsQTvs, hsQTvExplicit, emptyLHsQTvs,
64
        isHsKindedTyVar, hsTvbAllKinded, isLHsForAllTy,
65
        hsScopedTvs, hsWcScopedTvs, dropWildCards,
66
        hsTyVarName, hsAllLTyVarNames, hsLTyVarLocNames,
67
        hsLTyVarName, hsLTyVarNames, hsLTyVarLocName, hsExplicitLTyVarNames,
68
        splitLHsInstDeclTy, getLHsInstDeclHead, getLHsInstDeclClass_maybe,
69
        splitLHsPatSynTy,
70
71
        splitLHsForAllTyInvis, splitLHsQualTy,
        splitLHsSigmaTyInvis, splitLHsGADTPrefixTy,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
72
        splitHsFunType, hsTyGetAppHead_maybe,
My Nguyen's avatar
My Nguyen committed
73
        mkHsOpTy, mkHsAppTy, mkHsAppTys, mkHsAppKindTy,
74
        ignoreParens, hsSigType, hsSigWcType, hsPatSigType,
75
        hsTyKindSig,
76
        hsConDetailsArgs,
Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
77
        setHsTyVarBndrFlag, hsTyVarBndrFlag,
78

Simon Peyton Jones's avatar
Simon Peyton Jones committed
79
        -- Printing
80
        pprHsType, pprHsForAll, pprHsForAllExtra, pprHsExplicitForAll,
81
        pprLHsContext,
82
        hsTypeNeedsParens, parenthesizeHsType, parenthesizeHsContext
83
84
    ) where

85
86
#include "HsVersions.h"

87
import GHC.Prelude
88

Sylvain Henry's avatar
Sylvain Henry committed
89
import {-# SOURCE #-} GHC.Hs.Expr ( HsSplice, pprSplice )
90

Sylvain Henry's avatar
Sylvain Henry committed
91
import GHC.Hs.Extension
dreixel's avatar
dreixel committed
92

Sylvain Henry's avatar
Sylvain Henry committed
93
94
95
import GHC.Types.Id ( Id )
import GHC.Types.Name( Name, NamedThing(getName) )
import GHC.Types.Name.Reader ( RdrName )
Sylvain Henry's avatar
Sylvain Henry committed
96
97
import GHC.Core.DataCon( HsSrcBang(..), HsImplBang(..),
                         SrcStrictness(..), SrcUnpackedness(..) )
Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
98
import GHC.Builtin.Types( manyDataConName, oneDataConName, mkTupleStr )
Sylvain Henry's avatar
Sylvain Henry committed
99
import GHC.Core.Type
Sylvain Henry's avatar
Sylvain Henry committed
100
import GHC.Hs.Doc
Sylvain Henry's avatar
Sylvain Henry committed
101
102
import GHC.Types.Basic
import GHC.Types.SrcLoc
103
104
105
106
import GHC.Utils.Outputable
import GHC.Data.FastString
import GHC.Data.Maybe( isJust )
import GHC.Utils.Misc ( count )
107

108
import Data.Data hiding ( Fixity, Prefix, Infix )
109

Austin Seipp's avatar
Austin Seipp committed
110
111
112
{-
************************************************************************
*                                                                      *
113
\subsection{Bang annotations}
Austin Seipp's avatar
Austin Seipp committed
114
115
116
*                                                                      *
************************************************************************
-}
117

118
-- | Located Bang Type
119
type LBangType pass = Located (BangType pass)
120
121

-- | Bang Type
122
123
124
125
126
--
-- In the parser, strictness and packedness annotations bind more tightly
-- than docstrings. This means that when consuming a 'BangType' (and looking
-- for 'HsBangTy') we must be ready to peer behind a potential layer of
-- 'HsDocTy'. See #15206 for motivation and 'getBangType' for an example.
127
type BangType pass  = HsType pass       -- Bangs are in the HsType data type
128
129

getBangType :: LHsType a -> LHsType a
130
131
132
133
getBangType                 (L _ (HsBangTy _ _ lty))       = lty
getBangType (L _ (HsDocTy x (L _ (HsBangTy _ _ lty)) lds)) =
  addCLoc lty lds (HsDocTy x lty lds)
getBangType lty                                            = lty
134

Simon Peyton Jones's avatar
Simon Peyton Jones committed
135
getBangStrictness :: LHsType a -> HsSrcBang
136
137
getBangStrictness                 (L _ (HsBangTy _ s _))     = s
getBangStrictness (L _ (HsDocTy _ (L _ (HsBangTy _ s _)) _)) = s
Alan Zimmerman's avatar
Alan Zimmerman committed
138
getBangStrictness _ = (HsSrcBang NoSourceText NoSrcUnpack NoSrcStrict)
139

Austin Seipp's avatar
Austin Seipp committed
140
141
142
{-
************************************************************************
*                                                                      *
143
\subsection{Data types}
Austin Seipp's avatar
Austin Seipp committed
144
145
*                                                                      *
************************************************************************
146

147
148
This is the syntax for types as seen in type signatures.

149
150
Note [HsBSig binder lists]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Rik Steenkamp's avatar
Rik Steenkamp committed
151
Consider a binder (or pattern) decorated with a type or kind,
152
153
154
155
156
157
   \ (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
Sylvain Henry's avatar
Sylvain Henry committed
158
See also Note [Kind and type-variable binders] in GHC.Rename.HsType
159
160
161

Note [HsType binders]
~~~~~~~~~~~~~~~~~~~~~
Alan Zimmerman's avatar
Alan Zimmerman committed
162
The system for recording type and kind-variable binders in HsTypes
163
164
165
166
is a bit complicated.  Here's how it works.

* In a HsType,
     HsForAllTy   represents an /explicit, user-written/ 'forall'
Ryan Scott's avatar
Ryan Scott committed
167
168
                   e.g.   forall a b.   {...} or
                          forall a b -> {...}
Rik Steenkamp's avatar
Rik Steenkamp committed
169
     HsQualTy     represents an /explicit, user-written/ context
170
171
                   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
172
  These constructors represent what the user wrote, no more
173
174
  and no less.

175
* The ForAllTelescope field of HsForAllTy represents whether a forall is
Ryan Scott's avatar
Ryan Scott committed
176
177
178
  invisible (e.g., forall a b. {...}, with a dot) or visible
  (e.g., forall a b -> {...}, with an arrow).

179
180
181
182
183
184
185
186
* 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
187
  the renamer. For example, if the user writes
188
189
190
191
192
193
194
195
196
197
198
     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 _.

199
200
201
202
203
204
205
* HsSigPatType describes types that appear in pattern signatures and
  the signatures of term-level binders in RULES. Like
  HsWildCardBndrs/HsImplicitBndrs, they track the names of wildcard
  variables and implicitly bound type variables. Unlike
  HsImplicitBndrs, however, HsSigPatTypes do not obey the
  forall-or-nothing rule. See Note [Pattern signature binders and scoping].

206
207
208
209
210
211
212
213
214
215
* 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

216
217
218
219
220
221
222
223
224
225
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.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
226
227
    The renamer leaves it untouched, and it is later given a fresh
    meta tyvar in the typechecker.
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244

  * 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)
245
  _b is a named wildcard.  (See the comments in #10982)
246

247
248
249
250
251
252
253
254
255
* Named wildcards are bound by the HsWildCardBndrs (for types that obey the
  forall-or-nothing rule) and HsPatSigType (for type signatures in patterns
  and term-level binders in RULES), which wrap types that are allowed to have
  wildcards. Unnamed wildcards, however are left unchanged until typechecking,
  where we give them fresh wild tyvars and determine whether or not to emit
  hole constraints on each wildcard (we don't if it's a visible type/kind
  argument or a type family pattern). See related notes
  Note [Wildcards in visible kind application] and
  Note [Wildcards in visible type application] in GHC.Tc.Gen.HsType.
256
257
258
259

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

260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
Note [Ordering of implicit variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Since the advent of -XTypeApplications, GHC makes promises about the ordering
of implicit variable quantification. Specifically, we offer that implicitly
quantified variables (such as those in const :: a -> b -> a, without a `forall`)
will occur in left-to-right order of first occurrence. Here are a few examples:

  const :: a -> b -> a       -- forall a b. ...
  f :: Eq a => b -> a -> a   -- forall a b. ...  contexts are included

  type a <-< b = b -> a
  g :: a <-< b               -- forall a b. ...  type synonyms matter

  class Functor f where
    fmap :: (a -> b) -> f a -> f b   -- forall f a b. ...
    -- The f is quantified by the class, so only a and b are considered in fmap

This simple story is complicated by the possibility of dependency: all variables
must come after any variables mentioned in their kinds.

  typeRep :: Typeable a => TypeRep (a :: k)   -- forall k a. ...

The k comes first because a depends on k, even though the k appears later than
the a in the code. Thus, GHC does a *stable topological sort* on the variables.
By "stable", we mean that any two variables who do not depend on each other
preserve their existing left-to-right ordering.

287
Implicitly bound variables are collected by the extract- family of functions
Sylvain Henry's avatar
Sylvain Henry committed
288
(extractHsTysRdrTyVars, extractHsTyVarBndrsKVs, etc.) in GHC.Rename.HsType.
289
These functions thus promise to keep left-to-right ordering.
290
291
Look for pointers to this note to see the places where the action happens.

292
293
294
295
296
297
298
299
300
301
302
Note that we also maintain this ordering in kind signatures. Even though
there's no visible kind application (yet), having implicit variables be
quantified in left-to-right order in kind signatures is nice since:

* It's consistent with the treatment for type signatures.
* It can affect how types are displayed with -fprint-explicit-kinds (see
  #15568 for an example), which is a situation where knowing the order in
  which implicit variables are quantified can be useful.
* In the event that visible kind application is implemented, the order in
  which we would expect implicit variables to be ordered in kinds will have
  already been established.
Austin Seipp's avatar
Austin Seipp committed
303
-}
304

305
-- | Located Haskell Context
306
type LHsContext pass = Located (HsContext pass)
Alan Zimmerman's avatar
Alan Zimmerman committed
307
      -- ^ 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnUnit'
Sylvain Henry's avatar
Sylvain Henry committed
308
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
309

310
311
312
313
314
315
316
317
noLHsContext :: LHsContext pass
-- Use this when there is no context in the original program
-- It would really be more kosher to use a Maybe, to distinguish
--     class () => C a where ...
-- from
--     class C a where ...
noLHsContext = noLoc []

318
-- | Haskell Context
319
type HsContext pass = [LHsType pass]
320

321
-- | Located Haskell Type
322
type LHsType pass = Located (HsType pass)
Alan Zimmerman's avatar
Alan Zimmerman committed
323
324
      -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when
      --   in a list
325

Sylvain Henry's avatar
Sylvain Henry committed
326
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
327
328

-- | Haskell Kind
329
type HsKind pass = HsType pass
330
331

-- | Located Haskell Kind
332
type LHsKind pass = Located (HsKind pass)
333
334
      -- ^ 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'

Sylvain Henry's avatar
Sylvain Henry committed
335
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
336

337
--------------------------------------------------
338
339
--             LHsQTyVars
--  The explicitly-quantified binders in a data/type declaration
340

341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
-- | The type variable binders in an 'HsForAllTy'.
-- See also @Note [Variable Specificity and Forall Visibility]@ in
-- "GHC.Tc.Gen.HsType".
data HsForAllTelescope pass
  = HsForAllVis -- ^ A visible @forall@ (e.g., @forall a -> {...}@).
                --   These do not have any notion of specificity, so we use
                --   '()' as a placeholder value.
    { hsf_xvis      :: XHsForAllVis pass
    , hsf_vis_bndrs :: [LHsTyVarBndr () pass]
    }
  | HsForAllInvis -- ^ An invisible @forall@ (e.g., @forall a {b} c -> {...}@),
                  --   where each binder has a 'Specificity'.
    { hsf_xinvis       :: XHsForAllInvis pass
    , hsf_invis_bndrs  :: [LHsTyVarBndr Specificity pass]
    }
  | XHsForAllTelescope !(XXHsForAllTelescope pass)

type instance XHsForAllVis   (GhcPass _) = NoExtField
type instance XHsForAllInvis (GhcPass _) = NoExtField

type instance XXHsForAllTelescope (GhcPass _) = NoExtCon

363
-- | Located Haskell Type Variable Binder
Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
364
type LHsTyVarBndr flag pass = Located (HsTyVarBndr flag pass)
365
                         -- See Note [HsType binders]
366

367
-- | Located Haskell Quantified Type Variables
368
data LHsQTyVars pass   -- See Note [HsType binders]
369
  = HsQTvs { hsq_ext :: XHsQTvs pass
Simon Peyton Jones's avatar
Simon Peyton Jones committed
370

Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
371
           , hsq_explicit :: [LHsTyVarBndr () pass]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
372
                -- Explicit variables, written by the user
373
    }
Ryan Scott's avatar
Ryan Scott committed
374
  | XLHsQTyVars !(XXLHsQTyVars pass)
375

376
377
378
type HsQTvsRn = [Name]  -- Implicit variables
  -- For example, in   data T (a :: k1 -> k2) = ...
  -- the 'a' is explicit while 'k1', 'k2' are implicit
Simon Peyton Jones's avatar
Simon Peyton Jones committed
379

380
type instance XHsQTvs GhcPs = NoExtField
381
382
type instance XHsQTvs GhcRn = HsQTvsRn
type instance XHsQTvs GhcTc = HsQTvsRn
383

384
type instance XXLHsQTyVars  (GhcPass _) = NoExtCon
385

386
387
388
389
390
391
392
393
394
395
mkHsForAllVisTele ::
  [LHsTyVarBndr () (GhcPass p)] -> HsForAllTelescope (GhcPass p)
mkHsForAllVisTele vis_bndrs =
  HsForAllVis { hsf_xvis = noExtField, hsf_vis_bndrs = vis_bndrs }

mkHsForAllInvisTele ::
  [LHsTyVarBndr Specificity (GhcPass p)] -> HsForAllTelescope (GhcPass p)
mkHsForAllInvisTele invis_bndrs =
  HsForAllInvis { hsf_xinvis = noExtField, hsf_invis_bndrs = invis_bndrs }

Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
396
mkHsQTvs :: [LHsTyVarBndr () GhcPs] -> LHsQTyVars GhcPs
397
mkHsQTvs tvs = HsQTvs { hsq_ext = noExtField, hsq_explicit = tvs }
398

Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
399
hsQTvExplicit :: LHsQTyVars pass -> [LHsTyVarBndr () pass]
400
hsQTvExplicit = hsq_explicit
401

402
emptyLHsQTvs :: LHsQTyVars GhcRn
403
emptyLHsQTvs = HsQTvs { hsq_ext = [], hsq_explicit = [] }
404

405
------------------------------------------------
406
--            HsImplicitBndrs
407
408
-- Used to quantify the implicit binders of a type
--    * Implicit binders of a type signature (LHsSigType/LHsSigWcType)
409
410
--    * Patterns in a type/data family instance (HsTyPats)

411
-- | Haskell Implicit Binders
412
data HsImplicitBndrs pass thing   -- See Note [HsType binders]
413
414
415
416
  = HsIB { hsib_ext  :: XHsIB pass thing -- after renamer: [Name]
                                         -- Implicitly-bound kind & type vars
                                         -- Order is important; see
                                         -- Note [Ordering of implicit variables]
Sylvain Henry's avatar
Sylvain Henry committed
417
                                         -- in GHC.Rename.HsType
418

419
         , hsib_body :: thing            -- Main payload (type or list of types)
420
    }
Ryan Scott's avatar
Ryan Scott committed
421
  | XHsImplicitBndrs !(XXHsImplicitBndrs pass thing)
422

423
type instance XHsIB              GhcPs _ = NoExtField
424
425
type instance XHsIB              GhcRn _ = [Name]
type instance XHsIB              GhcTc _ = [Name]
426

427
type instance XXHsImplicitBndrs  (GhcPass _) _ = NoExtCon
428

429
-- | Haskell Wildcard Binders
430
data HsWildCardBndrs pass thing
431
432
    -- See Note [HsType binders]
    -- See Note [The wildcard story for types]
433
  = HsWC { hswc_ext :: XHsWC pass thing
434
                -- after the renamer
My Nguyen's avatar
My Nguyen committed
435
436
                -- Wild cards, only named
                -- See Note [Wildcards in visible kind application]
437

438
439
440
441
         , 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.
442
    }
Ryan Scott's avatar
Ryan Scott committed
443
  | XHsWildCardBndrs !(XXHsWildCardBndrs pass thing)
444

445
type instance XHsWC              GhcPs b = NoExtField
446
447
448
type instance XHsWC              GhcRn b = [Name]
type instance XHsWC              GhcTc b = [Name]

449
type instance XXHsWildCardBndrs  (GhcPass _) b = NoExtCon
450

451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
-- | Types that can appear in pattern signatures, as well as the signatures for
-- term-level binders in RULES.
-- See @Note [Pattern signature binders and scoping]@.
--
-- This is very similar to 'HsSigWcType', but with
-- slightly different semantics: see @Note [HsType binders]@.
-- See also @Note [The wildcard story for types]@.
data HsPatSigType pass
  = HsPS { hsps_ext  :: XHsPS pass   -- ^ After renamer: 'HsPSRn'
         , hsps_body :: LHsType pass -- ^ Main payload (the type itself)
    }
  | XHsPatSigType !(XXHsPatSigType pass)

-- | The extension field for 'HsPatSigType', which is only used in the
-- renamer onwards. See @Note [Pattern signature binders and scoping]@.
data HsPSRn = HsPSRn
  { hsps_nwcs    :: [Name] -- ^ Wildcard names
  , hsps_imp_tvs :: [Name] -- ^ Implicitly bound variable names
  }
  deriving Data

type instance XHsPS GhcPs = NoExtField
type instance XHsPS GhcRn = HsPSRn
type instance XHsPS GhcTc = HsPSRn

type instance XXHsPatSigType (GhcPass _) = NoExtCon

478
-- | Located Haskell Signature Type
479
type LHsSigType   pass = HsImplicitBndrs pass (LHsType pass)    -- Implicit only
480
481

-- | Located Haskell Wildcard Type
482
type LHsWcType    pass = HsWildCardBndrs pass (LHsType pass)    -- Wildcard only
483
484

-- | Located Haskell Signature Wildcard Type
485
type LHsSigWcType pass = HsWildCardBndrs pass (LHsSigType pass) -- Both
486
487
488

-- See Note [Representing type signatures]

489
hsImplicitBody :: HsImplicitBndrs (GhcPass p) thing -> thing
490
491
hsImplicitBody (HsIB { hsib_body = body }) = body

492
hsSigType :: LHsSigType (GhcPass p) -> LHsType (GhcPass p)
493
494
hsSigType = hsImplicitBody

495
hsSigWcType :: LHsSigWcType pass -> LHsType pass
496
hsSigWcType sig_ty = hsib_body (hswc_body sig_ty)
497

498
499
500
hsPatSigType :: HsPatSigType pass -> LHsType pass
hsPatSigType = hsps_body

501
dropWildCards :: LHsSigWcType pass -> LHsSigType pass
502
-- Drop the wildcard part of a LHsSigWcType
503
dropWildCards sig_ty = hswc_body sig_ty
504
505
506
507
508
509
510
511
512

{- 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
513
 * The LHsType binds the /explicitly/ quantified tyvars
514
515
516
517

E.g. For a signature like
   f :: forall (a::k). blah
we get
518
   HsIB { hsib_vars = [k]
519
        , hsib_body = HsForAllTy { hst_tele = HsForAllInvis [(a::*)]
520
521
                                 , hst_body = blah }
The implicit kind variable 'k' is bound by the HsIB;
522
the explicitly forall'd tyvar 'a' is bound by the HsForAllTy
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587

Note [Pattern signature binders and scoping]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the pattern signatures like those on `t` and `g` in:

   f = let h = \(t :: (b, b) ->
               \(g :: forall a. a -> b) ->
               ...(t :: (Int,Int))...
       in woggle

* The `b` in t's pattern signature is implicitly bound and scopes over
  the signature and the body of the lambda.  It stands for a type (any type);
  indeed we subsequently discover that b=Int.
  (See Note [TyVarTv] in GHC.Tc.Utils.TcMType for more on this point.)
* The `b` in g's pattern signature is an /occurrence/ of the `b` bound by
  t's pattern signature.
* The `a` in `forall a` scopes only over the type `a -> b`, not over the body
  of the lambda.
* There is no forall-or-nothing rule for pattern signatures, which is why the
  type `forall a. a -> b` is permitted in `g`'s pattern signature, even though
  `b` is not explicitly bound.
  See Note [forall-or-nothing rule] in GHC.Rename.HsType.

Similar scoping rules apply to term variable binders in RULES, like in the
following example:

   {-# RULES "h" forall (t :: (b, b)) (g :: forall a. a -> b). h t g = ... #-}

Just like in pattern signatures, the `b` in t's signature is implicitly bound
and scopes over the remainder of the RULE. As a result, the `b` in g's
signature is an occurrence. Moreover, the `a` in `forall a` scopes only over
the type `a -> b`, and the forall-or-nothing rule does not apply.

While quite similar, RULE term binder signatures behave slightly differently
from pattern signatures in two ways:

1. Unlike in pattern signatures, where type variables can stand for any type,
   type variables in RULE term binder signatures are skolems.
   See Note [Typechecking pattern signature binders] in GHC.Tc.Gen.HsType for
   more on this point.

   In this sense, type variables in pattern signatures are quite similar to
   named wildcards, as both can refer to arbitrary types. The main difference
   lies in error reporting: if a named wildcard `_a` in a pattern signature
   stands for Int, then by default GHC will emit a warning stating as much.
   Changing `_a` to `a`, on the other hand, will cause it not to be reported.
2. In the `h` RULE above, only term variables are explicitly bound, so any free
   type variables in the term variables' signatures are implicitly bound.
   This is just like how the free type variables in pattern signatures are
   implicitly bound. If a RULE explicitly binds both term and type variables,
   however, then free type variables in term signatures are /not/ implicitly
   bound. For example, this RULE would be ill scoped:

     {-# RULES "h2" forall b. forall (t :: (b, c)) (g :: forall a. a -> b).
                    h2 t g = ... #-}

   This is because `b` and `c` occur free in the signature for `t`, but only
   `b` was explicitly bound, leaving `c` out of scope. If the RULE had started
   with `forall b c.`, then it would have been accepted.

The types in pattern signatures and RULE term binder signatures are represented
in the AST by HsSigPatType. From the renamer onward, the hsps_ext field (of
type HsPSRn) tracks the names of named wildcards and implicitly bound type
variables so that they can be brought into scope during renaming and
typechecking.
588
589
-}

590
mkHsImplicitBndrs :: thing -> HsImplicitBndrs GhcPs thing
591
mkHsImplicitBndrs x = HsIB { hsib_ext  = noExtField
592
                           , hsib_body = x }
593

594
mkHsWildCardBndrs :: thing -> HsWildCardBndrs GhcPs thing
595
mkHsWildCardBndrs x = HsWC { hswc_body = x
596
                           , hswc_ext  = noExtField }
597

598
599
600
601
mkHsPatSigType :: LHsType GhcPs -> HsPatSigType GhcPs
mkHsPatSigType x = HsPS { hsps_ext  = noExtField
                        , hsps_body = x }

602
603
-- Add empty binders.  This is a bit suspicious; what if
-- the wrapped thing had free type variables?
604
mkEmptyImplicitBndrs :: thing -> HsImplicitBndrs GhcRn thing
605
mkEmptyImplicitBndrs x = HsIB { hsib_ext = []
606
                              , hsib_body = x }
607

608
mkEmptyWildCardBndrs :: thing -> HsWildCardBndrs GhcRn thing
609
mkEmptyWildCardBndrs x = HsWC { hswc_body = x
610
                              , hswc_ext  = [] }
611

612

613
--------------------------------------------------
Mateusz Kowalczyk's avatar
Typo    
Mateusz Kowalczyk committed
614
-- | These names are used early on to store the names of implicit
615
-- parameters.  They completely disappear after type-checking.
Jan Stolarek's avatar
Jan Stolarek committed
616
newtype HsIPName = HsIPName FastString
617
  deriving( Eq, Data )
618
619
620
621
622
623
624
625
626
627
628
629

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

630
--------------------------------------------------
631
632

-- | Haskell Type Variable Binder
Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
633
634
635
636
-- The flag annotates the binder. It is 'Specificity' in places where
-- explicit specificity is allowed (e.g. x :: forall {a} b. ...) or
-- '()' in other places.
data HsTyVarBndr flag pass
637
  = UserTyVar        -- no explicit kinding
638
         (XUserTyVar pass)
Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
639
         flag
640
         (Located (IdP pass))
Sylvain Henry's avatar
Sylvain Henry committed
641
        -- See Note [Located RdrNames] in GHC.Hs.Expr
Simon Peyton Jones's avatar
Simon Peyton Jones committed
642

643
  | KindedTyVar
644
         (XKindedTyVar pass)
Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
645
         flag
646
647
         (Located (IdP pass))
         (LHsKind pass)  -- The user-supplied kind signature
Alan Zimmerman's avatar
Alan Zimmerman committed
648
649
650
        -- ^
        --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
        --          'ApiAnnotation.AnnDcolon', 'ApiAnnotation.AnnClose'
651

Sylvain Henry's avatar
Sylvain Henry committed
652
        -- For details on above see note [Api annotations] in GHC.Parser.Annotation
653
654

  | XTyVarBndr
Ryan Scott's avatar
Ryan Scott committed
655
      !(XXTyVarBndr pass)
656

657
658
type instance XUserTyVar    (GhcPass _) = NoExtField
type instance XKindedTyVar  (GhcPass _) = NoExtField
659

660
type instance XXTyVarBndr   (GhcPass _) = NoExtCon
661

Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
662
663
664
665
666
667
668
669
670
671
672
-- | Return the attached flag
hsTyVarBndrFlag :: HsTyVarBndr flag (GhcPass pass) -> flag
hsTyVarBndrFlag (UserTyVar _ fl _)     = fl
hsTyVarBndrFlag (KindedTyVar _ fl _ _) = fl

-- | Set the attached flag
setHsTyVarBndrFlag :: flag -> HsTyVarBndr flag' (GhcPass pass)
  -> HsTyVarBndr flag (GhcPass pass)
setHsTyVarBndrFlag f (UserTyVar x _ l)     = UserTyVar x f l
setHsTyVarBndrFlag f (KindedTyVar x _ l k) = KindedTyVar x f l k

673
-- | Does this 'HsTyVarBndr' come with an explicit kind annotation?
Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
674
isHsKindedTyVar :: HsTyVarBndr flag pass -> Bool
675
676
isHsKindedTyVar (UserTyVar {})   = False
isHsKindedTyVar (KindedTyVar {}) = True
677
isHsKindedTyVar (XTyVarBndr {})  = False
678

679
-- | Do all type variables in this 'LHsQTyVars' come with kind annotations?
680
hsTvbAllKinded :: LHsQTyVars pass -> Bool
681
hsTvbAllKinded = all (isHsKindedTyVar . unLoc) . hsQTvExplicit
682

Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
683
684
685
686
instance NamedThing (HsTyVarBndr flag GhcRn) where
  getName (UserTyVar _ _ v) = unLoc v
  getName (KindedTyVar _ _ v _) = unLoc v

687
-- | Haskell Type
688
data HsType pass
689
  = HsForAllTy   -- See Note [HsType binders]
Ryan Scott's avatar
Ryan Scott committed
690
      { hst_xforall :: XForAllTy pass
691
      , hst_tele    :: HsForAllTelescope pass
Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
692
693
                                     -- Explicit, user-supplied 'forall a {b} c'
      , hst_body    :: LHsType pass  -- body type
694
      }
Alan Zimmerman's avatar
Alan Zimmerman committed
695
696
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnForall',
      --         'ApiAnnotation.AnnDot','ApiAnnotation.AnnDarrow'
Sylvain Henry's avatar
Sylvain Henry committed
697
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
698

699
  | HsQualTy   -- See Note [HsType binders]
700
701
702
      { hst_xqual :: XQualTy pass
      , hst_ctxt  :: LHsContext pass       -- Context C => blah
      , hst_body  :: LHsType pass }
703

704
705
706
707
  | HsTyVar  (XTyVar pass)
              PromotionFlag    -- Whether explicitly promoted,
                               -- for the pretty printer
             (Located (IdP pass))
708
709
                  -- Type variable, type constructor, or data constructor
                  -- see Note [Promotions (HsTyVar)]
Sylvain Henry's avatar
Sylvain Henry committed
710
                  -- See Note [Located RdrNames] in GHC.Hs.Expr
Alan Zimmerman's avatar
Alan Zimmerman committed
711
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None
712

Sylvain Henry's avatar
Sylvain Henry committed
713
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
714

715
716
  | HsAppTy             (XAppTy pass)
                        (LHsType pass)
717
                        (LHsType pass)
Alan Zimmerman's avatar
Alan Zimmerman committed
718
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None
719

Sylvain Henry's avatar
Sylvain Henry committed
720
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
721

My Nguyen's avatar
My Nguyen committed
722
723
724
725
  | HsAppKindTy         (XAppKindTy pass) -- type level type app
                        (LHsType pass)
                        (LHsKind pass)

726
  | HsFunTy             (XFunTy pass)
Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
727
                        (HsArrow pass)
728
                        (LHsType pass)   -- function type
729
                        (LHsType pass)
730
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow',
731

Sylvain Henry's avatar
Sylvain Henry committed
732
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
733

734
735
  | HsListTy            (XListTy pass)
                        (LHsType pass)  -- Element type
Alan Zimmerman's avatar
Alan Zimmerman committed
736
737
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
      --         'ApiAnnotation.AnnClose' @']'@
738

Sylvain Henry's avatar
Sylvain Henry committed
739
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
740

741
742
  | HsTupleTy           (XTupleTy pass)
                        HsTupleSort
743
                        [LHsType pass]  -- Element types (length gives arity)
Alan Zimmerman's avatar
Alan Zimmerman committed
744
745
    -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(' or '(#'@,
    --         'ApiAnnotation.AnnClose' @')' or '#)'@
746

Sylvain Henry's avatar
Sylvain Henry committed
747
    -- For details on above see note [Api annotations] in GHC.Parser.Annotation
748

749
750
  | HsSumTy             (XSumTy pass)
                        [LHsType pass]  -- Element types (length gives arity)
751
752
753
    -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(#'@,
    --         'ApiAnnotation.AnnClose' '#)'@

Sylvain Henry's avatar
Sylvain Henry committed
754
    -- For details on above see note [Api annotations] in GHC.Parser.Annotation
755

756
757
  | HsOpTy              (XOpTy pass)
                        (LHsType pass) (Located (IdP pass)) (LHsType pass)
Alan Zimmerman's avatar
Alan Zimmerman committed
758
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None
chak's avatar
chak committed
759

Sylvain Henry's avatar
Sylvain Henry committed
760
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
761

762
  | HsParTy             (XParTy pass)
Sylvain Henry's avatar
Sylvain Henry committed
763
                        (LHsType pass)   -- See Note [Parens in HsSyn] in GHC.Hs.Expr
764
        -- Parenthesis preserved for the precedence re-arrangement in
Sylvain Henry's avatar
Sylvain Henry committed
765
        -- GHC.Rename.HsType
Simon Peyton Jones's avatar
Simon Peyton Jones committed
766
        -- It's important that a * (b + c) doesn't get rearranged to (a*b) + c!
Alan Zimmerman's avatar
Alan Zimmerman committed
767
768
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
      --         'ApiAnnotation.AnnClose' @')'@
chak's avatar
chak committed
769

Sylvain Henry's avatar
Sylvain Henry committed
770
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
771

772
773
  | HsIParamTy          (XIParamTy pass)
                        (Located HsIPName) -- (?x :: ty)
774
775
                        (LHsType pass)   -- Implicit parameters as they occur in
                                         -- contexts
Alan Zimmerman's avatar
Alan Zimmerman committed
776
777
778
779
      -- ^
      -- > (?x :: ty)
      --
      -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
batterseapower's avatar
batterseapower committed
780

Sylvain Henry's avatar
Sylvain Henry committed
781
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
782

783
784
785
786
787
  | HsStarTy            (XStarTy pass)
                        Bool             -- Is this the Unicode variant?
                                         -- Note [HsStarTy]
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None

788
789
  | HsKindSig           (XKindSig pass)
                        (LHsType pass)  -- (ty :: kind)
790
                        (LHsKind pass)  -- A type with a kind signature
Alan Zimmerman's avatar
Alan Zimmerman committed
791
792
793
794
795
      -- ^
      -- > (ty :: kind)
      --
      -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
      --         'ApiAnnotation.AnnDcolon','ApiAnnotation.AnnClose' @')'@
796

Sylvain Henry's avatar
Sylvain Henry committed
797
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
798

799
800
  | HsSpliceTy          (XSpliceTy pass)
                        (HsSplice pass)   -- Includes quasi-quotes
Alan Zimmerman's avatar
Alan Zimmerman committed
801
802
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'$('@,
      --         'ApiAnnotation.AnnClose' @')'@
803

Sylvain Henry's avatar
Sylvain Henry committed
804
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
805

806
807
  | HsDocTy             (XDocTy pass)
                        (LHsType pass) LHsDocString -- A documented type
Alan Zimmerman's avatar
Alan Zimmerman committed
808
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None
809

Sylvain Henry's avatar
Sylvain Henry committed
810
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
811

812
813
  | HsBangTy    (XBangTy pass)
                HsSrcBang (LHsType pass)   -- Bang-style type annotations
Alan Zimmerman's avatar
Alan Zimmerman committed
814
815
816
817
818
      -- ^ - 'ApiAnnotation.AnnKeywordId' :
      --         'ApiAnnotation.AnnOpen' @'{-\# UNPACK' or '{-\# NOUNPACK'@,
      --         'ApiAnnotation.AnnClose' @'#-}'@
      --         'ApiAnnotation.AnnBang' @\'!\'@

Sylvain Henry's avatar
Sylvain Henry committed
819
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
820

821
822
  | HsRecTy     (XRecTy pass)
                [LConDeclField pass]    -- Only in data type declarations
Alan Zimmerman's avatar
Alan Zimmerman committed
823
824
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
      --         'ApiAnnotation.AnnClose' @'}'@
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
825

Sylvain Henry's avatar
Sylvain Henry committed
826
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
827

828
829
830
  -- | HsCoreTy (XCoreTy pass) Type -- An escape hatch for tunnelling a *closed*
  --                                -- Core Type through HsSyn.
  --     -- ^ - 'ApiAnnotation.AnnKeywordId' : None
dreixel's avatar
dreixel committed
831

Sylvain Henry's avatar
Sylvain Henry committed
832
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
833

834
  | HsExplicitListTy       -- A promoted explicit list
835
        (XExplicitListTy pass)
836
        PromotionFlag      -- whether explicitly promoted, for pretty printer
837
        [LHsType pass]
Alan Zimmerman's avatar
Alan Zimmerman committed
838
839
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @"'["@,
      --         'ApiAnnotation.AnnClose' @']'@
840

Sylvain Henry's avatar
Sylvain Henry committed
841
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
842

843
  | HsExplicitTupleTy      -- A promoted explicit tuple
844
        (XExplicitTupleTy pass)
845
        [LHsType pass]
Alan Zimmerman's avatar
Alan Zimmerman committed
846
847
      -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @"'("@,
      --         'ApiAnnotation.AnnClose' @')'@
dreixel's avatar
dreixel committed
848

Sylvain Henry's avatar
Sylvain Henry committed
849
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
850

851
  | HsTyLit (XTyLit pass) HsTyLit      -- A promoted numeric literal.
Alan Zimmerman's avatar
Alan Zimmerman committed
852
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None
853

Sylvain Henry's avatar
Sylvain Henry committed
854
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
855

856
  | HsWildCardTy (XWildCardTy pass)  -- A type wildcard
857
      -- See Note [The wildcard story for types]
Alan Zimmerman's avatar
Alan Zimmerman committed
858
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None
859

Sylvain Henry's avatar
Sylvain Henry committed
860
      -- For details on above see note [Api annotations] in GHC.Parser.Annotation
861
862
863
864
865
866
867
868
869
870
871
872
873
874

  -- For adding new constructors via Trees that Grow
  | XHsType
      (XXType pass)

data NewHsTypeX
  = NHsCoreTy Type -- An escape hatch for tunnelling a *closed*
                   -- Core Type through HsSyn.
    deriving Data
      -- ^ - 'ApiAnnotation.AnnKeywordId' : None

instance Outputable NewHsTypeX where
  ppr (NHsCoreTy ty) = ppr ty

875
876
877
878
879
880
881
882
883
884
885
886
887
type instance XForAllTy        (GhcPass _) = NoExtField
type instance XQualTy          (GhcPass _) = NoExtField
type instance XTyVar           (GhcPass _) = NoExtField
type instance XAppTy           (GhcPass _) = NoExtField
type instance XFunTy           (GhcPass _) = NoExtField
type instance XListTy          (GhcPass _) = NoExtField
type instance XTupleTy         (GhcPass _) = NoExtField
type instance XSumTy           (GhcPass _) = NoExtField
type instance XOpTy            (GhcPass _) = NoExtField
type instance XParTy           (GhcPass _) = NoExtField
type instance XIParamTy        (GhcPass _) = NoExtField
type instance XStarTy          (GhcPass _) = NoExtField
type instance XKindSig         (GhcPass _) = NoExtField
888

889
type instance XAppKindTy       (GhcPass _) = SrcSpan -- Where the `@` lives
My Nguyen's avatar
My Nguyen committed
890

891
892
type instance XSpliceTy        GhcPs = NoExtField
type instance XSpliceTy        GhcRn = NoExtField
893
894
type instance XSpliceTy        GhcTc = Kind

895
896
897
type instance XDocTy           (GhcPass _) = NoExtField
type instance XBangTy          (GhcPass _) = NoExtField
type instance XRecTy           (GhcPass _) = NoExtField
898

899
900
type instance XExplicitListTy  GhcPs = NoExtField
type instance XExplicitListTy  GhcRn = NoExtField
901
902
type instance XExplicitListTy  GhcTc = Kind

903
904
type instance XExplicitTupleTy GhcPs = NoExtField
type instance XExplicitTupleTy GhcRn = NoExtField
905
906
type instance XExplicitTupleTy GhcTc = [Kind]

907
type instance XTyLit           (GhcPass _) = NoExtField
908

909
type instance XWildCardTy      (GhcPass _) = NoExtField
910
911
912

type instance XXType         (GhcPass _) = NewHsTypeX

dreixel's avatar
dreixel committed
913

Sylvain Henry's avatar
Sylvain Henry committed
914
-- Note [Literal source text] in GHC.Types.Basic for SourceText fields in
Alan Zimmerman's avatar
Alan Zimmerman committed
915
-- the following
916
-- | Haskell Type Literal
917
data HsTyLit
Alan Zimmerman's avatar
Alan Zimmerman committed
918
919
  = HsNumTy SourceText Integer
  | HsStrTy SourceText FastString
920
    deriving Data
921

Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
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
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
oneDataConHsTy :: HsType GhcRn
oneDataConHsTy = HsTyVar noExtField NotPromoted (noLoc oneDataConName)

manyDataConHsTy :: HsType GhcRn
manyDataConHsTy = HsTyVar noExtField NotPromoted (noLoc manyDataConName)

isUnrestricted :: HsArrow GhcRn -> Bool
isUnrestricted (arrowToHsType -> L _ (HsTyVar _ _ (L _ n))) = n == manyDataConName
isUnrestricted _ = False

-- | Denotes the type of arrows in the surface language
data HsArrow pass
  = HsUnrestrictedArrow
    -- ^ a -> b
  | HsLinearArrow
    -- ^ a #-> b
  | HsExplicitMult (LHsType pass)
    -- ^ a # m -> b (very much including `a # Many -> b`! This is how the
    -- programmer wrote it). It is stored as an `HsType` so as to preserve the
    -- syntax as written in the program.

-- | Convert an arrow into its corresponding multiplicity. In essence this
-- erases the information of whether the programmer wrote an explicit
-- multiplicity or a shorthand.
arrowToHsType :: HsArrow GhcRn -> LHsType GhcRn
arrowToHsType HsUnrestrictedArrow = noLoc manyDataConHsTy
arrowToHsType HsLinearArrow = noLoc oneDataConHsTy
arrowToHsType (HsExplicitMult p) = p

-- | This is used in the syntax. In constructor declaration. It must keep the
-- arrow representation.
data HsScaled pass a = HsScaled (HsArrow pass) a

hsMult :: HsScaled pass a -> HsArrow pass
hsMult (HsScaled m _) = m

hsScaledThing :: HsScaled pass a -> a
hsScaledThing (HsScaled _ t) = t

-- | When creating syntax we use the shorthands. It's better for printing, also,
-- the shorthands work trivially at each pass.
hsUnrestricted, hsLinear :: a -> HsScaled pass a
hsUnrestricted = HsScaled HsUnrestrictedArrow
hsLinear = HsScaled HsLinearArrow

instance Outputable a => Outputable (HsScaled pass a) where
   ppr (HsScaled _cnt t) = -- ppr cnt <> ppr t
                          ppr t

instance
      (OutputableBndrId pass) =>
      Outputable (HsArrow (GhcPass pass)) where
  ppr HsUnrestrictedArrow = parens arrow
  ppr HsLinearArrow = parens lollipop
  ppr (HsExplicitMult p) = parens (mulArrow (ppr p))

thomasw's avatar
thomasw committed
978

Austin Seipp's avatar
Austin Seipp committed
979
{-
980
981
982
983
Note [Unit tuples]
~~~~~~~~~~~~~~~~~~
Consider the type
    type instance F Int = ()
Austin Seipp's avatar
Austin Seipp committed
984
985
We want to parse that "()"
    as HsTupleTy HsBoxedOrConstraintTuple [],
986
987
988
989
990
991
992
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
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
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
1008
1009
1010
  The 'Promoted' field in an HsTyVar captures whether the type was promoted in
  the source code by prefixing an apostrophe.

1011
Note [HsStarTy]
1012
~~~~~~~~~~~~~~~
1013
1014
1015
1016
When the StarIsType extension is enabled, we want to treat '*' and its Unicode
variant identically to 'Data.Kind.Type'. Unfortunately, doing so in the parser
would mean that when we pretty-print it back, we don't know whether the user
wrote '*' or 'Type', and lose the parse/ppr roundtrip property.
1017

1018
1