Rep.hs 78.1 KB
Newer Older
1 2 3
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1998
Sylvain Henry's avatar
Sylvain Henry committed
4
\section[GHC.Core.TyCo.Rep]{Type and Coercion - friends' interface}
5 6 7

Note [The Type-related module hierarchy]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sylvain Henry's avatar
Sylvain Henry committed
8 9
  GHC.Core.Class
  GHC.Core.Coercion.Axiom
Sylvain Henry's avatar
Sylvain Henry committed
10 11 12 13 14 15 16 17
  GHC.Core.TyCon           imports GHC.Core.{Class, Coercion.Axiom}
  GHC.Core.TyCo.Rep        imports GHC.Core.{Class, Coercion.Axiom, TyCon}
  GHC.Core.TyCo.Ppr        imports GHC.Core.TyCo.Rep
  GHC.Core.TyCo.FVs        imports GHC.Core.TyCo.Rep
  GHC.Core.TyCo.Subst      imports GHC.Core.TyCo.{Rep, FVs, Ppr}
  GHC.Core.TyCo.Tidy       imports GHC.Core.TyCo.{Rep, FVs}
  GHC.Builtin.Types.Prim   imports GHC.Core.TyCo.Rep ( including mkTyConTy )
  GHC.Core.Coercion        imports GHC.Core.Type
18 19 20
-}

