Type.hs 74.9 KB
Newer Older
Austin Seipp's avatar
Austin Seipp committed
1 2 3 4
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1993-1998

5

Simon Marlow's avatar
Simon Marlow committed
6
This module defines interface types and binders
Austin Seipp's avatar
Austin Seipp committed
7
-}
8

Ben Gamari's avatar
Ben Gamari committed
9
{-# LANGUAGE CPP, FlexibleInstances, BangPatterns #-}
Sylvain Henry's avatar
Sylvain Henry committed
10
{-# LANGUAGE MultiWayIf #-}
11
{-# LANGUAGE TupleSections #-}
12
{-# LANGUAGE LambdaCase #-}
13 14
    -- FlexibleInstances for Binary (DefMethSpec IfaceType)

15
module GHC.Iface.Type (
16
        IfExtName, IfLclName,
17

18
        IfaceType(..), IfacePredType, IfaceKind, IfaceCoercion(..),
Ningning Xie's avatar
Ningning Xie committed
19
        IfaceMCoercion(..),
20
        IfaceUnivCoProv(..),
21
        IfaceTyCon(..), IfaceTyConInfo(..), IfaceTyConSort(..),
22
        IfaceTyLit(..), IfaceAppArgs(..),
23
        IfaceContext, IfaceBndr(..), IfaceOneShot(..), IfaceLamBndr,
24
        IfaceTvBndr, IfaceIdBndr, IfaceTyConBinder,
Ryan Scott's avatar
Ryan Scott committed
25 26
        IfaceForAllBndr, ArgFlag(..), AnonArgFlag(..),
        ForallVisFlag(..), ShowForAllFlag(..),
27
        mkIfaceForAllTvBndr,
28
        mkIfaceTyConKind,
29

30
        ifForAllBndrVar, ifForAllBndrName, ifaceBndrName,
Ningning Xie's avatar
Ningning Xie committed
31
        ifTyConBinderVar, ifTyConBinderName,
32

33
        -- Equality testing
34
        isIfaceLiftedTypeKind,
35

36 37
        -- Conversion from IfaceAppArgs to IfaceTypes/ArgFlags
        appArgsIfaceTypes, appArgsIfaceTypesArgFlags,
38

39
        -- Printing
40 41
        SuppressBndrSig(..),
        UseBndrParens(..),
42
        pprIfaceType, pprParendIfaceType, pprPrecIfaceType,
43
        pprIfaceContext, pprIfaceContextArr,
44
        pprIfaceIdBndr, pprIfaceLamBndr, pprIfaceTvBndr, pprIfaceTyConBinders,
45
        pprIfaceBndrs, pprIfaceAppArgs, pprParendIfaceAppArgs,
46 47
        pprIfaceForAllPart, pprIfaceForAllPartMust, pprIfaceForAll,
        pprIfaceSigmaType, pprIfaceTyLit,
48 49
        pprIfaceCoercion, pprParendIfaceCoercion,
        splitIfaceSigmaTy, pprIfaceTypeApp, pprUserIfaceForAll,
Ben Gamari's avatar
Ben Gamari committed
50
        pprIfaceCoTcApp, pprTyTcApp, pprIfacePrefixApp,
51
        isIfaceTauType,
52

53 54 55
        suppressIfaceInvisibles,
        stripIfaceInvisVars,
        stripInvisArgs,
56

57
        mkIfaceTySubst, substIfaceTyVar, substIfaceAppArgs, inDomIfaceTySubst
58 59
    ) where

60 61
#include "HsVersions.h"

62 63
import GhcPrelude

64
import {-# SOURCE #-} TysWiredIn ( coercibleTyCon, heqTyCon
65
                                 , liftedRepDataConTyCon, tupleTyConName )
66
import {-# SOURCE #-} Type       ( isRuntimeRepTy )
Ben Gamari's avatar
Ben Gamari committed
67

68
import DynFlags
69
import TyCon hiding ( pprPromotionQuote )
70
import CoAxiom
Simon Marlow's avatar
Simon Marlow committed
71
import Var
72
import PrelNames
Simon Marlow's avatar
Simon Marlow committed
73 74
import Name
import BasicTypes
75
import Binary
76 77
import Outputable
import FastString
Ben Gamari's avatar
Ben Gamari committed
78
import FastStringEnv
79
import Util
80

81
import Data.Maybe( isJust )
82
import qualified Data.Semigroup as Semi
83
import Control.DeepSeq
Ben Gamari's avatar
Ben Gamari committed
84

Austin Seipp's avatar
Austin Seipp committed
85 86 87
{-
************************************************************************
*                                                                      *
88
                Local (nested) binders
Austin Seipp's avatar
Austin Seipp committed
89 90 91
*                                                                      *
************************************************************************
-}
92

93
type IfLclName = FastString     -- A local name in iface syntax
94

95
type IfExtName = Name   -- An External or WiredIn Name can appear in Iface syntax
96
                        -- (However Internal or System Names never should)
97

98
data IfaceBndr          -- Local (non-top-level) binders
99 100
  = IfaceIdBndr {-# UNPACK #-} !IfaceIdBndr
  | IfaceTvBndr {-# UNPACK #-} !IfaceTvBndr
101

102 103
type IfaceIdBndr  = (IfLclName, IfaceType)
type IfaceTvBndr  = (IfLclName, IfaceKind)
104

Simon Peyton Jones's avatar
Simon Peyton Jones committed
105 106 107
ifaceTvBndrName :: IfaceTvBndr -> IfLclName
ifaceTvBndrName (n,_) = n

Ningning Xie's avatar
Ningning Xie committed
108 109 110 111 112 113 114
ifaceIdBndrName :: IfaceIdBndr -> IfLclName
ifaceIdBndrName (n,_) = n

ifaceBndrName :: IfaceBndr -> IfLclName
ifaceBndrName (IfaceTvBndr bndr) = ifaceTvBndrName bndr
ifaceBndrName (IfaceIdBndr bndr) = ifaceIdBndrName bndr

115 116 117 118
ifaceBndrType :: IfaceBndr -> IfaceType
ifaceBndrType (IfaceIdBndr (_, t)) = t
ifaceBndrType (IfaceTvBndr (_, t)) = t

Simon Peyton Jones's avatar
Simon Peyton Jones committed
119
type IfaceLamBndr = (IfaceBndr, IfaceOneShot)
120

121 122
data IfaceOneShot    -- See Note [Preserve OneShotInfo] in CoreTicy
  = IfaceNoOneShot   -- and Note [The oneShot function] in MkId
123 124 125
  | IfaceOneShot


126 127 128 129 130 131 132 133
{-
%************************************************************************
%*                                                                      *
                IfaceType
%*                                                                      *
%************************************************************************
-}

134
-------------------------------
135
type IfaceKind     = IfaceType
136

137 138 139
-- | A kind of universal type, used for types and kinds.
--
-- Any time a 'Type' is pretty-printed, it is first converted to an 'IfaceType'
140
-- before being printed. See Note [Pretty printing via Iface syntax] in PprTyThing
141
data IfaceType
142
  = IfaceFreeTyVar TyVar                -- See Note [Free tyvars in IfaceType]
143 144
  | IfaceTyVar     IfLclName            -- Type/coercion variable only, not tycon
  | IfaceLitTy     IfaceTyLit
145 146 147 148
  | IfaceAppTy     IfaceType IfaceAppArgs
                             -- See Note [Suppressing invisible arguments] for
                             -- an explanation of why the second field isn't
                             -- IfaceType, analogous to AppTy.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
149
  | IfaceFunTy     AnonArgFlag IfaceType IfaceType
150
  | IfaceForAllTy  IfaceForAllBndr IfaceType
151 152
  | IfaceTyConApp  IfaceTyCon IfaceAppArgs  -- Not necessarily saturated
                                            -- Includes newtypes, synonyms, tuples
153 154
  | IfaceCastTy     IfaceType IfaceCoercion
  | IfaceCoercionTy IfaceCoercion
Ben Gamari's avatar
Ben Gamari committed
155

156
  | IfaceTupleTy                  -- Saturated tuples (unsaturated ones use IfaceTyConApp)
Ben Gamari's avatar
Ben Gamari committed
157
       TupleSort                  -- What sort of tuple?
158
       PromotionFlag                 -- A bit like IfaceTyCon
159
       IfaceAppArgs               -- arity = length args
160
          -- For promoted data cons, the kind args are omitted
161

batterseapower's avatar
batterseapower committed
162
type IfacePredType = IfaceType
163 164
type IfaceContext = [IfacePredType]

165
data IfaceTyLit
166 167
  = IfaceNumTyLit Integer
  | IfaceStrTyLit FastString
168
  deriving (Eq)
169

Ningning Xie's avatar
Ningning Xie committed
170 171
type IfaceTyConBinder = VarBndr IfaceBndr TyConBndrVis
type IfaceForAllBndr  = VarBndr IfaceBndr ArgFlag
172

173 174 175 176
-- | Make an 'IfaceForAllBndr' from an 'IfaceTvBndr'.
mkIfaceForAllTvBndr :: ArgFlag -> IfaceTvBndr -> IfaceForAllBndr
mkIfaceForAllTvBndr vis var = Bndr (IfaceTvBndr var) vis

177 178 179 180 181 182 183 184 185
-- | Build the 'tyConKind' from the binders and the result kind.
-- Keep in sync with 'mkTyConKind' in types/TyCon.
mkIfaceTyConKind :: [IfaceTyConBinder] -> IfaceKind -> IfaceKind
mkIfaceTyConKind bndrs res_kind = foldr mk res_kind bndrs
  where
    mk :: IfaceTyConBinder -> IfaceKind -> IfaceKind
    mk (Bndr tv (AnonTCB af))   k = IfaceFunTy af (ifaceBndrType tv) k
    mk (Bndr tv (NamedTCB vis)) k = IfaceForAllTy (Bndr tv vis) k

186 187
-- | Stores the arguments in a type application as a list.
-- See @Note [Suppressing invisible arguments]@.
188 189
data IfaceAppArgs
  = IA_Nil
190 191 192 193 194 195 196 197 198 199 200 201 202
  | IA_Arg IfaceType    -- The type argument

           ArgFlag      -- The argument's visibility. We store this here so
                        -- that we can:
                        --
                        -- 1. Avoid pretty-printing invisible (i.e., specified
                        --    or inferred) arguments when
                        --    -fprint-explicit-kinds isn't enabled, or
                        -- 2. When -fprint-explicit-kinds *is*, enabled, print
                        --    specified arguments in @(...) and inferred
                        --    arguments in @{...}.

           IfaceAppArgs -- The rest of the arguments
203

204
instance Semi.Semigroup IfaceAppArgs where
205 206
  IA_Nil <> xs              = xs
  IA_Arg ty argf rest <> xs = IA_Arg ty argf (rest Semi.<> xs)
207

208 209
instance Monoid IfaceAppArgs where
  mempty = IA_Nil
210
  mappend = (Semi.<>)
Ben Gamari's avatar
Ben Gamari committed
211

212 213 214 215
-- Encodes type constructors, kind constructors,
-- coercion constructors, the lot.
-- We have to tag them in order to pretty print them
-- properly.
216 217
data IfaceTyCon = IfaceTyCon { ifaceTyConName :: IfExtName
                             , ifaceTyConInfo :: IfaceTyConInfo }
218
    deriving (Eq)
219

Ben Gamari's avatar
Ben Gamari committed
220 221 222 223 224 225 226 227 228 229 230 231
-- | The various types of TyCons which have special, built-in syntax.
data IfaceTyConSort = IfaceNormalTyCon          -- ^ a regular tycon

                    | IfaceTupleTyCon !Arity !TupleSort
                      -- ^ e.g. @(a, b, c)@ or @(#a, b, c#)@.
                      -- The arity is the tuple width, not the tycon arity
                      -- (which is twice the width in the case of unboxed
                      -- tuples).

                    | IfaceSumTyCon !Arity
                      -- ^ e.g. @(a | b | c)@

232 233 234 235 236 237
                    | IfaceEqualityTyCon
                      -- ^ A heterogeneous equality TyCon
                      --   (i.e. eqPrimTyCon, eqReprPrimTyCon, heqTyCon)
                      -- that is actually being applied to two types
                      -- of the same kind.  This affects pretty-printing
                      -- only: see Note [Equality predicates in IfaceType]
Ben Gamari's avatar
Ben Gamari committed
238 239
                    deriving (Eq)

240
{- Note [Free tyvars in IfaceType]
241
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Simon Peyton Jones's avatar
Simon Peyton Jones committed
242 243
Nowadays (since Nov 16, 2016) we pretty-print a Type by converting to
an IfaceType and pretty printing that.  This eliminates a lot of
244
pretty-print duplication, and it matches what we do with pretty-
245
printing TyThings. See Note [Pretty printing via Iface syntax] in PprTyThing.
246 247 248 249 250 251

It works fine for closed types, but when printing debug traces (e.g.
when using -ddump-tc-trace) we print a lot of /open/ types.  These
types are full of TcTyVars, and it's absolutely crucial to print them
in their full glory, with their unique, TcTyVarDetails etc.

252
So we simply embed a TyVar in IfaceType with the IfaceFreeTyVar constructor.
253 254
Note that:

255 256
* We never expect to serialise an IfaceFreeTyVar into an interface file, nor
  to deserialise one.  IfaceFreeTyVar is used only in the "convert to IfaceType
257 258
  and then pretty-print" pipeline.

259
We do the same for covars, naturally.
260

Ben Gamari's avatar
Ben Gamari committed
261 262 263
Note [Equality predicates in IfaceType]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GHC has several varieties of type equality (see Note [The equality types story]
264
in TysPrim for details).  In an effort to avoid confusing users, we suppress
265 266 267 268 269
the differences during pretty printing unless certain flags are enabled.
Here is how each equality predicate* is printed in homogeneous and
heterogeneous contexts, depending on which combination of the
-fprint-explicit-kinds and -fprint-equality-relations flags is used:

270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
--------------------------------------------------------------------------------------------
|         Predicate             |        Neither flag        |    -fprint-explicit-kinds   |
|-------------------------------|----------------------------|-----------------------------|
| a ~ b         (homogeneous)   |        a ~ b               | (a :: Type) ~  (b :: Type)  |
| a ~~ b,       homogeneously   |        a ~ b               | (a :: Type) ~  (b :: Type)  |
| a ~~ b,       heterogeneously |        a ~~ c              | (a :: Type) ~~ (c :: k)     |
| a ~# b,       homogeneously   |        a ~ b               | (a :: Type) ~  (b :: Type)  |
| a ~# b,       heterogeneously |        a ~~ c              | (a :: Type) ~~ (c :: k)     |
| Coercible a b (homogeneous)   |        Coercible a b       | Coercible @Type a b         |
| a ~R# b,      homogeneously   |        Coercible a b       | Coercible @Type a b         |
| a ~R# b,      heterogeneously |        a ~R# b             | (a :: Type) ~R# (c :: k)    |
|-------------------------------|----------------------------|-----------------------------|
|         Predicate             | -fprint-equality-relations |          Both flags         |
|-------------------------------|----------------------------|-----------------------------|
| a ~ b         (homogeneous)   |        a ~  b              | (a :: Type) ~  (b :: Type)  |
| a ~~ b,       homogeneously   |        a ~~ b              | (a :: Type) ~~ (b :: Type)  |
| a ~~ b,       heterogeneously |        a ~~ c              | (a :: Type) ~~ (c :: k)     |
| a ~# b,       homogeneously   |        a ~# b              | (a :: Type) ~# (b :: Type)  |
| a ~# b,       heterogeneously |        a ~# c              | (a :: Type) ~# (c :: k)     |
| Coercible a b (homogeneous)   |        Coercible a b       | Coercible @Type a b         |
| a ~R# b,      homogeneously   |        a ~R# b             | (a :: Type) ~R# (b :: Type) |
| a ~R# b,      heterogeneously |        a ~R# b             | (a :: Type) ~R# (c :: k)    |
--------------------------------------------------------------------------------------------
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312

(* There is no heterogeneous, representational, lifted equality counterpart
to (~~). There could be, but there seems to be no use for it.)

This table adheres to the following rules:

A. With -fprint-equality-relations, print the true equality relation.
B. Without -fprint-equality-relations:
     i. If the equality is representational and homogeneous, use Coercible.
    ii. Otherwise, if the equality is representational, use ~R#.
   iii. If the equality is nominal and homogeneous, use ~.
    iv. Otherwise, if the equality is nominal, use ~~.
C. With -fprint-explicit-kinds, print kinds on both sides of an infix operator,
   as above; or print the kind with Coercible.
D. Without -fprint-explicit-kinds, don't print kinds.

A hetero-kinded equality is used homogeneously when it is applied to two
identical kinds. Unfortunately, determining this from an IfaceType isn't
possible since we can't see through type synonyms. Consequently, we need to
record whether this particular application is homogeneous in IfaceTyConSort
313 314
for the purposes of pretty-printing.

315
See Note [The equality types story] in TysPrim.
Ben Gamari's avatar
Ben Gamari committed
316 317
-}

318 319
data IfaceTyConInfo   -- Used to guide pretty-printing
                      -- and to disambiguate D from 'D (they share a name)
320
  = IfaceTyConInfo { ifaceTyConIsPromoted :: PromotionFlag
Ben Gamari's avatar
Ben Gamari committed
321
                   , ifaceTyConSort       :: IfaceTyConSort }
322
    deriving (Eq)
323

Ningning Xie's avatar
Ningning Xie committed
324 325 326 327
data IfaceMCoercion
  = IfaceMRefl
  | IfaceMCo IfaceCoercion

328
data IfaceCoercion
Ningning Xie's avatar
Ningning Xie committed
329 330
  = IfaceReflCo       IfaceType
  | IfaceGReflCo      Role IfaceType (IfaceMCoercion)
331 332 333
  | IfaceFunCo        Role IfaceCoercion IfaceCoercion
  | IfaceTyConAppCo   Role IfaceTyCon [IfaceCoercion]
  | IfaceAppCo        IfaceCoercion IfaceCoercion
Ningning Xie's avatar
Ningning Xie committed
334
  | IfaceForAllCo     IfaceBndr IfaceCoercion IfaceCoercion
335 336
  | IfaceCoVarCo      IfLclName
  | IfaceAxiomInstCo  IfExtName BranchIndex [IfaceCoercion]
337 338 339 340
  | IfaceAxiomRuleCo  IfLclName [IfaceCoercion]
       -- There are only a fixed number of CoAxiomRules, so it suffices
       -- to use an IfaceLclName to distinguish them.
       -- See Note [Adding built-in type families] in TcTypeNats
341 342 343 344 345 346 347 348
  | IfaceUnivCo       IfaceUnivCoProv Role IfaceType IfaceType
  | IfaceSymCo        IfaceCoercion
  | IfaceTransCo      IfaceCoercion IfaceCoercion
  | IfaceNthCo        Int IfaceCoercion
  | IfaceLRCo         LeftOrRight IfaceCoercion
  | IfaceInstCo       IfaceCoercion IfaceCoercion
  | IfaceKindCo       IfaceCoercion
  | IfaceSubCo        IfaceCoercion
Simon Peyton Jones's avatar
Simon Peyton Jones committed
349 350
  | IfaceFreeCoVar    CoVar    -- See Note [Free tyvars in IfaceType]
  | IfaceHoleCo       CoVar    -- ^ See Note [Holes in IfaceCoercion]
351 352 353 354 355 356

data IfaceUnivCoProv
  = IfaceUnsafeCoerceProv
  | IfacePhantomProv IfaceCoercion
  | IfaceProofIrrelProv IfaceCoercion
  | IfacePluginProv String
357

Simon Peyton Jones's avatar
Simon Peyton Jones committed
358 359 360 361 362 363 364 365 366 367
{- Note [Holes in IfaceCoercion]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When typechecking fails the typechecker will produce a HoleCo to stand
in place of the unproven assertion. While we generally don't want to
let these unproven assertions leak into interface files, we still need
to be able to pretty-print them as we use IfaceType's pretty-printer
to render Types. For this reason IfaceCoercion has a IfaceHoleCo
constructor; however, we fails when asked to serialize to a
IfaceHoleCo to ensure that they don't end up in an interface file.

368

369 370
%************************************************************************
%*                                                                      *
371
                Functions over IFaceTypes
Austin Seipp's avatar
Austin Seipp committed
372 373 374
*                                                                      *
************************************************************************
-}
375

Ben Gamari's avatar
Ben Gamari committed
376 377 378
ifaceTyConHasKey :: IfaceTyCon -> Unique -> Bool
ifaceTyConHasKey tc key = ifaceTyConName tc `hasKey` key

379
isIfaceLiftedTypeKind :: IfaceKind -> Bool
380
isIfaceLiftedTypeKind (IfaceTyConApp tc IA_Nil)
381 382
  = isLiftedTypeKindTyConName (ifaceTyConName tc)
isIfaceLiftedTypeKind (IfaceTyConApp tc
383 384
                       (IA_Arg (IfaceTyConApp ptr_rep_lifted IA_Nil)
                               Required IA_Nil))
Ben Gamari's avatar
Ben Gamari committed
385
  =  tc `ifaceTyConHasKey` tYPETyConKey
Richard Eisenberg's avatar
Richard Eisenberg committed
386
  && ptr_rep_lifted `ifaceTyConHasKey` liftedRepDataConKey
387 388
isIfaceLiftedTypeKind _ = False

389
splitIfaceSigmaTy :: IfaceType -> ([IfaceForAllBndr], [IfacePredType], IfaceType)
390
-- Mainly for printing purposes
391 392 393 394 395 396 397 398 399 400 401 402
--
-- Here we split nested IfaceSigmaTy properly.
--
-- @
-- forall t. T t => forall m a b. M m => (a -> m b) -> t a -> m (t b)
-- @
--
-- If you called @splitIfaceSigmaTy@ on this type:
--
-- @
-- ([t, m, a, b], [T t, M m], (a -> m b) -> t a -> m (t b))
-- @
403
splitIfaceSigmaTy ty
404 405 406 407
  = case (bndrs, theta) of
      ([], []) -> (bndrs, theta, tau)
      _        -> let (bndrs', theta', tau') = splitIfaceSigmaTy tau
                   in (bndrs ++ bndrs', theta ++ theta', tau')
408
  where
409
    (bndrs, rho)   = split_foralls ty
batterseapower's avatar
batterseapower committed
410
    (theta, tau)   = split_rho rho
411

412 413
    split_foralls (IfaceForAllTy bndr ty)
        = case split_foralls ty of { (bndrs, rho) -> (bndr:bndrs, rho) }
414 415
    split_foralls rho = ([], rho)

Simon Peyton Jones's avatar
Simon Peyton Jones committed
416
    split_rho (IfaceFunTy InvisArg ty1 ty2)
417
        = case split_rho ty2 of { (ps, tau) -> (ty1:ps, tau) }
418
    split_rho tau = ([], tau)
419

420
suppressIfaceInvisibles :: DynFlags -> [IfaceTyConBinder] -> [a] -> [a]
421
suppressIfaceInvisibles dflags tys xs
422 423 424 425 426
  | gopt Opt_PrintExplicitKinds dflags = xs
  | otherwise = suppress tys xs
    where
      suppress _       []      = []
      suppress []      a       = a
427 428 429
      suppress (k:ks) (x:xs)
        | isInvisibleTyConBinder k =     suppress ks xs
        | otherwise                = x : suppress ks xs
430

431
stripIfaceInvisVars :: DynFlags -> [IfaceTyConBinder] -> [IfaceTyConBinder]
432
stripIfaceInvisVars dflags tyvars
433
  | gopt Opt_PrintExplicitKinds dflags = tyvars
434
  | otherwise = filterOut isInvisibleTyConBinder tyvars
435

Ningning Xie's avatar
Ningning Xie committed
436 437 438
-- | Extract an 'IfaceBndr' from an 'IfaceForAllBndr'.
ifForAllBndrVar :: IfaceForAllBndr -> IfaceBndr
ifForAllBndrVar = binderVar
439 440 441

-- | Extract the variable name from an 'IfaceForAllBndr'.
ifForAllBndrName :: IfaceForAllBndr -> IfLclName
Ningning Xie's avatar
Ningning Xie committed
442
ifForAllBndrName fab = ifaceBndrName (ifForAllBndrVar fab)
443

Ningning Xie's avatar
Ningning Xie committed
444 445 446
-- | Extract an 'IfaceBndr' from an 'IfaceTyConBinder'.
ifTyConBinderVar :: IfaceTyConBinder -> IfaceBndr
ifTyConBinderVar = binderVar
447

448
-- | Extract the variable name from an 'IfaceTyConBinder'.
449
ifTyConBinderName :: IfaceTyConBinder -> IfLclName
Ningning Xie's avatar
Ningning Xie committed
450
ifTyConBinderName tcb = ifaceBndrName (ifTyConBinderVar tcb)
451

452 453 454 455
ifTypeIsVarFree :: IfaceType -> Bool
-- Returns True if the type definitely has no variables at all
-- Just used to control pretty printing
ifTypeIsVarFree ty = go ty
456
  where
457
    go (IfaceTyVar {})         = False
458
    go (IfaceFreeTyVar {})     = False
459
    go (IfaceAppTy fun args)   = go fun && go_args args
Simon Peyton Jones's avatar
Simon Peyton Jones committed
460
    go (IfaceFunTy _ arg res)  = go arg && go res
461 462 463 464 465 466 467
    go (IfaceForAllTy {})      = False
    go (IfaceTyConApp _ args)  = go_args args
    go (IfaceTupleTy _ _ args) = go_args args
    go (IfaceLitTy _)          = True
    go (IfaceCastTy {})        = False -- Safe
    go (IfaceCoercionTy {})    = False -- Safe

468
    go_args IA_Nil = True
469
    go_args (IA_Arg arg _ args) = go arg && go_args args
470

471 472 473 474 475
{- Note [Substitution on IfaceType]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Substitutions on IfaceType are done only during pretty-printing to
construct the result type of a GADT, and does not deal with binders
(eg IfaceForAll), so it doesn't need fancy capture stuff.  -}
476

477
type IfaceTySubst = FastStringEnv IfaceType -- Note [Substitution on IfaceType]
478

479 480 481 482 483 484 485
mkIfaceTySubst :: [(IfLclName,IfaceType)] -> IfaceTySubst
-- See Note [Substitution on IfaceType]
mkIfaceTySubst eq_spec = mkFsEnv eq_spec

inDomIfaceTySubst :: IfaceTySubst -> IfaceTvBndr -> Bool
-- See Note [Substitution on IfaceType]
inDomIfaceTySubst subst (fs, _) = isJust (lookupFsEnv subst fs)
486 487

substIfaceType :: IfaceTySubst -> IfaceType -> IfaceType
488
-- See Note [Substitution on IfaceType]
489 490 491
substIfaceType env ty
  = go ty
  where
492
    go (IfaceFreeTyVar tv)    = IfaceFreeTyVar tv
493
    go (IfaceTyVar tv)        = substIfaceTyVar env tv
494
    go (IfaceAppTy  t ts)     = IfaceAppTy  (go t) (substIfaceAppArgs env ts)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
495
    go (IfaceFunTy af t1 t2)  = IfaceFunTy af (go t1) (go t2)
496
    go ty@(IfaceLitTy {})     = ty
497 498
    go (IfaceTyConApp tc tys) = IfaceTyConApp tc (substIfaceAppArgs env tys)
    go (IfaceTupleTy s i tys) = IfaceTupleTy s i (substIfaceAppArgs env tys)
499
    go (IfaceForAllTy {})     = pprPanic "substIfaceType" (ppr ty)
500 501 502
    go (IfaceCastTy ty co)    = IfaceCastTy (go ty) (go_co co)
    go (IfaceCoercionTy co)   = IfaceCoercionTy (go_co co)

Ningning Xie's avatar
Ningning Xie committed
503 504 505 506 507 508
    go_mco IfaceMRefl    = IfaceMRefl
    go_mco (IfaceMCo co) = IfaceMCo $ go_co co

    go_co (IfaceReflCo ty)           = IfaceReflCo (go ty)
    go_co (IfaceGReflCo r ty mco)    = IfaceGReflCo r (go ty) (go_mco mco)
    go_co (IfaceFunCo r c1 c2)       = IfaceFunCo r (go_co c1) (go_co c2)
509 510 511
    go_co (IfaceTyConAppCo r tc cos) = IfaceTyConAppCo r tc (go_cos cos)
    go_co (IfaceAppCo c1 c2)         = IfaceAppCo (go_co c1) (go_co c2)
    go_co (IfaceForAllCo {})         = pprPanic "substIfaceCoercion" (ppr ty)
512
    go_co (IfaceFreeCoVar cv)        = IfaceFreeCoVar cv
513
    go_co (IfaceCoVarCo cv)          = IfaceCoVarCo cv
Simon Peyton Jones's avatar
Simon Peyton Jones committed
514
    go_co (IfaceHoleCo cv)           = IfaceHoleCo cv
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
    go_co (IfaceAxiomInstCo a i cos) = IfaceAxiomInstCo a i (go_cos cos)
    go_co (IfaceUnivCo prov r t1 t2) = IfaceUnivCo (go_prov prov) r (go t1) (go t2)
    go_co (IfaceSymCo co)            = IfaceSymCo (go_co co)
    go_co (IfaceTransCo co1 co2)     = IfaceTransCo (go_co co1) (go_co co2)
    go_co (IfaceNthCo n co)          = IfaceNthCo n (go_co co)
    go_co (IfaceLRCo lr co)          = IfaceLRCo lr (go_co co)
    go_co (IfaceInstCo c1 c2)        = IfaceInstCo (go_co c1) (go_co c2)
    go_co (IfaceKindCo co)           = IfaceKindCo (go_co co)
    go_co (IfaceSubCo co)            = IfaceSubCo (go_co co)
    go_co (IfaceAxiomRuleCo n cos)   = IfaceAxiomRuleCo n (go_cos cos)

    go_cos = map go_co

    go_prov IfaceUnsafeCoerceProv    = IfaceUnsafeCoerceProv
    go_prov (IfacePhantomProv co)    = IfacePhantomProv (go_co co)
    go_prov (IfaceProofIrrelProv co) = IfaceProofIrrelProv (go_co co)
    go_prov (IfacePluginProv str)    = IfacePluginProv str
532

533 534
substIfaceAppArgs :: IfaceTySubst -> IfaceAppArgs -> IfaceAppArgs
substIfaceAppArgs env args
535 536
  = go args
  where
537 538
    go IA_Nil              = IA_Nil
    go (IA_Arg ty arg tys) = IA_Arg (substIfaceType env ty) arg (go tys)
539 540 541 542 543

substIfaceTyVar :: IfaceTySubst -> IfLclName -> IfaceType
substIfaceTyVar env tv
  | Just ty <- lookupFsEnv env tv = ty
  | otherwise                     = IfaceTyVar tv
544

545

Austin Seipp's avatar
Austin Seipp committed
546 547 548
{-
************************************************************************
*                                                                      *
549
                Functions over IfaceAppArgs
Austin Seipp's avatar
Austin Seipp committed
550 551 552
*                                                                      *
************************************************************************
-}
553

554
stripInvisArgs :: DynFlags -> IfaceAppArgs -> IfaceAppArgs
555
stripInvisArgs dflags tys
556
  | gopt Opt_PrintExplicitKinds dflags = tys
557
  | otherwise = suppress_invis tys
558
    where
559
      suppress_invis c
560
        = case c of
561 562 563 564
            IA_Nil -> IA_Nil
            IA_Arg t argf ts
              |  isVisibleArgFlag argf
              -> IA_Arg t argf $ suppress_invis ts
565 566
              -- Keep recursing through the remainder of the arguments, as it's
              -- possible that there are remaining invisible ones.
Ningning Xie's avatar
Ningning Xie committed
567 568
              -- See the "In type declarations" section of Note [VarBndrs,
              -- TyCoVarBinders, TyConBinders, and visibility] in TyCoRep.
569 570
              |  otherwise
              -> suppress_invis ts
571

572 573
appArgsIfaceTypes :: IfaceAppArgs -> [IfaceType]
appArgsIfaceTypes IA_Nil = []
574 575 576 577 578 579
appArgsIfaceTypes (IA_Arg t _ ts) = t : appArgsIfaceTypes ts

appArgsIfaceTypesArgFlags :: IfaceAppArgs -> [(IfaceType, ArgFlag)]
appArgsIfaceTypesArgFlags IA_Nil = []
appArgsIfaceTypesArgFlags (IA_Arg t a ts)
                                 = (t, a) : appArgsIfaceTypesArgFlags ts
580

581 582
ifaceVisAppArgsLength :: IfaceAppArgs -> Int
ifaceVisAppArgsLength = go 0
Ben Gamari's avatar
Ben Gamari committed
583
  where
584 585 586 587
    go !n IA_Nil = n
    go n  (IA_Arg _ argf rest)
      | isVisibleArgFlag argf = go (n+1) rest
      | otherwise             = go n rest
Ben Gamari's avatar
Ben Gamari committed
588

Austin Seipp's avatar
Austin Seipp committed
589
{-
590 591
Note [Suppressing invisible arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
592 593 594
We use the IfaceAppArgs data type to specify which of the arguments to a type
should be displayed when pretty-printing, under the control of
-fprint-explicit-kinds.
595
See also Type.filterOutInvisibleTypes.
596
For example, given
597

598 599
    T :: forall k. (k->*) -> k -> *    -- Ordinary kind polymorphism
    'Just :: forall k. k -> 'Maybe k   -- Promoted
600

601 602
we want

603 604 605 606 607 608 609 610 611 612 613
    T * Tree Int    prints as    T Tree Int
    'Just *         prints as    Just *

For type constructors (IfaceTyConApp), IfaceAppArgs is a quite natural fit,
since the corresponding Core constructor:

    data Type
      = ...
      | TyConApp TyCon [Type]

Already puts all of its arguments into a list. So when converting a Type to an
614 615 616
IfaceType (see toIfaceAppArgsX in GHC.Core.ToIface), we simply use the kind of
the TyCon (which is cached) to guide the process of converting the argument
Types into an IfaceAppArgs list.
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631

We also want this behavior for IfaceAppTy, since given:

    data Proxy (a :: k)
    f :: forall (t :: forall a. a -> Type). Proxy Type (t Bool True)

We want to print the return type as `Proxy (t True)` without the use of
-fprint-explicit-kinds (#15330). Accomplishing this is trickier than in the
tycon case, because the corresponding Core constructor for IfaceAppTy:

    data Type
      = ...
      | AppTy Type Type

Only stores one argument at a time. Therefore, when converting an AppTy to an
632
IfaceAppTy (in toIfaceTypeX in GHC.CoreToIface), we:
633 634 635 636 637 638 639 640 641 642 643 644 645 646

1. Flatten the chain of AppTys down as much as possible
2. Use typeKind to determine the function Type's kind
3. Use this kind to guide the process of converting the argument Types into an
   IfaceAppArgs list.

By flattening the arguments like this, we obtain two benefits:

(a) We can reuse the same machinery to pretty-print IfaceTyConApp arguments as
    we do IfaceTyApp arguments, which means that we only need to implement the
    logic to filter out invisible arguments once.
(b) Unlike for tycons, finding the kind of a type in general (through typeKind)
    is not a constant-time operation, so by flattening the arguments first, we
    decrease the number of times we have to call typeKind.
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
Note [Pretty-printing invisible arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Note [Suppressing invisible arguments] is all about how to avoid printing
invisible arguments when the -fprint-explicit-kinds flag is disables. Well,
what about when it's enabled? Then we can and should print invisible kind
arguments, and this Note explains how we do it.

As two running examples, consider the following code:

  {-# LANGUAGE PolyKinds #-}
  data T1 a
  data T2 (a :: k)

When displaying these types (with -fprint-explicit-kinds on), we could just
do the following:

  T1 k a
  T2 k a

That certainly gets the job done. But it lacks a crucial piece of information:
is the `k` argument inferred or specified? To communicate this, we use visible
kind application syntax to distinguish the two cases:

  T1 @{k} a
  T2 @k   a

Here, @{k} indicates that `k` is an inferred argument, and @k indicates that
`k` is a specified argument. (See
Note [VarBndrs, TyCoVarBinders, TyConBinders, and visibility] in TyCoRep for
a lengthier explanation on what "inferred" and "specified" mean.)

Austin Seipp's avatar
Austin Seipp committed
679 680
************************************************************************
*                                                                      *
681
                Pretty-printing
Austin Seipp's avatar
Austin Seipp committed
682 683 684
*                                                                      *
************************************************************************
-}
685

Ben Gamari's avatar
Ben Gamari committed
686 687 688 689 690 691 692 693 694 695 696
if_print_coercions :: SDoc  -- ^ if printing coercions
                   -> SDoc  -- ^ otherwise
                   -> SDoc
if_print_coercions yes no
  = sdocWithDynFlags $ \dflags ->
    getPprStyle $ \style ->
    if gopt Opt_PrintExplicitCoercions dflags
         || dumpStyle style || debugStyle style
    then yes
    else no

697
pprIfaceInfixApp :: PprPrec -> SDoc -> SDoc -> SDoc -> SDoc
698
pprIfaceInfixApp ctxt_prec pp_tc pp_ty1 pp_ty2
699
  = maybeParen ctxt_prec opPrec $
700
    sep [pp_ty1, pp_tc <+> pp_ty2]
701

702
pprIfacePrefixApp :: PprPrec -> SDoc -> [SDoc] -> SDoc
703
pprIfacePrefixApp ctxt_prec pp_fun pp_tys
704
  | null pp_tys = pp_fun
705
  | otherwise   = maybeParen ctxt_prec appPrec $
706
                  hang pp_fun 2 (sep pp_tys)
707

708 709 710 711 712
isIfaceTauType :: IfaceType -> Bool
isIfaceTauType (IfaceForAllTy _ _) = False
isIfaceTauType (IfaceFunTy InvisArg _ _) = False
isIfaceTauType _ = True

Austin Seipp's avatar
Austin Seipp committed
713
-- ----------------------------- Printing binders ------------------------------------
714 715 716

instance Outputable IfaceBndr where
    ppr (IfaceIdBndr bndr) = pprIfaceIdBndr bndr
717 718
    ppr (IfaceTvBndr bndr) = char '@' <+> pprIfaceTvBndr bndr (SuppressBndrSig False)
                                                              (UseBndrParens False)
719 720 721 722

pprIfaceBndrs :: [IfaceBndr] -> SDoc
pprIfaceBndrs bs = sep (map ppr bs)

723 724 725 726
pprIfaceLamBndr :: IfaceLamBndr -> SDoc
pprIfaceLamBndr (b, IfaceNoOneShot) = ppr b
pprIfaceLamBndr (b, IfaceOneShot)   = ppr b <> text "[OneShot]"

Ben Gamari's avatar
Ben Gamari committed
727
pprIfaceIdBndr :: IfaceIdBndr -> SDoc
728
pprIfaceIdBndr (name, ty) = parens (ppr name <+> dcolon <+> ppr ty)
729

730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
{- Note [Suppressing binder signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When printing the binders in a 'forall', we want to keep the kind annotations:

    forall (a :: k). blah
              ^^^^
              good

On the other hand, when we print the binders of a data declaration in :info,
the kind information would be redundant due to the standalone kind signature:

   type F :: Symbol -> Type
   type F (s :: Symbol) = blah
             ^^^^^^^^^
             redundant

Here we'd like to omit the kind annotation:

   type F :: Symbol -> Type
   type F s = blah
-}

-- | Do we want to suppress kind annotations on binders?
-- See Note [Suppressing binder signatures]
newtype SuppressBndrSig = SuppressBndrSig Bool

newtype UseBndrParens = UseBndrParens Bool

pprIfaceTvBndr :: IfaceTvBndr -> SuppressBndrSig -> UseBndrParens -> SDoc
pprIfaceTvBndr (tv, ki) (SuppressBndrSig suppress_sig) (UseBndrParens use_parens)
  | suppress_sig             = ppr tv
761
  | isIfaceLiftedTypeKind ki = ppr tv
Ben Gamari's avatar
Ben Gamari committed
762 763 764 765
  | otherwise                = maybe_parens (ppr tv <+> dcolon <+> ppr ki)
  where
    maybe_parens | use_parens = parens
                 | otherwise  = id
766

767 768
pprIfaceTyConBinders :: SuppressBndrSig -> [IfaceTyConBinder] -> SDoc
pprIfaceTyConBinders suppress_sig = sep . map go
769
  where
770 771 772 773 774
    go :: IfaceTyConBinder -> SDoc
    go (Bndr (IfaceIdBndr bndr) _) = pprIfaceIdBndr bndr
    go (Bndr (IfaceTvBndr bndr) vis) =
      -- See Note [Pretty-printing invisible arguments]
      case vis of
775 776
        AnonTCB  VisArg    -> ppr_bndr (UseBndrParens True)
        AnonTCB  InvisArg  -> char '@' <> braces (ppr_bndr (UseBndrParens False))
777 778
          -- The above case is rare. (See Note [AnonTCB InvisArg] in TyCon.)
          -- Should we print these differently?
779 780 781
        NamedTCB Required  -> ppr_bndr (UseBndrParens True)
        NamedTCB Specified -> char '@' <> ppr_bndr (UseBndrParens True)
        NamedTCB Inferred  -> char '@' <> braces (ppr_bndr (UseBndrParens False))
782
      where
783
        ppr_bndr = pprIfaceTvBndr bndr suppress_sig
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798

instance Binary IfaceBndr where
    put_ bh (IfaceIdBndr aa) = do
            putByte bh 0
            put_ bh aa
    put_ bh (IfaceTvBndr ab) = do
            putByte bh 1
            put_ bh ab
    get bh = do
            h <- getByte bh
            case h of
              0 -> do aa <- get bh
                      return (IfaceIdBndr aa)
              _ -> do ab <- get bh
                      return (IfaceTvBndr ab)
799 800 801 802 803 804 805 806 807 808 809

instance Binary IfaceOneShot where
    put_ bh IfaceNoOneShot = do
            putByte bh 0
    put_ bh IfaceOneShot = do
            putByte bh 1
    get bh = do
            h <- getByte bh
            case h of
              0 -> do return IfaceNoOneShot
              _ -> do return IfaceOneShot
810

Austin Seipp's avatar
Austin Seipp committed
811
-- ----------------------------- Printing IfaceType ------------------------------------
812 813 814

---------------------------------
instance Outputable IfaceType where
815
  ppr ty = pprIfaceType ty
816

Ben Gamari's avatar
Ben Gamari committed
817
pprIfaceType, pprParendIfaceType :: IfaceType -> SDoc
818 819
pprIfaceType       = pprPrecIfaceType topPrec
pprParendIfaceType = pprPrecIfaceType appPrec
820

821
pprPrecIfaceType :: PprPrec -> IfaceType -> SDoc
822 823
-- We still need `eliminateRuntimeRep`, since the `pprPrecIfaceType` maybe
-- called from other places, besides `:type` and `:info`.
824
pprPrecIfaceType prec ty = eliminateRuntimeRep (ppr_ty prec) ty
825

Simon Peyton Jones's avatar
Simon Peyton Jones committed
826 827 828 829
ppr_sigma :: PprPrec -> IfaceType -> SDoc
ppr_sigma ctxt_prec ty
  = maybeParen ctxt_prec funPrec (pprIfaceSigmaType ShowForAllMust ty)

830
ppr_ty :: PprPrec -> IfaceType -> SDoc
Simon Peyton Jones's avatar
Simon Peyton Jones committed
831 832 833
ppr_ty ctxt_prec ty@(IfaceForAllTy {})        = ppr_sigma ctxt_prec ty
ppr_ty ctxt_prec ty@(IfaceFunTy InvisArg _ _) = ppr_sigma ctxt_prec ty

Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
834
ppr_ty _         (IfaceFreeTyVar tyvar) = ppr tyvar  -- This is the main reason for IfaceFreeTyVar!
835
ppr_ty _         (IfaceTyVar tyvar)     = ppr tyvar  -- See Note [TcTyVars in IfaceType]
Ben Gamari's avatar
Ben Gamari committed
836
ppr_ty ctxt_prec (IfaceTyConApp tc tys) = pprTyTcApp ctxt_prec tc tys
837
ppr_ty ctxt_prec (IfaceTupleTy i p tys) = pprTuple ctxt_prec i p tys
Ben Gamari's avatar
Ben Gamari committed
838
ppr_ty _         (IfaceLitTy n)         = pprIfaceTyLit n
839
        -- Function types
Simon Peyton Jones's avatar
Simon Peyton Jones committed
840
ppr_ty ctxt_prec (IfaceFunTy _ ty1 ty2)  -- Should be VisArg
841
  = -- We don't want to lose synonyms, so we mustn't use splitFunTys here.
842 843
    maybeParen ctxt_prec funPrec $
    sep [ppr_ty funPrec ty1, sep (ppr_fun_tail ty2)]
844
  where
Simon Peyton Jones's avatar
Simon Peyton Jones committed
845
    ppr_fun_tail (IfaceFunTy VisArg ty1 ty2)
846
      = (arrow <+> ppr_ty funPrec ty1) : ppr_fun_tail ty2
847
    ppr_fun_tail other_ty
848
      = [arrow <+> pprIfaceType other_ty]
849

850
ppr_ty ctxt_prec (IfaceAppTy t ts)
Ben Gamari's avatar
Ben Gamari committed
851 852 853 854 855
  = if_print_coercions
      ppr_app_ty
      ppr_app_ty_no_casts
  where
    ppr_app_ty =
856 857 858
        sdocWithDynFlags $ \dflags ->
        pprIfacePrefixApp ctxt_prec
                          (ppr_ty funPrec t)
859
                          (map (ppr_app_arg appPrec) (tys_wo_kinds dflags))
860

861
    tys_wo_kinds dflags = appArgsIfaceTypesArgFlags $ stripInvisArgs dflags ts
Ben Gamari's avatar
Ben Gamari committed
862 863 864

    -- Strip any casts from the head of the application
    ppr_app_ty_no_casts =
865 866 867
        case t of
          IfaceCastTy head _ -> ppr_ty ctxt_prec (mk_app_tys head ts)
          _                  -> ppr_app_ty
Ben Gamari's avatar
Ben Gamari committed
868

869
    mk_app_tys :: IfaceType -> IfaceAppArgs -> IfaceType
Ben Gamari's avatar
Ben Gamari committed
870 871
    mk_app_tys (IfaceTyConApp tc tys1) tys2 =
        IfaceTyConApp tc (tys1 `mappend` tys2)
872
    mk_app_tys t1 tys2 = IfaceAppTy t1 tys2
873

874
ppr_ty ctxt_prec (IfaceCastTy ty co)
Ben Gamari's avatar
Ben Gamari committed
875
  = if_print_coercions
876
      (parens (ppr_ty topPrec ty <+> text "|>" <+> ppr co))
Ben Gamari's avatar
Ben Gamari committed
877
      (ppr_ty ctxt_prec ty)
878 879

ppr_ty ctxt_prec (IfaceCoercionTy co)
Ben Gamari's avatar
Ben Gamari committed
880 881 882
  = if_print_coercions
      (ppr_co ctxt_prec co)
      (text "<>")
883

884 885 886 887
{- Note [Defaulting RuntimeRep variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
RuntimeRep variables are considered by many (most?) users to be little
more than syntactic noise. When the notion was introduced there was a
888
significant and understandable push-back from those with pedagogy in
889 890 891
mind, which argued that RuntimeRep variables would throw a wrench into
nearly any teach approach since they appear in even the lowly ($)
function's type,
Ben Gamari's avatar
Ben Gamari committed
892 893 894 895 896 897 898

    ($) :: forall (w :: RuntimeRep) a (b :: TYPE w). (a -> b) -> a -> b

which is significantly less readable than its non RuntimeRep-polymorphic type of

    ($) :: (a -> b) -> a -> b

899 900 901 902 903 904 905 906 907 908 909 910
Moreover, unboxed types don't appear all that often in run-of-the-mill
Haskell programs, so it makes little sense to make all users pay this
syntactic overhead.

For this reason it was decided that we would hide RuntimeRep variables
for now (see #11549). We do this by defaulting all type variables of
kind RuntimeRep to LiftedRep. This is done in a pass right before
pretty-printing (defaultRuntimeRepVars, controlled by
-fprint-explicit-runtime-reps)

This applies to /quantified/ variables like 'w' above.  What about
variables that are /free/ in the type being printed, which certainly
911
happens in error messages.  Suppose (#16074) we are reporting a
912 913 914 915 916 917 918 919 920 921 922
mismatch between two skolems
          (a :: RuntimeRep) ~ (b :: RuntimeRep)
We certainly don't want to say "Can't match LiftedRep ~ LiftedRep"!

But if we are printing the type
    (forall (a :: Type r). blah
we do want to turn that (free) r into LiftedRep, so it prints as
    (forall a. blah)

Conclusion: keep track of whether we we are in the kind of a
binder; ohly if so, convert free RuntimeRep variables to LiftedRep.
Ben Gamari's avatar
Ben Gamari committed
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
-}

-- | Default 'RuntimeRep' variables to 'LiftedPtr'. e.g.
--
-- @
-- ($) :: forall (r :: GHC.Types.RuntimeRep) a (b :: TYPE r).
--        (a -> b) -> a -> b
-- @
--
-- turns in to,
--
-- @ ($) :: forall a (b :: *). (a -> b) -> a -> b @
--
-- We do this to prevent RuntimeRep variables from incurring a significant
-- syntactic overhead in otherwise simple type signatures (e.g. ($)). See
-- Note [Defaulting RuntimeRep variables] and #11549 for further discussion.
--
940 941
defaultRuntimeRepVars :: IfaceType -> IfaceType
defaultRuntimeRepVars ty = go False emptyFsEnv ty
Ben Gamari's avatar
Ben Gamari committed
942
  where
943 944 945 946 947 948 949
    go :: Bool              -- True <=> Inside the kind of a binder
       -> FastStringEnv ()  -- Set of enclosing forall-ed RuntimeRep variables
       -> IfaceType         --  (replace them with LiftedRep)
       -> IfaceType
    go ink subs (IfaceForAllTy (Bndr (IfaceTvBndr (var, var_kind)) argf) ty)
     | isRuntimeRep var_kind
      , isInvisibleArgFlag argf -- Don't default *visible* quantification
Ningning Xie's avatar
Ningning Xie committed
950
                                -- or we get the mess in #13963
Ben Gamari's avatar
Ben Gamari committed
951
      = let subs' = extendFsEnv subs var ()
952 953 954
            -- Record that we should replace it with LiftedRep,
            -- and recurse, discarding the forall
        in go ink subs' ty
Ningning Xie's avatar
Ningning Xie committed
955

956 957
    go ink subs (IfaceForAllTy bndr ty)
      = IfaceForAllTy (go_ifacebndr subs bndr) (go ink subs ty)
Ben Gamari's avatar
Ben Gamari committed
958

959
    go _ subs ty@(IfaceTyVar tv)
Ben Gamari's avatar
Ben Gamari committed
960
      | tv `elemFsEnv` subs
961
      = IfaceTyConApp liftedRep IA_Nil