-- We expose the relevant stuff from this module via the Type module
21
{-# OPTIONS_HADDOCK not-home #-}
22
{-# LANGUAGE CPP, MultiWayIf, PatternSynonyms, BangPatterns, DeriveDataTypeable #-}
23

Sylvain Henry's avatar
Sylvain Henry committed
24
module GHC.Core.TyCo.Rep (
25
        TyThing(..), tyThingCategory, pprTyThingCategory, pprShortTyThing,
26 27

        -- * Types
28
        Type(..),
Simon Peyton Jones's avatar
Simon Peyton Jones committed
29

30 31
        TyLit(..),
        KindOrType, Kind,
32
        KnotTied,
33
        PredType, ThetaType,      -- Synonyms
34
        ArgFlag(..), AnonArgFlag(..),
35

Ben Gamari's avatar
Ben Gamari committed
36
        -- * Coercions
Ben Gamari's avatar
Ben Gamari committed
37
        Coercion(..),
Simon Peyton Jones's avatar
Simon Peyton Jones committed
38
        UnivCoProvenance(..),
39
        CoercionHole(..), BlockSubstFlag(..), coHoleCoVar, setCoHoleCoVar,
40
        CoercionN, CoercionR, CoercionP, KindCoercion,
Ningning Xie's avatar
Ningning Xie committed
41
        MCoercion(..), MCoercionR, MCoercionN,
42

Ben Gamari's avatar
Ben Gamari committed
43
        -- * Functions over types
44
        mkTyConTy, mkTyVarTy, mkTyVarTys,
Ningning Xie's avatar
Ningning Xie committed
45
        mkTyCoVarTy, mkTyCoVarTys,
Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
46
        mkFunTy, mkVisFunTy, mkInvisFunTy, mkVisFunTys,
Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
47
        mkForAllTy, mkForAllTys, mkInvisForAllTys,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
48
        mkPiTy, mkPiTys,
Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
49 50 51 52
        mkFunTyMany,
        mkScaledFunTy,
        mkVisFunTyMany, mkVisFunTysMany,
        mkInvisFunTyMany, mkInvisFunTysMany,
53
        mkTyConApp,
54

Ben Gamari's avatar
Ben Gamari committed
55
        -- * Functions over binders
Ningning Xie's avatar
Ningning Xie committed
56 57
        TyCoBinder(..), TyCoVarBinder, TyBinder,
        binderVar, binderVars, binderType, binderArgFlag,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
58
        delBinderVar,
59
        isInvisibleArgFlag, isVisibleArgFlag,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
60
        isInvisibleBinder, isVisibleBinder,
61
        isTyBinder, isNamedBinder,
62

Ben Gamari's avatar
Ben Gamari committed
63
        -- * Functions over coercions
64 65
        pickLR,

66 67 68
        -- ** Analyzing types
        TyCoFolder(..), foldTyCo,

69
        -- * Sizes
70 71 72 73
        typeSize, coercionSize, provSize,

        -- * Multiplicities
        Scaled(..), scaledMult, scaledThing, mapScaledType, Mult
74 75 76 77
    ) where

#include "HsVersions.h"

78
import GHC.Prelude
79

Sylvain Henry's avatar
Sylvain Henry committed
80
import {-# SOURCE #-} GHC.Core.TyCo.Ppr ( pprType, pprCo, pprTyLit )
Ben Gamari's avatar
Ben Gamari committed
81

82 83
   -- Transitively pulls in a LOT of stuff, better to break the loop

Sylvain Henry's avatar
Sylvain Henry committed
84
import {-# SOURCE #-} GHC.Core.ConLike ( ConLike(..), conLikeName )
85 86

-- friends:
87
import GHC.Iface.Type
Sylvain Henry's avatar
Sylvain Henry committed
88 89 90
import GHC.Types.Var
import GHC.Types.Var.Set
import GHC.Types.Name hiding ( varName )
Sylvain Henry's avatar
Sylvain Henry committed
91 92
import GHC.Core.TyCon
import GHC.Core.Coercion.Axiom
93 94

-- others
95 96
import GHC.Builtin.Names ( liftedTypeKindTyConKey, manyDataConKey )
import {-# SOURCE #-} GHC.Builtin.Types ( liftedTypeKindTyCon, manyDataConTy )
Sylvain Henry's avatar
Sylvain Henry committed
97
import GHC.Types.Basic ( LeftOrRight(..), pickLR )
98
import GHC.Types.Unique ( hasKey )
99 100 101
import GHC.Utils.Outputable
import GHC.Data.FastString
import GHC.Utils.Misc
102
import GHC.Utils.Panic
103 104 105 106 107

-- libraries
import qualified Data.Data as Data hiding ( TyCon )
import Data.IORef ( IORef )   -- for CoercionHole

108 109 110 111 112 113 114 115 116
{-
%************************************************************************
%*                                                                      *
                        TyThing
%*                                                                      *
%************************************************************************

Despite the fact that DataCon has to be imported via a hi-boot route,
this module seems the right place for TyThing, because it's needed for
Sylvain Henry's avatar
Sylvain Henry committed
117
funTyCon and all the types in GHC.Builtin.Types.Prim.
118

119
It is also SOURCE-imported into "GHC.Types.Name"
120 121 122 123 124 125 126 127 128 129 130 131 132


Note [ATyCon for classes]
~~~~~~~~~~~~~~~~~~~~~~~~~
Both classes and type constructors are represented in the type environment
as ATyCon.  You can tell the difference, and get to the class, with
   isClassTyCon :: TyCon -> Bool
   tyConClass_maybe :: TyCon -> Maybe Class
The Class and its associated TyCon have the same Name.
-}

-- | A global typecheckable-thing, essentially anything that has a name.
-- Not to be confused with a 'TcTyThing', which is also a typecheckable
133
-- thing but in the *local* context.  See "GHC.Tc.Utils.Env" for how to retrieve
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
-- a 'TyThing' given a 'Name'.
data TyThing
  = AnId     Id
  | AConLike ConLike
  | ATyCon   TyCon       -- TyCons and classes; see Note [ATyCon for classes]
  | ACoAxiom (CoAxiom Branched)

instance Outputable TyThing where
  ppr = pprShortTyThing

instance NamedThing TyThing where       -- Can't put this with the type
  getName (AnId id)     = getName id    -- decl, because the DataCon instance
  getName (ATyCon tc)   = getName tc    -- isn't visible there
  getName (ACoAxiom cc) = getName cc
  getName (AConLike cl) = conLikeName cl

pprShortTyThing :: TyThing -> SDoc
Sylvain Henry's avatar
Sylvain Henry committed
151
-- c.f. GHC.Core.Ppr.TyThing.pprTyThing, which prints all the details
152 153 154 155
pprShortTyThing thing
  = pprTyThingCategory thing <+> quotes (ppr (getName thing))

pprTyThingCategory :: TyThing -> SDoc
156 157 158 159 160 161 162 163 164 165
pprTyThingCategory = text . capitalise . tyThingCategory

tyThingCategory :: TyThing -> String
tyThingCategory (ATyCon tc)
  | isClassTyCon tc = "class"
  | otherwise       = "type constructor"
tyThingCategory (ACoAxiom _) = "coercion axiom"
tyThingCategory (AnId   _)   = "identifier"
tyThingCategory (AConLike (RealDataCon _)) = "data constructor"
tyThingCategory (AConLike (PatSynCon _))  = "pattern synonym"
166 167


168 169 170 171 172
{- **********************************************************************
*                                                                       *
                        Type
*                                                                       *
********************************************************************** -}
173 174 175

-- | The key representation of types within the compiler

176 177 178 179 180
type KindOrType = Type -- See Note [Arguments to type constructors]

-- | The key type representing kinds in the compiler.
type Kind = Type

181
-- If you edit this type, you may need to update the GHC formalism
Sylvain Henry's avatar
Sylvain Henry committed
182
-- See Note [GHC Formalism] in GHC.Core.Lint
183 184 185 186
data Type
  -- See Note [Non-trivial definitional equality]
  = TyVarTy Var -- ^ Vanilla type or kind variable (*never* a coercion variable)

187
  | AppTy
188 189 190
        Type
        Type            -- ^ Type application to something other than a 'TyCon'. Parameters:
                        --
191
                        --  1) Function: must /not/ be a 'TyConApp' or 'CastTy',
192
                        --     must be another 'AppTy', or 'TyVarTy'
193
                        --     See Note [Respecting definitional equality] \(EQ1) about the
194
                        --     no 'CastTy' requirement
195 196 197
                        --
                        --  2) Argument type

198
  | TyConApp
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
        TyCon
        [KindOrType]    -- ^ Application of a 'TyCon', including newtypes /and/ synonyms.
                        -- Invariant: saturated applications of 'FunTyCon' must
                        -- use 'FunTy' and saturated synonyms must use their own
                        -- constructors. However, /unsaturated/ 'FunTyCon's
                        -- do appear as 'TyConApp's.
                        -- Parameters:
                        --
                        -- 1) Type constructor being applied to.
                        --
                        -- 2) Type arguments. Might not have enough type arguments
                        --    here to saturate the constructor.
                        --    Even type synonyms are not necessarily saturated;
                        --    for example unsaturated type synonyms
                        --    can appear as the right hand side of a type synonym.

  | ForAllTy
Ningning Xie's avatar
Ningning Xie committed
216
        {-# UNPACK #-} !TyCoVarBinder
217
        Type            -- ^ A Π type.
218 219 220
             -- INVARIANT: If the binder is a coercion variable, it must
             -- be mentioned in the Type. See
             -- Note [Unused coercion variable in ForAllTy]
221

Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
222
  | FunTy      -- ^ FUN m t1 t2   Very common, so an important special case
Simon Peyton Jones's avatar
Simon Peyton Jones committed
223
                -- See Note [Function types]
Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
224 225
     { ft_af  :: AnonArgFlag    -- Is this (->) or (=>)?
     , ft_mult :: Mult          -- Multiplicity
Simon Peyton Jones's avatar
Simon Peyton Jones committed
226 227
     , ft_arg :: Type           -- Argument type
     , ft_res :: Type }         -- Result type
Simon Peyton Jones's avatar
Simon Peyton Jones committed
228

229 230 231 232
  | LitTy TyLit     -- ^ Type literals are similar to type constructors.

  | CastTy
        Type
233
        KindCoercion  -- ^ A kind cast. The coercion is always nominal.
234
                      -- INVARIANT: The cast is never reflexive
235
                      -- INVARIANT: The Type is not a CastTy (use TransCo instead)
236
                      -- INVARIANT: The Type is not a ForAllTy over a type variable
237
                      -- See Note [Respecting definitional equality] \(EQ2), (EQ3), (EQ4)
238 239 240 241 242 243 244

  | CoercionTy
        Coercion    -- ^ Injection of a Coercion into a type
                    -- This should only ever be used in the RHS of an AppTy,
                    -- in the list of a TyConApp, when applying a promoted
                    -- GADT data constructor

245
  deriving Data.Data
246

Ben Gamari's avatar
Ben Gamari committed
247 248 249
instance Outputable Type where
  ppr = pprType

250 251 252 253 254
-- NOTE:  Other parts of the code assume that type literals do not contain
-- types or type variables.
data TyLit
  = NumTyLit Integer
  | StrTyLit FastString
255 256 257 258 259 260 261
  deriving (Eq, Data.Data)

instance Ord TyLit where
   compare (NumTyLit _) (StrTyLit _) = LT
   compare (StrTyLit _) (NumTyLit _) = GT
   compare (NumTyLit x) (NumTyLit y) = compare x y
   compare (StrTyLit x) (StrTyLit y) = uniqCompareFS x y
262

Ben Gamari's avatar
Ben Gamari committed
263 264
instance Outputable TyLit where
   ppr = pprTyLit
Simon Peyton Jones's avatar
Simon Peyton Jones committed
265 266 267 268 269 270 271 272 273

{- Note [Function types]
~~~~~~~~~~~~~~~~~~~~~~~~
FFunTy is the constructor for a function type.  Lots of things to say
about it!

* FFunTy is the data constructor, meaning "full function type".

* The function type constructor (->) has kind
274
     (->) :: forall {r1} {r2}. TYPE r1 -> TYPE r2 -> Type LiftedRep
Simon Peyton Jones's avatar
Simon Peyton Jones committed
275 276 277 278 279
  mkTyConApp ensure that we convert a saturated application
    TyConApp (->) [r1,r2,t1,t2] into FunTy t1 t2
  dropping the 'r1' and 'r2' arguments; they are easily recovered
  from 't1' and 't2'.

280 281 282
* For the time being its RuntimeRep quantifiers are left
  inferred. This is to allow for it to evolve.

Simon Peyton Jones's avatar
Simon Peyton Jones committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
* The ft_af field says whether or not this is an invisible argument
     VisArg:   t1 -> t2    Ordinary function type
     InvisArg: t1 => t2    t1 is guaranteed to be a predicate type,
                           i.e. t1 :: Constraint
  See Note [Types for coercions, predicates, and evidence]

  This visibility info makes no difference in Core; it matters
  only when we regard the type as a Haskell source type.

* FunTy is a (unidirectional) pattern synonym that allows
  positional pattern matching (FunTy arg res), ignoring the
  ArgFlag.
-}

{- -----------------------
      Commented out until the pattern match
299
      checker can handle it; see #16185
Simon Peyton Jones's avatar
Simon Peyton Jones committed
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377

      For now we use the CPP macro #define FunTy FFunTy _
      (see HsVersions.h) to allow pattern matching on a
      (positional) FunTy constructor.

{-# COMPLETE FunTy, TyVarTy, AppTy, TyConApp
           , ForAllTy, LitTy, CastTy, CoercionTy :: Type #-}

-- | 'FunTy' is a (uni-directional) pattern synonym for the common
-- case where we want to match on the argument/result type, but
-- ignoring the AnonArgFlag
pattern FunTy :: Type -> Type -> Type
pattern FunTy arg res <- FFunTy { ft_arg = arg, ft_res = res }

       End of commented out block
---------------------------------- -}

{- Note [Types for coercions, predicates, and evidence]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We treat differently:

  (a) Predicate types
        Test: isPredTy
        Binders: DictIds
        Kind: Constraint
        Examples: (Eq a), and (a ~ b)

  (b) Coercion types are primitive, unboxed equalities
        Test: isCoVarTy
        Binders: CoVars (can appear in coercions)
        Kind: TYPE (TupleRep [])
        Examples: (t1 ~# t2) or (t1 ~R# t2)

  (c) Evidence types is the type of evidence manipulated by
      the type constraint solver.
        Test: isEvVarType
        Binders: EvVars
        Kind: Constraint or TYPE (TupleRep [])
        Examples: all coercion types and predicate types

Coercion types and predicate types are mutually exclusive,
but evidence types are a superset of both.

When treated as a user type,

  - Predicates (of kind Constraint) are invisible and are
    implicitly instantiated

  - Coercion types, and non-pred evidence types (i.e. not
    of kind Constrain), are just regular old types, are
    visible, and are not implicitly instantiated.

In a FunTy { ft_af = InvisArg }, the argument type is always
a Predicate type.

Note [Constraints in kinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Do we allow a type constructor to have a kind like
   S :: Eq a => a -> Type

No, we do not.  Doing so would mean would need a TyConApp like
   S @k @(d :: Eq k) (ty :: k)
 and we have no way to build, or decompose, evidence like
 (d :: Eq k) at the type level.

But we admit one exception: equality.  We /do/ allow, say,
   MkT :: (a ~ b) => a -> b -> Type a b

Why?  Because we can, without much difficulty.  Moreover
we can promote a GADT data constructor (see TyCon
Note [Promoted data constructors]), like
  data GT a b where
    MkGT : a -> a -> GT a a
so programmers might reasonably expect to be able to
promote MkT as well.

How does this work?

Sylvain Henry's avatar
Sylvain Henry committed
378
* In GHC.Tc.Validity.checkConstraintsOK we reject kinds that
Simon Peyton Jones's avatar
Simon Peyton Jones committed
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
  have constraints other than (a~b) and (a~~b).

* In Inst.tcInstInvisibleTyBinder we instantiate a call
  of MkT by emitting
     [W] co :: alpha ~# beta
  and producing the elaborated term
     MkT @alpha @beta (Eq# alpha beta co)
  We don't generate a boxed "Wanted"; we generate only a
  regular old /unboxed/ primitive-equality Wanted, and build
  the box on the spot.

* How can we get such a MkT?  By promoting a GADT-style data
  constructor
     data T a b where
       MkT :: (a~b) => a -> b -> T a b
  See DataCon.mkPromotedDataCon
Sylvain Henry's avatar
Sylvain Henry committed
395
  and Note [Promoted data constructors] in GHC.Core.TyCon
Simon Peyton Jones's avatar
Simon Peyton Jones committed
396 397 398

* We support both homogeneous (~) and heterogeneous (~~)
  equality.  (See Note [The equality types story]
Sylvain Henry's avatar
Sylvain Henry committed
399
  in GHC.Builtin.Types.Prim for a primer on these equality types.)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
400 401

* How do we prevent a MkT having an illegal constraint like
Sylvain Henry's avatar
Sylvain Henry committed
402
  Eq a?  We check for this at use-sites; see GHC.Tc.Gen.HsType.tcTyVar,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
  specifically dc_theta_illegal_constraint.

* Notice that nothing special happens if
    K :: (a ~# b) => blah
  because (a ~# b) is not a predicate type, and is never
  implicitly instantiated. (Mind you, it's not clear how you
  could creates a type constructor with such a kind.) See
  Note [Types for coercions, predicates, and evidence]

* The existence of promoted MkT with an equality-constraint
  argument is the (only) reason that the AnonTCB constructor
  of TyConBndrVis carries an AnonArgFlag (VisArg/InvisArg).
  For example, when we promote the data constructor
     MkT :: forall a b. (a~b) => a -> b -> T a b
  we get a PromotedDataCon with tyConBinders
      Bndr (a :: Type)  (NamedTCB Inferred)
      Bndr (b :: Type)  (NamedTCB Inferred)
      Bndr (_ :: a ~ b) (AnonTCB InvisArg)
      Bndr (_ :: a)     (AnonTCB VisArg))
      Bndr (_ :: b)     (AnonTCB VisArg))

* One might reasonably wonder who *unpacks* these boxes once they are
  made. After all, there is no type-level `case` construct. The
  surprising answer is that no one ever does. Instead, if a GADT
  constructor is used on the left-hand side of a type family equation,
  that occurrence forces GHC to unify the types in question. For
  example:

  data G a where
    MkG :: G Bool

  type family F (x :: G a) :: a where
    F MkG = False

  When checking the LHS `F MkG`, GHC sees the MkG constructor and then must
  unify F's implicit parameter `a` with Bool. This succeeds, making the equation

    F Bool (MkG @Bool <Bool>) = False

  Note that we never need unpack the coercion. This is because type
  family equations are *not* parametric in their kind variables. That
  is, we could have just said

  type family H (x :: G a) :: a where
    H _ = False

  The presence of False on the RHS also forces `a` to become Bool,
  giving us

    H Bool _ = False

  The fact that any of this works stems from the lack of phase
  separation between types and kinds (unlike the very present phase
  separation between terms and types).

  Once we have the ability to pattern-match on types below top-level,
  this will no longer cut it, but it seems fine for now.


Note [Arguments to type constructors]
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Because of kind polymorphism, in addition to type application we now
have kind instantiation. We reuse the same notations to do so.

For example:

  Just (* -> *) Maybe
  Right * Nat Zero

are represented by:

  TyConApp (PromotedDataCon Just) [* -> *, Maybe]
  TyConApp (PromotedDataCon Right) [*, Nat, (PromotedDataCon Zero)]

Important note: Nat is used as a *kind* and not as a type. This can be
confusing, since type-level Nat and kind-level Nat are identical. We
use the kind of (PromotedDataCon Right) to know if its arguments are
kinds or types.

This kind instantiation only happens in TyConApp currently.

Note [Non-trivial definitional equality]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Is Int |> <*> the same as Int? YES! In order to reduce headaches,
487 488 489
we decide that any reflexive casts in types are just ignored.
(Indeed they must be. See Note [Respecting definitional equality].)
More generally, the `eqType` function, which defines Core's type equality
490 491 492 493 494
relation, ignores casts and coercion arguments, as long as the
two types have the same kind. This allows us to be a little sloppier
in keeping track of coercions, which is a good thing. It also means
that eqType does not depend on eqCoercion, which is also a good thing.

495 496 497 498 499 500
Why is this sensible? That is, why is something different than α-equivalence
appropriate for the implementation of eqType?

Anything smaller than ~ and homogeneous is an appropriate definition for
equality. The type safety of FC depends only on ~. Let's say η : τ ~ σ. Any
expression of type τ can be transmuted to one of type σ at any point by
Ningning Xie's avatar
Ningning Xie committed
501 502
casting. The same is true of expressions of type σ. So in some sense, τ and σ
are interchangeable.
503 504

But let's be more precise. If we examine the typing rules of FC (say, those in
Ningning Xie's avatar
Ningning Xie committed
505
https://cs.brynmawr.edu/~rae/papers/2015/equalities/equalities.pdf)
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
there are several places where the same metavariable is used in two different
premises to a rule. (For example, see Ty_App.) There is an implicit equality
check here. What definition of equality should we use? By convention, we use
α-equivalence. Take any rule with one (or more) of these implicit equality
checks. Then there is an admissible rule that uses ~ instead of the implicit
check, adding in casts as appropriate.

The only problem here is that ~ is heterogeneous. To make the kinds work out
in the admissible rule that uses ~, it is necessary to homogenize the
coercions. That is, if we have η : (τ : κ1) ~ (σ : κ2), then we don't use η;
we use η |> kind η, which is homogeneous.

The effect of this all is that eqType, the implementation of the implicit
equality check, can use any homogeneous relation that is smaller than ~, as
those rules must also be admissible.

522 523 524
A more drawn out argument around all of this is presented in Section 7.2 of
Richard E's thesis (http://cs.brynmawr.edu/~rae/papers/2016/thesis/eisenberg-thesis.pdf).

525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
What would go wrong if we insisted on the casts matching? See the beginning of
Section 8 in the unpublished paper above. Theoretically, nothing at all goes
wrong. But in practical terms, getting the coercions right proved to be
nightmarish. And types would explode: during kind-checking, we often produce
reflexive kind coercions. When we try to cast by these, mkCastTy just discards
them. But if we used an eqType that distinguished between Int and Int |> <*>,
then we couldn't discard -- the output of kind-checking would be enormous,
and we would need enormous casts with lots of CoherenceCo's to straighten
them out.

Would anything go wrong if eqType respected type families? No, not at all. But
that makes eqType rather hard to implement.

Thus, the guideline for eqType is that it should be the largest
easy-to-implement relation that is still smaller than ~ and homogeneous. The
precise choice of relation is somewhat incidental, as long as the smart
constructors and destructors in Type respect whatever relation is chosen.

Another helpful principle with eqType is this:

545
 (EQ) If (t1 `eqType` t2) then I can replace t1 by t2 anywhere.
546 547 548

This principle also tells us that eqType must relate only types with the
same kinds.
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 588 589 590 591 592

Note [Respecting definitional equality]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Note [Non-trivial definitional equality] introduces the property (EQ).
How is this upheld?

Any function that pattern matches on all the constructors will have to
consider the possibility of CastTy. Presumably, those functions will handle
CastTy appropriately and we'll be OK.

More dangerous are the splitXXX functions. Let's focus on splitTyConApp.
We don't want it to fail on (T a b c |> co). Happily, if we have
  (T a b c |> co) `eqType` (T d e f)
then co must be reflexive. Why? eqType checks that the kinds are equal, as
well as checking that (a `eqType` d), (b `eqType` e), and (c `eqType` f).
By the kind check, we know that (T a b c |> co) and (T d e f) have the same
kind. So the only way that co could be non-reflexive is for (T a b c) to have
a different kind than (T d e f). But because T's kind is closed (all tycon kinds
are closed), the only way for this to happen is that one of the arguments has
to differ, leading to a contradiction. Thus, co is reflexive.

Accordingly, by eliminating reflexive casts, splitTyConApp need not worry
about outermost casts to uphold (EQ). Eliminating reflexive casts is done
in mkCastTy.

Unforunately, that's not the end of the story. Consider comparing
  (T a b c)      =?       (T a b |> (co -> <Type>)) (c |> co)
These two types have the same kind (Type), but the left type is a TyConApp
while the right type is not. To handle this case, we say that the right-hand
type is ill-formed, requiring an AppTy never to have a casted TyConApp
on its left. It is easy enough to pull around the coercions to maintain
this invariant, as done in Type.mkAppTy. In the example above, trying to
form the right-hand type will instead yield (T a b (c |> co |> sym co) |> <Type>).
Both the casts there are reflexive and will be dropped. Huzzah.

This idea of pulling coercions to the right works for splitAppTy as well.

However, there is one hiccup: it's possible that a coercion doesn't relate two
Pi-types. For example, if we have @type family Fun a b where Fun a b = a -> b@,
then we might have (T :: Fun Type Type) and (T |> axFun) Int. That axFun can't
be pulled to the right. But we don't need to pull it: (T |> axFun) Int is not
`eqType` to any proper TyConApp -- thus, leaving it where it is doesn't violate
our (EQ) property.

593
In order to detect reflexive casts reliably, we must make sure not
594 595
to have nested casts: we update (t |> co1 |> co2) to (t |> (co1 `TransCo` co2)).

596 597 598 599 600 601 602 603 604 605
One other troublesome case is ForAllTy. See Note [Weird typing rule for ForAllTy].
The kind of the body is the same as the kind of the ForAllTy. Accordingly,

  ForAllTy tv (ty |> co)     and     (ForAllTy tv ty) |> co

are `eqType`. But only the first can be split by splitForAllTy. So we forbid
the second form, instead pushing the coercion inside to get the first form.
This is done in mkCastTy.

In sum, in order to uphold (EQ), we need the following invariants:
606 607 608 609 610 611

  (EQ1) No decomposable CastTy to the left of an AppTy, where a decomposable
        cast is one that relates either a FunTy to a FunTy or a
        ForAllTy to a ForAllTy.
  (EQ2) No reflexive casts in CastTy.
  (EQ3) No nested CastTys.
Ningning Xie's avatar
Ningning Xie committed
612
  (EQ4) No CastTy over (ForAllTy (Bndr tyvar vis) body).
613
        See Note [Weird typing rule for ForAllTy]
614 615 616

These invariants are all documented above, in the declaration for Type.

Ningning Xie's avatar
Ningning Xie committed
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
Note [Unused coercion variable in ForAllTy]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have
  \(co:t1 ~ t2). e

What type should we give to this expression?
  (1) forall (co:t1 ~ t2) -> t
  (2) (t1 ~ t2) -> t

If co is used in t, (1) should be the right choice.
if co is not used in t, we would like to have (1) and (2) equivalent.

However, we want to keep eqType simple and don't want eqType (1) (2) to return
True in any case.

We decide to always construct (2) if co is not used in t.

Simon Peyton Jones's avatar
Simon Peyton Jones committed
634 635 636 637 638 639 640
Thus in mkLamType, we check whether the variable is a coercion
variable (of type (t1 ~# t2), and whether it is un-used in the
body. If so, it returns a FunTy instead of a ForAllTy.

There are cases we want to skip the check. For example, the check is
unnecessary when it is known from the context that the input variable
is a type variable.  In those cases, we use mkForAllTy.
Ningning Xie's avatar
Ningning Xie committed
641

642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
Note [Weird typing rule for ForAllTy]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Here is the (truncated) typing rule for the dependent ForAllTy:

  inner : TYPE r
  tyvar is not free in r
  ----------------------------------------
  ForAllTy (Bndr tyvar vis) inner : TYPE r

Note that the kind of `inner` is the kind of the overall ForAllTy. This is
necessary because every ForAllTy over a type variable is erased at runtime.
Thus the runtime representation of a ForAllTy (as encoded, via TYPE rep, in
the kind) must be the same as the representation of the body. We must check
for skolem-escape, though. The skolem-escape would prevent a definition like

  undefined :: forall (r :: RuntimeRep) (a :: TYPE r). a

because the type's kind (TYPE r) mentions the out-of-scope r. Luckily, the real
type of undefined is

  undefined :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => a

and that HasCallStack constraint neatly sidesteps the potential skolem-escape
problem.

If the bound variable is a coercion variable:

  inner : TYPE r
  covar is free in inner
  ------------------------------------
  ForAllTy (Bndr covar vis) inner : Type

Here, the kind of the ForAllTy is just Type, because coercion abstractions
are *not* erased. The "covar is free in inner" premise is solely to maintain
the representation invariant documented in
Note [Unused coercion variable in ForAllTy]. Though there is surface similarity
between this free-var check and the one in the tyvar rule, these two restrictions
are truly unrelated.

681
-}
682

683 684
-- | A type labeled 'KnotTied' might have knot-tied tycons in it. See
-- Note [Type checking recursive type and class declarations] in
685
-- "GHC.Tc.TyCl"
686 687
type KnotTied ty = ty

688 689
{- **********************************************************************
*                                                                       *
Ningning Xie's avatar
Ningning Xie committed
690
                  TyCoBinder and ArgFlag
691 692
*                                                                       *
********************************************************************** -}
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
693

Ningning Xie's avatar
Ningning Xie committed
694 695 696 697
-- | A 'TyCoBinder' represents an argument to a function. TyCoBinders can be
-- dependent ('Named') or nondependent ('Anon'). They may also be visible or
-- not. See Note [TyCoBinders]
data TyCoBinder
Simon Peyton Jones's avatar
Simon Peyton Jones committed
698
  = Named TyCoVarBinder    -- A type-lambda binder
Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
699 700
  | Anon AnonArgFlag (Scaled Type)  -- A term-lambda binder. Type here can be CoercionTy.
                                    -- Visibility is determined by the AnonArgFlag
Simon Peyton Jones's avatar
Simon Peyton Jones committed
701 702
  deriving Data.Data

Ben Gamari's avatar
Ben Gamari committed
703 704 705
instance Outputable TyCoBinder where
  ppr (Anon af ty) = ppr af <+> ppr ty
  ppr (Named (Bndr v Required))  = ppr v
Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
706 707 708 709
  -- See Note [Explicit Case Statement for Specificity]
  ppr (Named (Bndr v (Invisible spec))) = case spec of
    SpecifiedSpec -> char '@' <> ppr v
    InferredSpec  -> braces (ppr v)
Ben Gamari's avatar
Ben Gamari committed
710 711


Ningning Xie's avatar
Ningning Xie committed
712 713 714 715
-- | 'TyBinder' is like 'TyCoBinder', but there can only be 'TyVarBinder'
-- in the 'Named' field.
type TyBinder = TyCoBinder

Simon Peyton Jones's avatar
Simon Peyton Jones committed
716 717
-- | Remove the binder's variable from the set, if the binder has
-- a variable.
Ningning Xie's avatar
Ningning Xie committed
718 719
delBinderVar :: VarSet -> TyCoVarBinder -> VarSet
delBinderVar vars (Bndr tv _) = vars `delVarSet` tv
Simon Peyton Jones's avatar
Simon Peyton Jones committed
720 721

-- | Does this binder bind an invisible argument?
Ningning Xie's avatar
Ningning Xie committed
722 723
isInvisibleBinder :: TyCoBinder -> Bool
isInvisibleBinder (Named (Bndr _ vis)) = isInvisibleArgFlag vis
Simon Peyton Jones's avatar
Simon Peyton Jones committed
724 725
isInvisibleBinder (Anon InvisArg _)    = True
isInvisibleBinder (Anon VisArg   _)    = False
Simon Peyton Jones's avatar
Simon Peyton Jones committed
726 727

-- | Does this binder bind a visible argument?
Ningning Xie's avatar
Ningning Xie committed
728
isVisibleBinder :: TyCoBinder -> Bool
Simon Peyton Jones's avatar
Simon Peyton Jones committed
729 730
isVisibleBinder = not . isInvisibleBinder

731 732 733 734
isNamedBinder :: TyCoBinder -> Bool
isNamedBinder (Named {}) = True
isNamedBinder (Anon {})  = False

Ningning Xie's avatar
Ningning Xie committed
735 736
-- | If its a named binder, is the binder a tyvar?
-- Returns True for nondependent binder.
737 738 739
-- This check that we're really returning a *Ty*Binder (as opposed to a
-- coercion binder). That way, if/when we allow coercion quantification
-- in more places, we'll know we missed updating some function.
Ningning Xie's avatar
Ningning Xie committed
740 741 742
isTyBinder :: TyCoBinder -> Bool
isTyBinder (Named bnd) = isTyVarBinder bnd
isTyBinder _ = True
Simon Peyton Jones's avatar
Simon Peyton Jones committed
743

Ningning Xie's avatar
Ningning Xie committed
744
{- Note [TyCoBinders]
745
~~~~~~~~~~~~~~~~~~~
Ningning Xie's avatar
Ningning Xie committed
746 747
A ForAllTy contains a TyCoVarBinder.  But a type can be decomposed
to a telescope consisting of a [TyCoBinder]
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
748

Ningning Xie's avatar
Ningning Xie committed
749
A TyCoBinder represents the type of binders -- that is, the type of an
750 751
argument to a Pi-type. GHC Core currently supports two different
Pi-types:
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
752

753
 * A non-dependent function type,
754
   written with ->, e.g. ty1 -> ty2
Ben Gamari's avatar
Ben Gamari committed
755 756
   represented as FunTy ty1 ty2. These are
   lifted to Coercions with the corresponding FunCo.
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
757

758 759
 * A dependent compile-time-only polytype,
   written with forall, e.g.  forall (a:*). ty
Tobias Dammers's avatar
Tobias Dammers committed
760
   represented as ForAllTy (Bndr a v) ty
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
761

762 763
Both Pi-types classify terms/types that take an argument. In other
words, if `x` is either a function or a polytype, `x arg` makes sense
764
(for an appropriate `arg`).
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
765 766


Ningning Xie's avatar
Ningning Xie committed
767
Note [VarBndrs, TyCoVarBinders, TyConBinders, and visibility]
768
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Ningning Xie's avatar
Ningning Xie committed
769 770 771
* A ForAllTy (used for both types and kinds) contains a TyCoVarBinder.
  Each TyCoVarBinder
      Bndr a tvis
772 773 774 775
  is equipped with tvis::ArgFlag, which says whether or not arguments
  for this binder should be visible (explicit) in source Haskell.

* A TyCon contains a list of TyConBinders.  Each TyConBinder
Ningning Xie's avatar
Ningning Xie committed
776
      Bndr a cvis
777 778 779 780
  is equipped with cvis::TyConBndrVis, which says whether or not type
  and kind arguments for this TyCon should be visible (explicit) in
  source Haskell.

781
This table summarises the visibility rules:
782 783
---------------------------------------------------------------------------------------
|                                                      Occurrences look like this
Gabor Greif's avatar
Gabor Greif committed
784
|                             GHC displays type as     in Haskell source code
Ningning Xie's avatar
Ningning Xie committed
785 786
|--------------------------------------------------------------------------------------
| Bndr a tvis :: TyCoVarBinder, in the binder of ForAllTy for a term
787 788
|  tvis :: ArgFlag
|  tvis = Inferred:            f :: forall {a}. type    Arg not allowed:  f
Ningning Xie's avatar
Ningning Xie committed
789
                               f :: forall {co}. type   Arg not allowed:  f
790
|  tvis = Specified:           f :: forall a. type      Arg optional:     f  or  f @Int
Richard Eisenberg's avatar
Richard Eisenberg committed
791
|  tvis = Required:            T :: forall k -> type    Arg required:     T *
Ningning Xie's avatar
Ningning Xie committed
792
|    This last form is illegal in terms: See Note [No Required TyCoBinder in terms]
793
|
Ningning Xie's avatar
Ningning Xie committed
794
| Bndr k cvis :: TyConBinder, in the TyConBinders of a TyCon
795 796 797
|  cvis :: TyConBndrVis
|  cvis = AnonTCB:             T :: kind -> kind        Required:            T *
|  cvis = NamedTCB Inferred:   T :: forall {k}. kind    Arg not allowed:     T
Ningning Xie's avatar
Ningning Xie committed
798
|                              T :: forall {co}. kind   Arg not allowed:     T
799 800 801
|  cvis = NamedTCB Specified:  T :: forall k. kind      Arg not allowed[1]:  T
|  cvis = NamedTCB Required:   T :: forall k -> kind    Required:            T *
---------------------------------------------------------------------------------------
802 803 804 805 806

[1] In types, in the Specified case, it would make sense to allow
    optional kind applications, thus (T @*), but we have not
    yet implemented that

807
---- In term declarations ----
808

809 810 811
* Inferred.  Function defn, with no signature:  f1 x = x
  We infer f1 :: forall {a}. a -> a, with 'a' Inferred
  It's Inferred because it doesn't appear in any
812 813 814 815
  user-written signature for f1

* Specified.  Function defn, with signature (implicit forall):
     f2 :: a -> a; f2 x = x
Ningning Xie's avatar
Ningning Xie committed
816
  So f2 gets the type f2 :: forall a. a -> a, with 'a' Specified
817 818 819 820
  even though 'a' is not bound in the source code by an explicit forall

* Specified.  Function defn, with signature (explicit forall):
     f3 :: forall a. a -> a; f3 x = x
Ningning Xie's avatar
Ningning Xie committed
821
  So f3 gets the type f3 :: forall a. a -> a, with 'a' Specified
822

Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
823 824 825 826 827 828
* Inferred.  Function defn, with signature (explicit forall), marked as inferred:
     f4 :: forall {a}. a -> a; f4 x = x
  So f4 gets the type f4 :: forall {a}. a -> a, with 'a' Inferred
  It's Inferred because the user marked it as such, even though it does appear
  in the user-written signature for f4

829
* Inferred/Specified.  Function signature with inferred kind polymorphism.
Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
830 831
     f5 :: a b -> Int
  So 'f5' gets the type f5 :: forall {k} (a:k->*) (b:k). a b -> Int
832
  Here 'k' is Inferred (it's not mentioned in the type),
833 834 835
  but 'a' and 'b' are Specified.

* Specified.  Function signature with explicit kind polymorphism
Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
836
     f6 :: a (b :: k) -> Int
837
  This time 'k' is Specified, because it is mentioned explicitly,
Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
838
  so we get f6 :: forall (k:*) (a:k->*) (b:k). a b -> Int
839 840

* Similarly pattern synonyms:
841 842
  Inferred - from inferred types (e.g. no pattern type signature)
           - or from inferred kind polymorphism
843

844
---- In type declarations ----
845

846
* Inferred (k)
847 848
     data T1 a b = MkT1 (a b)
  Here T1's kind is  T1 :: forall {k:*}. (k->*) -> k -> *
849
  The kind variable 'k' is Inferred, since it is not mentioned
850

Ningning Xie's avatar
Ningning Xie committed
851
  Note that 'a' and 'b' correspond to /Anon/ TyCoBinders in T1's kind,
852
  and Anon binders don't have a visibility flag. (Or you could think
853
  of Anon having an implicit Required flag.)
854 855 856 857

* Specified (k)
     data T2 (a::k->*) b = MkT (a b)
  Here T's kind is  T :: forall (k:*). (k->*) -> k -> *
Simon Peyton Jones's avatar
Simon Peyton Jones committed
858
  The kind variable 'k' is Specified, since it is mentioned in
859 860
  the signature.

861
* Required (k)
862 863
     data T k (a::k->*) b = MkT (a b)
  Here T's kind is  T :: forall k:* -> (k->*) -> k -> *
864
  The kind is Required, since it bound in a positional way in T's declaration
865 866
  Every use of T must be explicitly applied to a kind

867
* Inferred (k1), Specified (k)
868 869
     data T a b (c :: k) = MkT (a b) (Proxy c)
  Here T's kind is  T :: forall {k1:*} (k:*). (k1->*) -> k1 -> k -> *
Gabor Greif's avatar
Gabor Greif committed
870
  So 'k' is Specified, because it appears explicitly,
871
  but 'k1' is Inferred, because it does not
872

873 874 875 876 877 878 879 880 881 882 883 884 885
Generally, in the list of TyConBinders for a TyCon,

* Inferred arguments always come first
* Specified, Anon and Required can be mixed

e.g.
  data Foo (a :: Type) :: forall b. (a -> b -> Type) -> Type where ...

Here Foo's TyConBinders are
   [Required 'a', Specified 'b', Anon]
and its kind prints as
   Foo :: forall a -> forall b. (a -> b -> Type) -> Type

Sylvain Henry's avatar
Sylvain Henry committed
886
See also Note [Required, Specified, and Inferred for types] in GHC.Tc.TyCl
Tobias Dammers's avatar
Tobias Dammers committed
887

888 889
---- Printing -----

Ryan Scott's avatar
Ryan Scott committed
890
 We print forall types with enough syntax to tell you their visibility
891 892 893 894 895 896
 flag.  But this is not source Haskell, and these types may not all
 be parsable.

 Specified: a list of Specified binders is written between `forall` and `.`:
               const :: forall a b. a -> b -> a

897
 Inferred: like Specified, but every binder is written in braces:
898 899
               f :: forall {k} (a:k). S k a -> Int

900
 Required: binders are put between `forall` and `->`:
901 902 903 904 905
              T :: forall k -> *

---- Other points -----

* In classic Haskell, all named binders (that is, the type variables in
906
  a polymorphic function type f :: forall a. a -> a) have been Inferred.
907

908
* Inferred variables correspond to "generalized" variables from the
909 910
  Visible Type Applications paper (ESOP'16).

Ningning Xie's avatar
Ningning Xie committed
911
Note [No Required TyCoBinder in terms]
912
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
913
We don't allow Required foralls for term variables, including pattern
914 915 916
synonyms and data constructors.  Why?  Because then an application
would need a /compulsory/ type argument (possibly without an "@"?),
thus (f Int); and we don't have concrete syntax for that.
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
917

Ningning Xie's avatar
Ningning Xie committed
918
We could change this decision, but Required, Named TyCoBinders are rare
919
anyway.  (Most are Anons.)
920 921

However the type of a term can (just about) have a required quantifier;
Sylvain Henry's avatar
Sylvain Henry committed
922
see Note [Required quantifiers in the type of a term] in GHC.Tc.Gen.Expr.
923 924
-}

925 926 927 928 929 930 931 932

{- **********************************************************************
*                                                                       *
                        PredType
*                                                                       *
********************************************************************** -}


933
-- | A type of the form @p@ of constraint kind represents a value whose type is
934 935 936
-- the Haskell predicate @p@, where a predicate is what occurs before
-- the @=>@ in a Haskell type.
--
937 938
-- We use 'PredType' as documentation to mark those types that we guarantee to
-- have this kind.
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
--
-- It can be expanded into its representation, but:
--
-- * The type checker must treat it as opaque
--
-- * The rest of the compiler treats it as transparent
--
-- Consider these examples:
--
-- > f :: (Eq a) => a -> Int
-- > g :: (?x :: Int -> Int) => a -> Int
-- > h :: (r\l) => {r} => {l::Int | r}
--
-- Here the @Eq a@ and @?x :: Int -> Int@ and @r\l@ are all called \"predicates\"
type PredType = Type

-- | A collection of 'PredType's
type ThetaType = [PredType]

{-
(We don't support TREX records yet, but the setup is designed
to expand to allow them.)

A Haskell qualified type, such as that for f,g,h above, is
represented using
        * a FunTy for the double arrow
        * with a type of kind Constraint as the function argument

The predicate really does turn into a real extra argument to the
function.  If the argument has type (p :: Constraint) then the predicate p is
represented by evidence of type p.

971

972 973 974 975 976 977
%************************************************************************
%*                                                                      *
            Simple constructors
%*                                                                      *
%************************************************************************

Sylvain Henry's avatar
Sylvain Henry committed
978
These functions are here so that they can be used by GHC.Builtin.Types.Prim,
979 980 981 982 983
which in turn is imported by Type
-}

mkTyVarTy  :: TyVar   -> Type
mkTyVarTy v = ASSERT2( isTyVar v, ppr v <+> dcolon <+> ppr (tyVarKind v) )
Ningning Xie's avatar
Ningning Xie committed
984
              TyVarTy v
985 986 987 988

mkTyVarTys :: [TyVar] -> [Type]
mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy

Ningning Xie's avatar
Ningning Xie committed
989 990 991 992 993 994 995 996 997 998
mkTyCoVarTy :: TyCoVar -> Type
mkTyCoVarTy v
  | isTyVar v
  = TyVarTy v
  | otherwise
  = CoercionTy (CoVarCo v)

mkTyCoVarTys :: [TyCoVar] -> [Type]
mkTyCoVarTys = map mkTyCoVarTy

Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
999 1000
infixr 3 `mkFunTy`, `mkVisFunTy`, `mkInvisFunTy`, `mkVisFunTyMany`,
         `mkInvisFunTyMany`      -- Associates to the right
1001

Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
1002 1003 1004 1005 1006
mkFunTy :: AnonArgFlag -> Mult -> Type -> Type -> Type
mkFunTy af mult arg res = FunTy { ft_af = af
                                , ft_mult = mult
                                , ft_arg = arg
                                , ft_res = res }
1007

Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
1008 1009 1010 1011
mkScaledFunTy :: AnonArgFlag -> Scaled Type -> Type -> Type
mkScaledFunTy af (Scaled mult arg) res = mkFunTy af mult arg res

mkVisFunTy, mkInvisFunTy :: Mult -> Type -> Type -> Type
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1012 1013 1014
mkVisFunTy   = mkFunTy VisArg
mkInvisFunTy = mkFunTy InvisArg

Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
1015
mkFunTyMany :: AnonArgFlag -> Type -> Type -> Type
1016
mkFunTyMany af = mkFunTy af manyDataConTy
Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
1017 1018 1019

-- | Special, common, case: Arrow type with mult Many
mkVisFunTyMany :: Type -> Type -> Type
1020
mkVisFunTyMany = mkVisFunTy manyDataConTy
Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
1021 1022

mkInvisFunTyMany :: Type -> Type -> Type
1023
mkInvisFunTyMany = mkInvisFunTy manyDataConTy
Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
1024

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1025
-- | Make nested arrow types
Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
1026 1027 1028 1029 1030 1031 1032 1033
mkVisFunTys :: [Scaled Type] -> Type -> Type
mkVisFunTys tys ty = foldr (mkScaledFunTy VisArg) ty tys

mkVisFunTysMany :: [Type] -> Type -> Type
mkVisFunTysMany tys ty = foldr mkVisFunTyMany ty tys

mkInvisFunTysMany :: [Type] -> Type -> Type
mkInvisFunTysMany tys ty = foldr mkInvisFunTyMany ty tys
Ningning Xie's avatar
Ningning Xie committed
1034 1035 1036 1037 1038

-- | Like 'mkTyCoForAllTy', but does not check the occurrence of the binder
-- See Note [Unused coercion variable in ForAllTy]
mkForAllTy :: TyCoVar -> ArgFlag -> Type -> Type
mkForAllTy tv vis ty = ForAllTy (Bndr tv vis) ty
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1039

Ningning Xie's avatar
Ningning Xie committed
1040 1041
-- | Wraps foralls over the type using the provided 'TyCoVar's from left to right
mkForAllTys :: [TyCoVarBinder] -> Type -> Type
1042 1043
mkForAllTys tyvars ty = foldr ForAllTy ty tyvars

Gert-Jan Bottu's avatar
Gert-Jan Bottu committed
1044 1045 1046 1047
-- | Wraps foralls over the type using the provided 'InvisTVBinder's from left to right
mkInvisForAllTys :: [InvisTVBinder] -> Type -> Type
mkInvisForAllTys tyvars ty = foldr ForAllTy ty $ tyVarSpecToBinders tyvars

Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
1048 1049
mkPiTy :: TyCoBinder -> Type -> Type
mkPiTy (Anon af ty1) ty2        = mkScaledFunTy af ty1 ty2
Ningning Xie's avatar
Ningning Xie committed
1050 1051 1052
mkPiTy (Named (Bndr tv vis)) ty = mkForAllTy tv vis ty

mkPiTys :: [TyCoBinder] -> Type -> Type
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1053 1054
mkPiTys tbs ty = foldr mkPiTy ty tbs

1055 1056 1057 1058
-- | Create the plain type constructor type which has been applied to no type arguments at all.
mkTyConTy :: TyCon -> Type
mkTyConTy tycon = TyConApp tycon []

1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
-- | A key function: builds a 'TyConApp' or 'FunTy' as appropriate to
-- its arguments.  Applies its arguments to the constructor from left to right.
mkTyConApp :: TyCon -> [Type] -> Type
mkTyConApp tycon tys
  | isFunTyCon tycon
  , [w, _rep1,_rep2,ty1,ty2] <- tys
  -- The FunTyCon (->) is always a visible one
  = FunTy { ft_af = VisArg, ft_mult = w, ft_arg = ty1, ft_res = ty2 }

  -- Note [mkTyConApp and Type]
  | tycon `hasKey` liftedTypeKindTyConKey
  = ASSERT2( null tys, ppr tycon $$ ppr tys )
    liftedTypeKindTyConApp
  | tycon `hasKey` manyDataConKey
  -- There are a lot of occurrences of 'Many' so it's a small optimisation to
  -- avoid reboxing every time `mkTyConApp` is called.
  = ASSERT2( null tys, ppr tycon $$ ppr tys )
    manyDataConTy
  | otherwise
  = TyConApp tycon tys

-- This is a single, global definition of the type `Type`
-- Defined here so it is only allocated once.
-- See Note [mkTyConApp and Type]
liftedTypeKindTyConApp :: Type
liftedTypeKindTyConApp = TyConApp liftedTypeKindTyCon []

{-
Note [mkTyConApp and Type]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Whilst benchmarking it was observed in #17292 that GHC allocated a lot
of `TyConApp` constructors. Upon further inspection a large number of these
TyConApp constructors were all duplicates of `Type` applied to no arguments.

```
(From a sample of 100000 TyConApp closures)
0x45f3523    - 28732 - `Type`
0x420b840702 - 9629  - generic type constructors
0x42055b7e46 - 9596
0x420559b582 - 9511
0x420bb15a1e - 9509
0x420b86c6ba - 9501
0x42055bac1e - 9496
0x45e68fd    - 538 - `TYPE ...`
```

Therefore in `mkTyConApp` we have a special case for `Type` to ensure that
only one `TyConApp 'Type []` closure is allocated during the course of
compilation. In order to avoid a potentially expensive series of checks in
`mkTyConApp` only this egregious case is special cased at the moment.
-}

1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
{-
%************************************************************************
%*                                                                      *
            Coercions
%*                                                                      *
%************************************************************************
-}

-- | A 'Coercion' is concrete evidence of the equality/convertibility
-- of two types.

-- If you edit this type, you may need to update the GHC formalism
Sylvain Henry's avatar
Sylvain Henry committed
1123
-- See Note [GHC Formalism] in GHC.Core.Lint
1124 1125
data Coercion
  -- Each constructor has a "role signature", indicating the way roles are
1126 1127 1128 1129 1130 1131
  -- propagated through coercions.
  --    -  P, N, and R stand for coercions of the given role
  --    -  e stands for a coercion of a specific unknown role
  --           (think "role polymorphism")
  --    -  "e" stands for an explicit role parameter indicating role e.
  --    -   _ stands for a parameter that is not a Role or Coercion.
1132 1133

  -- These ones mirror the shape of types
Ningning Xie's avatar
Ningning Xie committed
1134 1135
  = -- Refl :: _ -> N
    Refl Type  -- See Note [Refl invariant]
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
          -- Invariant: applications of (Refl T) to a bunch of identity coercions
          --            always show up as Refl.
          -- For example  (Refl T) (Refl a) (Refl b) shows up as (Refl (T a b)).

          -- Applications of (Refl T) to some coercions, at least one of
          -- which is NOT the identity, show up as TyConAppCo.
          -- (They may not be fully saturated however.)
          -- ConAppCo coercions (like all coercions other than Refl)
          -- are NEVER the identity.

Ningning Xie's avatar
Ningning Xie committed
1146 1147 1148 1149 1150 1151 1152
          -- Use (GRefl Representational ty MRefl), not (SubCo (Refl ty))

  -- GRefl :: "e" -> _ -> Maybe N -> e
  -- See Note [Generalized reflexive coercion]
  | GRefl Role Type MCoercionN  -- See Note [Refl invariant]
          -- Use (Refl ty), not (GRefl Nominal ty MRefl)
          -- Use (GRefl Representational _ _), not (SubCo (GRefl Nominal _ _))
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162

  -- These ones simply lift the correspondingly-named
  -- Type constructors into Coercions

  -- TyConAppCo :: "e" -> _ -> ?? -> e
  -- See Note [TyConAppCo roles]
  | TyConAppCo Role TyCon [Coercion]    -- lift TyConApp
               -- The TyCon is never a synonym;
               -- we expand synonyms eagerly
               -- But it can be a type function
1163
               -- TyCon is never a saturated (->); use FunCo instead
1164

1165
  | AppCo Coercion CoercionN             -- lift AppTy
eir@cis.upenn.edu's avatar