Type.hs 88.9 KB
Newer Older
1 2 3 4
-- (c) The University of Glasgow 2006
-- (c) The GRASP/AQUA Project, Glasgow University, 1998
--
-- Type - public interface
5

Richard Eisenberg's avatar
Richard Eisenberg committed
6
{-# LANGUAGE CPP, FlexibleContexts #-}
7
{-# OPTIONS_GHC -fno-warn-orphans #-}
Ian Lynagh's avatar
Ian Lynagh committed
8

batterseapower's avatar
batterseapower committed
9
-- | Main functions for manipulating types and type-related things
10
module Type (
ian@well-typed.com's avatar
ian@well-typed.com committed
11
        -- Note some of this is just re-exports from TyCon..
12

batterseapower's avatar
batterseapower committed
13
        -- * Main data types representing Types
ian@well-typed.com's avatar
ian@well-typed.com committed
14 15
        -- $type_classification

batterseapower's avatar
batterseapower committed
16
        -- $representation_types
17
        TyThing(..), Type, ArgFlag(..), KindOrType, PredType, ThetaType,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
18
        Var, TyVar, isTyVar, TyCoVar, TyBinder, TyVarBinder,
19

batterseapower's avatar
batterseapower committed
20
        -- ** Constructing and deconstructing types
21 22
        mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe, repGetTyVar_maybe,
        getCastedTyVar_maybe, tyVarKind,
23

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
24
        mkAppTy, mkAppTys, splitAppTy, splitAppTys, repSplitAppTys,
25
        splitAppTy_maybe, repSplitAppTy_maybe, tcRepSplitAppTy_maybe,
26

ian@well-typed.com's avatar
ian@well-typed.com committed
27
        mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe,
28
        splitFunTys, funResultTy, funArgTy,
29

ian@well-typed.com's avatar
ian@well-typed.com committed
30
        mkTyConApp, mkTyConTy,
31 32
        tyConAppTyCon_maybe, tyConAppTyConPicky_maybe,
        tyConAppArgs_maybe, tyConAppTyCon, tyConAppArgs,
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
33
        splitTyConApp_maybe, splitTyConApp, tyConAppArgN, nextRole,
34 35 36
        splitListTyConApp_maybe,
        repSplitTyConApp_maybe,

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
37
        mkForAllTy, mkForAllTys, mkInvForAllTys, mkSpecForAllTys,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
38 39 40 41
        mkVisForAllTys, mkInvForAllTy,
        splitForAllTys, splitForAllTyVarBndrs,
        splitForAllTy_maybe, splitForAllTy,
        splitPiTy_maybe, splitPiTy, splitPiTys,
42
        mkPiTy, mkPiTys, mkTyConBindersPreferAnon,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
43
        mkLamType, mkLamTypes,
44
        piResultTy, piResultTys,
45
        applyTysX, dropForAlls,
46

47 48
        mkNumLitTy, isNumLitTy,
        mkStrLitTy, isStrLitTy,
49

Simon Peyton Jones's avatar
Simon Peyton Jones committed
50
        mkCastTy, mkCoercionTy, splitCastTy_maybe,
51

52
        userTypeError_maybe, pprUserTypeErrorTy,
53

54
        coAxNthLHS,
55 56 57 58 59 60 61 62
        stripCoercionTy, splitCoercionType_maybe,

        splitPiTysInvisible, filterOutInvisibleTypes,
        filterOutInvisibleTyVars, partitionInvisibles,
        synTyConResKind,

        -- Analyzing types
        TyCoMapper(..), mapType, mapCoercion,
ian@well-typed.com's avatar
ian@well-typed.com committed
63 64 65 66 67

        -- (Newtypes)
        newTyConInstRhs,

        -- Pred types
batterseapower's avatar
batterseapower committed
68
        mkFamilyTyConApp,
ian@well-typed.com's avatar
ian@well-typed.com committed
69
        isDictLikeTy,
70 71 72
        mkPrimEqPred, mkReprPrimEqPred, mkPrimEqPredRole,
        equalityTyCon,
        mkHeteroPrimEqPred, mkHeteroReprPrimEqPred,
73
        mkClassPred,
74
        isClassPred, isEqPred, isNomEqPred,
75
        isIPPred, isIPPred_maybe, isIPTyCon, isIPClass,
76
        isCTupleClass,
ian@well-typed.com's avatar
ian@well-typed.com committed
77

batterseapower's avatar
batterseapower committed
78
        -- Deconstructing predicate types
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
79
        PredTree(..), EqRel(..), eqRelRole, classifyPredType,
batterseapower's avatar
batterseapower committed
80
        getClassPredTys, getClassPredTys_maybe,
Joachim Breitner's avatar
Joachim Breitner committed
81
        getEqPredTys, getEqPredTys_maybe, getEqPredRole,
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
82
        predTypeEqRel,
83

84
        -- ** Binders
85
        sameVis,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
86
        mkTyVarBinder, mkTyVarBinders,
87
        mkAnonBinder,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
88
        isAnonTyBinder, isNamedTyBinder,
89
        binderVar, binderVars, binderKind, binderArgFlag,
90
        tyBinderType,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
91
        binderRelevantType_maybe, caseBinder,
92
        isVisibleArgFlag, isInvisibleArgFlag, isVisibleBinder, isInvisibleBinder,
93
        tyConBindersTyBinders,
94
        mkTyBinderTyConBinder,
95

ian@well-typed.com's avatar
ian@well-typed.com committed
96
        -- ** Common type constructors
batterseapower's avatar
batterseapower committed
97
        funTyCon,
98

batterseapower's avatar
batterseapower committed
99
        -- ** Predicates on types
100
        isTyVarTy, isFunTy, isDictTy, isPredTy, isCoercionTy,
101
        isCoercionTy_maybe, isCoercionType, isForAllTy,
102
        isPiTy, isTauTy, isFamFreeTy,
batterseapower's avatar
batterseapower committed
103

ian@well-typed.com's avatar
ian@well-typed.com committed
104
        -- (Lifting and boxity)
Richard Eisenberg's avatar
Richard Eisenberg committed
105
        isLiftedType_maybe, isUnliftedType, isUnboxedTupleType, isUnboxedSumType,
106
        isAlgType, isClosedAlgType,
ian@well-typed.com's avatar
ian@well-typed.com committed
107
        isPrimitiveType, isStrictType,
108 109 110
        isRuntimeRepTy, isRuntimeRepVar, isRuntimeRepKindedTy,
        dropRuntimeRepArgs,
        getRuntimeRep, getRuntimeRepFromKind,
111

ian@well-typed.com's avatar
ian@well-typed.com committed
112
        -- * Main data types representing Kinds
113
        Kind,
batterseapower's avatar
batterseapower committed
114 115

        -- ** Finding the kind of a type
Richard Eisenberg's avatar
Richard Eisenberg committed
116
        typeKind, isTypeLevPoly, resultIsLevPoly,
ian@well-typed.com's avatar
ian@well-typed.com committed
117

118
        -- ** Common Kind
119
        liftedTypeKind,
batterseapower's avatar
batterseapower committed
120

ian@well-typed.com's avatar
ian@well-typed.com committed
121
        -- * Type free variables
Simon Peyton Jones's avatar
Simon Peyton Jones committed
122 123
        tyCoFVsOfType, tyCoFVsBndr,
        tyCoVarsOfType, tyCoVarsOfTypes,
124 125
        tyCoVarsOfTypeDSet,
        coVarsOfType,
126
        coVarsOfTypes, closeOverKinds, closeOverKindsList,
Richard Eisenberg's avatar
Richard Eisenberg committed
127
        noFreeVarsOfType,
128
        splitVisVarsOfType, splitVisVarsOfTypes,
ian@well-typed.com's avatar
ian@well-typed.com committed
129
        expandTypeSynonyms,
130 131 132
        typeSize,

        -- * Well-scoped lists of variables
133
        dVarSetElemsWellScoped, toposortTyVars, tyCoVarsOfTypeWellScoped,
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
134
        tyCoVarsOfTypesWellScoped,
135

ian@well-typed.com's avatar
ian@well-typed.com committed
136
        -- * Type comparison
niteria's avatar
niteria committed
137 138
        eqType, eqTypeX, eqTypes, nonDetCmpType, nonDetCmpTypes, nonDetCmpTypeX,
        nonDetCmpTypesX, nonDetCmpTc,
139
        eqVarBndrs,
140

ian@well-typed.com's avatar
ian@well-typed.com committed
141
        -- * Forcing evaluation of types
batterseapower's avatar
batterseapower committed
142
        seqType, seqTypes,
143

batterseapower's avatar
batterseapower committed
144
        -- * Other views onto Types
145
        coreView, coreViewOneStarKind,
batterseapower's avatar
batterseapower committed
146

147
        tyConsOfType,
batterseapower's avatar
batterseapower committed
148

ian@well-typed.com's avatar
ian@well-typed.com committed
149 150
        -- * Main type substitution data types
        TvSubstEnv,     -- Representation widely visible
151
        TCvSubst(..),    -- Representation visible to a few friends
ian@well-typed.com's avatar
ian@well-typed.com committed
152 153

        -- ** Manipulating type substitutions
154
        emptyTvSubstEnv, emptyTCvSubst, mkEmptyTCvSubst,
ian@well-typed.com's avatar
ian@well-typed.com committed
155

niteria's avatar
niteria committed
156
        mkTCvSubst, zipTvSubst, mkTvSubstPrs,
157
        notElemTCvSubst,
158
        getTvSubstEnv, setTvSubstEnv,
159
        zapTCvSubst, getTCvInScope, getTCvSubstRangeFVs,
160
        extendTCvInScope, extendTCvInScopeList, extendTCvInScopeSet,
161
        extendTCvSubst, extendCvSubst,
162 163
        extendTvSubst, extendTvSubstBinder,
        extendTvSubstList, extendTvSubstAndInScope,
164
        extendTvSubstWithClone,
165 166
        isInScope, composeTCvSubstEnv, composeTCvSubst, zipTyEnv, zipCoEnv,
        isEmptyTCvSubst, unionTCvSubst,
167

ian@well-typed.com's avatar
ian@well-typed.com committed
168 169
        -- ** Performing substitution on types and kinds
        substTy, substTys, substTyWith, substTysWith, substTheta,
170 171
        substTyAddInScope,
        substTyUnchecked, substTysUnchecked, substThetaUnchecked,
172
        substTyWithUnchecked,
173
        substCoUnchecked, substCoWithUnchecked,
174
        substTyVarBndr, substTyVar, substTyVars,
175
        cloneTyVarBndr, cloneTyVarBndrs, lookupTyVar,
176

ian@well-typed.com's avatar
ian@well-typed.com committed
177
        -- * Pretty-printing
Simon Peyton Jones's avatar
Simon Peyton Jones committed
178
        pprType, pprParendType, pprTypeApp, pprTyThingCategory, pprShortTyThing,
Ben Gamari's avatar
Ben Gamari committed
179
        pprTvBndr, pprTvBndrs, pprForAll, pprUserForAll,
180
        pprSigmaType, ppSuggestExplicitKinds,
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
181
        pprTheta, pprThetaArrowTy, pprClassPred,
dreixel's avatar
dreixel committed
182
        pprKind, pprParendKind, pprSourceTyCon,
183
        TyPrec(..), maybeParen,
Ben Gamari's avatar
Ben Gamari committed
184
        pprTyVar, pprTyVars, pprTcAppTy, pprPrefixApp, pprArrowChain,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
185 186 187 188 189

        -- * Tidying type related things up for printing
        tidyType,      tidyTypes,
        tidyOpenType,  tidyOpenTypes,
        tidyOpenKind,
190 191
        tidyTyCoVarBndr, tidyTyCoVarBndrs, tidyFreeTyCoVars,
        tidyOpenTyCoVar, tidyOpenTyCoVars,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
192 193
        tidyTyVarOcc,
        tidyTopType,
194
        tidyKind,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
195
        tidyTyVarBinder, tidyTyVarBinders
196
    ) where
197

198 199
#include "HsVersions.h"

200
-- We import the representation and primitive functions from TyCoRep.
201 202
-- Many things are reexported, but not the representation!

dreixel's avatar
dreixel committed
203
import Kind
204
import TyCoRep
205

206
-- friends:
207
import Var
208 209
import VarEnv
import VarSet
210
import NameEnv
211

212 213
import Class
import TyCon
214
import TysPrim
215 216 217
import {-# SOURCE #-} TysWiredIn ( listTyCon, typeNatKind
                                 , typeSymbolKind, liftedTypeKind )
import PrelNames
218
import CoAxiom
219
import {-# SOURCE #-} Coercion
220

221
-- others
222
import Util
223
import Outputable
224
import FastString
225 226 227
import Pair
import ListSetOps
import Digraph
228
import Unique ( nonDetCmpUnique )
229 230 231
import SrcLoc  ( SrcSpan )
import OccName ( OccName )
import Name    ( mkInternalName )
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
232

ian@well-typed.com's avatar
ian@well-typed.com committed
233
import Maybes           ( orElse )
234
import Data.Maybe       ( isJust, mapMaybe )
235
import Control.Monad    ( guard )
236
import Control.Arrow    ( first, second )
237

batterseapower's avatar
batterseapower committed
238 239
-- $type_classification
-- #type_classification#
ian@well-typed.com's avatar
ian@well-typed.com committed
240
--
batterseapower's avatar
batterseapower committed
241
-- Types are one of:
ian@well-typed.com's avatar
ian@well-typed.com committed
242
--
batterseapower's avatar
batterseapower committed
243
-- [Unboxed]            Iff its representation is other than a pointer
ian@well-typed.com's avatar
ian@well-typed.com committed
244 245
--                      Unboxed types are also unlifted.
--
batterseapower's avatar
batterseapower committed
246
-- [Lifted]             Iff it has bottom as an element.
ian@well-typed.com's avatar
ian@well-typed.com committed
247 248 249 250 251 252
--                      Closures always have lifted types: i.e. any
--                      let-bound identifier in Core must have a lifted
--                      type. Operationally, a lifted object is one that
--                      can be entered.
--                      Only lifted types may be unified with a type variable.
--
batterseapower's avatar
batterseapower committed
253
-- [Algebraic]          Iff it is a type with one or more constructors, whether
ian@well-typed.com's avatar
ian@well-typed.com committed
254 255 256 257 258 259
--                      declared with @data@ or @newtype@.
--                      An algebraic type is one that can be deconstructed
--                      with a case expression. This is /not/ the same as
--                      lifted types, because we also include unboxed
--                      tuples in this classification.
--
batterseapower's avatar
batterseapower committed
260
-- [Data]               Iff it is a type declared with @data@, or a boxed tuple.
ian@well-typed.com's avatar
ian@well-typed.com committed
261
--
batterseapower's avatar
batterseapower committed
262
-- [Primitive]          Iff it is a built-in type that can't be expressed in Haskell.
ian@well-typed.com's avatar
ian@well-typed.com committed
263
--
batterseapower's avatar
batterseapower committed
264 265
-- Currently, all primitive types are unlifted, but that's not necessarily
-- the case: for example, @Int@ could be primitive.
ian@well-typed.com's avatar
ian@well-typed.com committed
266
--
batterseapower's avatar
batterseapower committed
267 268 269
-- Some primitive types are unboxed, such as @Int#@, whereas some are boxed
-- but unlifted (such as @ByteArray#@).  The only primitive types that we
-- classify as algebraic are the unboxed tuples.
ian@well-typed.com's avatar
ian@well-typed.com committed
270
--
batterseapower's avatar
batterseapower committed
271
-- Some examples of type classifications that may make this a bit clearer are:
ian@well-typed.com's avatar
ian@well-typed.com committed
272
--
batterseapower's avatar
batterseapower committed
273
-- @
274
-- Type          primitive       boxed           lifted          algebraic
batterseapower's avatar
batterseapower committed
275
-- -----------------------------------------------------------------------------
276 277 278 279 280 281
-- Int#          Yes             No              No              No
-- ByteArray#    Yes             Yes             No              No
-- (\# a, b \#)  Yes             No              No              Yes
-- (\# a | b \#) Yes             No              No              Yes
-- (  a, b  )    No              Yes             Yes             Yes
-- [a]           No              Yes             Yes             Yes
batterseapower's avatar
batterseapower committed
282 283 284 285 286
-- @

-- $representation_types
-- A /source type/ is a type that is a separate type as far as the type checker is
-- concerned, but which has a more low-level representation as far as Core-to-Core
batterseapower's avatar
batterseapower committed
287
-- passes and the rest of the back end is concerned.
batterseapower's avatar
batterseapower committed
288 289 290 291 292
--
-- You don't normally have to worry about this, as the utility functions in
-- this module will automatically convert a source into a representation type
-- if they are spotted, to the best of it's abilities. If you don't want this
-- to happen, use the equivalent functions from the "TcType" module.
293

294 295 296
{-
************************************************************************
*                                                                      *
ian@well-typed.com's avatar
ian@well-typed.com committed
297
                Type representation
298 299 300
*                                                                      *
************************************************************************
-}
301 302 303

{-# INLINE coreView #-}
coreView :: Type -> Maybe Type
304 305
-- ^ This function Strips off the /top layer only/ of a type synonym
-- application (if any) its underlying representation type.
306 307
-- Returns Nothing if there is nothing to look through.
--
308 309
-- By being non-recursive and inlined, this case analysis gets efficiently
-- joined onto the case analysis that the caller is already doing
310
coreView (TyConApp tc tys) | Just (tenv, rhs, tys') <- expandSynTyCon_maybe tc tys
niteria's avatar
niteria committed
311
  = Just (mkAppTys (substTy (mkTvSubstPrs tenv) rhs) tys')
312 313
               -- The free vars of 'rhs' should all be bound by 'tenv', so it's
               -- ok to use 'substTy' here.
314
               -- See also Note [The substitution invariant] in TyCoRep.
batterseapower's avatar
batterseapower committed
315
               -- Its important to use mkAppTys, rather than (foldl AppTy),
ian@well-typed.com's avatar
ian@well-typed.com committed
316
               -- because the function part might well return a
batterseapower's avatar
batterseapower committed
317
               -- partially-applied type constructor; indeed, usually will!
318
coreView _ = Nothing
319

320
-- | Like 'coreView', but it also "expands" @Constraint@ to become
Richard Eisenberg's avatar
Richard Eisenberg committed
321
-- @TYPE LiftedRep@.
322
{-# INLINE coreViewOneStarKind #-}
323
coreViewOneStarKind :: Type -> Maybe Type
324 325 326 327 328
coreViewOneStarKind ty
  | Just ty' <- coreView ty   = Just ty'
  | TyConApp tc [] <- ty
  , isStarKindSynonymTyCon tc = Just liftedTypeKind
  | otherwise                 = Nothing
329

330 331 332 333 334
-----------------------------------------------
expandTypeSynonyms :: Type -> Type
-- ^ Expand out all type synonyms.  Actually, it'd suffice to expand out
-- just the ones that discard type variables (e.g.  type Funny a = Int)
-- But we don't know which those are currently, so we just expand all.
335 336 337
--
-- 'expandTypeSynonyms' only expands out type synonyms mentioned in the type,
-- not in the kinds of any TyCon or TyVar mentioned in the type.
338 339
--
-- Keep this synchronized with 'synonymTyConsOfType'
ian@well-typed.com's avatar
ian@well-typed.com committed
340
expandTypeSynonyms ty
341
  = go (mkEmptyTCvSubst in_scope) ty
342
  where
343 344
    in_scope = mkInScopeSet (tyCoVarsOfType ty)

345
    go subst (TyConApp tc tys)
346 347 348 349 350 351 352 353 354 355
      | Just (tenv, rhs, tys') <- expandSynTyCon_maybe tc expanded_tys
      = let subst' = mkTvSubst in_scope (mkVarEnv tenv)
            -- Make a fresh substitution; rhs has nothing to
            -- do with anything that has happened so far
            -- NB: if you make changes here, be sure to build an
            --     /idempotent/ substitution, even in the nested case
            --        type T a b = a -> b
            --        type S x y = T y x
            -- (Trac #11665)
        in  mkAppTys (go subst' rhs) tys'
356
      | otherwise
357 358 359 360
      = TyConApp tc expanded_tys
      where
        expanded_tys = (map (go subst) tys)

361 362 363
    go _     (LitTy l)     = LitTy l
    go subst (TyVarTy tv)  = substTyVar subst tv
    go subst (AppTy t1 t2) = mkAppTy (go subst t1) (go subst t2)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
364
    go subst (FunTy arg res)
365
      = mkFunTy (go subst arg) (go subst res)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
366
    go subst (ForAllTy (TvBndr tv vis) t)
367
      = let (subst', tv') = substTyVarBndrCallback go subst tv in
Simon Peyton Jones's avatar
Simon Peyton Jones committed
368
        ForAllTy (TvBndr tv' vis) (go subst' t)
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 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 463 464 465 466 467 468 469
    go subst (CastTy ty co)  = mkCastTy (go subst ty) (go_co subst co)
    go subst (CoercionTy co) = mkCoercionTy (go_co subst co)

    go_co subst (Refl r ty)
      = mkReflCo r (go subst ty)
       -- NB: coercions are always expanded upon creation
    go_co subst (TyConAppCo r tc args)
      = mkTyConAppCo r tc (map (go_co subst) args)
    go_co subst (AppCo co arg)
      = mkAppCo (go_co subst co) (go_co subst arg)
    go_co subst (ForAllCo tv kind_co co)
      = let (subst', tv', kind_co') = go_cobndr subst tv kind_co in
        mkForAllCo tv' kind_co' (go_co subst' co)
    go_co subst (CoVarCo cv)
      = substCoVar subst cv
    go_co subst (AxiomInstCo ax ind args)
      = mkAxiomInstCo ax ind (map (go_co subst) args)
    go_co subst (UnivCo p r t1 t2)
      = mkUnivCo (go_prov subst p) r (go subst t1) (go subst t2)
    go_co subst (SymCo co)
      = mkSymCo (go_co subst co)
    go_co subst (TransCo co1 co2)
      = mkTransCo (go_co subst co1) (go_co subst co2)
    go_co subst (NthCo n co)
      = mkNthCo n (go_co subst co)
    go_co subst (LRCo lr co)
      = mkLRCo lr (go_co subst co)
    go_co subst (InstCo co arg)
      = mkInstCo (go_co subst co) (go_co subst arg)
    go_co subst (CoherenceCo co1 co2)
      = mkCoherenceCo (go_co subst co1) (go_co subst co2)
    go_co subst (KindCo co)
      = mkKindCo (go_co subst co)
    go_co subst (SubCo co)
      = mkSubCo (go_co subst co)
    go_co subst (AxiomRuleCo ax cs) = AxiomRuleCo ax (map (go_co subst) cs)

    go_prov _     UnsafeCoerceProv    = UnsafeCoerceProv
    go_prov subst (PhantomProv co)    = PhantomProv (go_co subst co)
    go_prov subst (ProofIrrelProv co) = ProofIrrelProv (go_co subst co)
    go_prov _     p@(PluginProv _)    = p
    go_prov _     (HoleProv h)        = pprPanic "expandTypeSynonyms hit a hole" (ppr h)

      -- the "False" and "const" are to accommodate the type of
      -- substForAllCoBndrCallback, which is general enough to
      -- handle coercion optimization (which sometimes swaps the
      -- order of a coercion)
    go_cobndr subst = substForAllCoBndrCallback False (go_co subst) subst

{-
************************************************************************
*                                                                      *
   Analyzing types
*                                                                      *
************************************************************************

These functions do a map-like operation over types, performing some operation
on all variables and binding sites. Primarily used for zonking.

Note [Efficiency for mapCoercion ForAllCo case]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As noted in Note [Forall coercions] in TyCoRep, a ForAllCo is a bit redundant.
It stores a TyVar and a Coercion, where the kind of the TyVar always matches
the left-hand kind of the coercion. This is convenient lots of the time, but
not when mapping a function over a coercion.

The problem is that tcm_tybinder will affect the TyVar's kind and
mapCoercion will affect the Coercion, and we hope that the results will be
the same. Even if they are the same (which should generally happen with
correct algorithms), then there is an efficiency issue. In particular,
this problem seems to make what should be a linear algorithm into a potentially
exponential one. But it's only going to be bad in the case where there's
lots of foralls in the kinds of other foralls. Like this:

  forall a : (forall b : (forall c : ...). ...). ...

This construction seems unlikely. So we'll do the inefficient, easy way
for now.

Note [Specialising mappers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
These INLINABLE pragmas are indispensable. mapType/mapCoercion are used
to implement zonking, and it's vital that they get specialised to the TcM
monad. This specialisation happens automatically (that is, without a
SPECIALISE pragma) as long as the definitions are INLINABLE. For example,
this one change made a 20% allocation difference in perf/compiler/T5030.

-}

-- | This describes how a "map" operation over a type/coercion should behave
data TyCoMapper env m
  = TyCoMapper
      { tcm_smart :: Bool -- ^ Should the new type be created with smart
                         -- constructors?
      , tcm_tyvar :: env -> TyVar -> m Type
      , tcm_covar :: env -> CoVar -> m Coercion
      , tcm_hole  :: env -> CoercionHole -> Role
                  -> Type -> Type -> m Coercion
          -- ^ What to do with coercion holes. See Note [Coercion holes] in
          -- TyCoRep.

470
      , tcm_tybinder :: env -> TyVar -> ArgFlag -> m (env, TyVar)
471 472 473 474
          -- ^ The returned env is used in the extended scope
      }

{-# INLINABLE mapType #-}  -- See Note [Specialising mappers]
475
mapType :: Monad m => TyCoMapper env m -> env -> Type -> m Type
476 477 478 479 480 481 482
mapType mapper@(TyCoMapper { tcm_smart = smart, tcm_tyvar = tyvar
                           , tcm_tybinder = tybinder })
        env ty
  = go ty
  where
    go (TyVarTy tv) = tyvar env tv
    go (AppTy t1 t2) = mkappty <$> go t1 <*> go t2
483 484
    go t@(TyConApp _ []) = return t  -- avoid allocation in this exceedingly
                                     -- common case (mostly, for *)
485
    go (TyConApp tc tys) = mktyconapp tc <$> mapM go tys
Simon Peyton Jones's avatar
Simon Peyton Jones committed
486 487
    go (FunTy arg res)   = FunTy <$> go arg <*> go res
    go (ForAllTy (TvBndr tv vis) inner)
488 489
      = do { (env', tv') <- tybinder env tv vis
           ; inner' <- mapType mapper env' inner
Simon Peyton Jones's avatar
Simon Peyton Jones committed
490 491 492
           ; return $ ForAllTy (TvBndr tv' vis) inner' }
    go ty@(LitTy {})   = return ty
    go (CastTy ty co)  = mkcastty <$> go ty <*> mapCoercion mapper env co
493 494
    go (CoercionTy co) = CoercionTy <$> mapCoercion mapper env co

Simon Peyton Jones's avatar
Simon Peyton Jones committed
495 496 497
    (mktyconapp, mkappty, mkcastty)
      | smart     = (mkTyConApp, mkAppTy, mkCastTy)
      | otherwise = (TyConApp,   AppTy,   CastTy)
498 499

{-# INLINABLE mapCoercion #-}  -- See Note [Specialising mappers]
500
mapCoercion :: Monad m
501 502 503 504 505 506 507 508 509 510 511 512
            => TyCoMapper env m -> env -> Coercion -> m Coercion
mapCoercion mapper@(TyCoMapper { tcm_smart = smart, tcm_covar = covar
                               , tcm_hole = cohole, tcm_tybinder = tybinder })
            env co
  = go co
  where
    go (Refl r ty) = Refl r <$> mapType mapper env ty
    go (TyConAppCo r tc args)
      = mktyconappco r tc <$> mapM go args
    go (AppCo c1 c2) = mkappco <$> go c1 <*> go c2
    go (ForAllCo tv kind_co co)
      = do { kind_co' <- go kind_co
513
           ; (env', tv') <- tybinder env tv Inferred
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
           ; co' <- mapCoercion mapper env' co
           ; return $ mkforallco tv' kind_co' co' }
        -- See Note [Efficiency for mapCoercion ForAllCo case]
    go (CoVarCo cv) = covar env cv
    go (AxiomInstCo ax i args)
      = mkaxiominstco ax i <$> mapM go args
    go (UnivCo (HoleProv hole) r t1 t2)
      = cohole env hole r t1 t2
    go (UnivCo p r t1 t2)
      = mkunivco <$> go_prov p <*> pure r
                 <*> mapType mapper env t1 <*> mapType mapper env t2
    go (SymCo co) = mksymco <$> go co
    go (TransCo c1 c2) = mktransco <$> go c1 <*> go c2
    go (AxiomRuleCo r cos) = AxiomRuleCo r <$> mapM go cos
    go (NthCo i co)        = mknthco i <$> go co
    go (LRCo lr co)        = mklrco lr <$> go co
    go (InstCo co arg)     = mkinstco <$> go co <*> go arg
    go (CoherenceCo c1 c2) = mkcoherenceco <$> go c1 <*> go c2
    go (KindCo co)         = mkkindco <$> go co
    go (SubCo co)          = mksubco <$> go co

    go_prov UnsafeCoerceProv    = return UnsafeCoerceProv
    go_prov (PhantomProv co)    = PhantomProv <$> go co
    go_prov (ProofIrrelProv co) = ProofIrrelProv <$> go co
    go_prov p@(PluginProv _)    = return p
    go_prov (HoleProv _)        = panic "mapCoercion"

    ( mktyconappco, mkappco, mkaxiominstco, mkunivco
      , mksymco, mktransco, mknthco, mklrco, mkinstco, mkcoherenceco
      , mkkindco, mksubco, mkforallco)
      | smart
      = ( mkTyConAppCo, mkAppCo, mkAxiomInstCo, mkUnivCo
        , mkSymCo, mkTransCo, mkNthCo, mkLRCo, mkInstCo, mkCoherenceCo
        , mkKindCo, mkSubCo, mkForAllCo )
      | otherwise
      = ( TyConAppCo, AppCo, AxiomInstCo, UnivCo
        , SymCo, TransCo, NthCo, LRCo, InstCo, CoherenceCo
        , KindCo, SubCo, ForAllCo )
552

553 554 555
{-
************************************************************************
*                                                                      *
556
\subsection{Constructor-specific functions}
557 558
*                                                                      *
************************************************************************
sof's avatar
sof committed
559 560


561
---------------------------------------------------------------------
ian@well-typed.com's avatar
ian@well-typed.com committed
562 563
                                TyVarTy
                                ~~~~~~~
564 565
-}

batterseapower's avatar
batterseapower committed
566 567
-- | Attempts to obtain the type variable underlying a 'Type', and panics with the
-- given message if this is not a type variable type. See also 'getTyVar_maybe'
568
getTyVar :: String -> Type -> TyVar
569
getTyVar msg ty = case getTyVar_maybe ty of
ian@well-typed.com's avatar
ian@well-typed.com committed
570 571
                    Just tv -> tv
                    Nothing -> panic ("getTyVar: " ++ msg)
572

573
isTyVarTy :: Type -> Bool
574 575
isTyVarTy ty = isJust (getTyVar_maybe ty)

batterseapower's avatar
batterseapower committed
576
-- | Attempts to obtain the type variable underlying a 'Type'
577
getTyVar_maybe :: Type -> Maybe TyVar
578
getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
                  | otherwise               = repGetTyVar_maybe ty

-- | If the type is a tyvar, possibly under a cast, returns it, along
-- with the coercion. Thus, the co is :: kind tv ~R kind type
getCastedTyVar_maybe :: Type -> Maybe (TyVar, Coercion)
getCastedTyVar_maybe ty | Just ty' <- coreView ty = getCastedTyVar_maybe ty'
getCastedTyVar_maybe (CastTy (TyVarTy tv) co)     = Just (tv, co)
getCastedTyVar_maybe (TyVarTy tv)
  = Just (tv, mkReflCo Nominal (tyVarKind tv))
getCastedTyVar_maybe _                            = Nothing

-- | Attempts to obtain the type variable underlying a 'Type', without
-- any expansion
repGetTyVar_maybe :: Type -> Maybe TyVar
repGetTyVar_maybe (TyVarTy tv) = Just tv
repGetTyVar_maybe _            = Nothing
595

596
{-
597
---------------------------------------------------------------------
ian@well-typed.com's avatar
ian@well-typed.com committed
598 599 600
                                AppTy
                                ~~~~~
We need to be pretty careful with AppTy to make sure we obey the
601 602
invariant that a TyConApp is always visibly so.  mkAppTy maintains the
invariant: use it.
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622

Note [Decomposing fat arrow c=>t]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Can we unify (a b) with (Eq a => ty)?   If we do so, we end up with
a partial application like ((=>) Eq a) which doesn't make sense in
source Haskell.  In constrast, we *can* unify (a b) with (t1 -> t2).
Here's an example (Trac #9858) of how you might do it:
   i :: (Typeable a, Typeable b) => Proxy (a b) -> TypeRep
   i p = typeRep p

   j = i (Proxy :: Proxy (Eq Int => Int))
The type (Proxy (Eq Int => Int)) is only accepted with -XImpredicativeTypes,
but suppose we want that.  But then in the call to 'i', we end
up decomposing (Eq Int => Int), and we definitely don't want that.

This really only applies to the type checker; in Core, '=>' and '->'
are the same, as are 'Constraint' and '*'.  But for now I've put
the test in repSplitAppTy_maybe, which applies throughout, because
the other calls to splitAppTy are in Unify, which is also used by
the type checker (e.g. when matching type-function equations).
623

624
-}
625

batterseapower's avatar
batterseapower committed
626
-- | Applies a type to another, as in e.g. @k a@
627
mkAppTy :: Type -> Type -> Type
628 629
mkAppTy (TyConApp tc tys) ty2 = mkTyConApp tc (tys ++ [ty2])
mkAppTy ty1               ty2 = AppTy ty1 ty2
ian@well-typed.com's avatar
ian@well-typed.com committed
630 631 632 633 634 635 636 637
        -- Note that the TyConApp could be an
        -- under-saturated type synonym.  GHC allows that; e.g.
        --      type Foo k = k a -> k a
        --      type Id x = x
        --      foo :: Foo Id -> Foo Id
        --
        -- Here Id is partially applied in the type sig for Foo,
        -- but once the type synonyms are expanded all is well
638

639
mkAppTys :: Type -> [Type] -> Type
ian@well-typed.com's avatar
ian@well-typed.com committed
640
mkAppTys ty1                []   = ty1
641 642 643
mkAppTys (TyConApp tc tys1) tys2 = mkTyConApp tc (tys1 ++ tys2)
mkAppTys ty1                tys2 = foldl AppTy ty1 tys2

644
-------------
645
splitAppTy_maybe :: Type -> Maybe (Type, Type)
batterseapower's avatar
batterseapower committed
646 647 648
-- ^ Attempt to take a type application apart, whether it is a
-- function, type constructor, or plain type application. Note
-- that type family applications are NEVER unsaturated by this!
649
splitAppTy_maybe ty | Just ty' <- coreView ty
ian@well-typed.com's avatar
ian@well-typed.com committed
650
                    = splitAppTy_maybe ty'
651
splitAppTy_maybe ty = repSplitAppTy_maybe ty
652

653 654
-------------
repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
ian@well-typed.com's avatar
ian@well-typed.com committed
655
-- ^ Does the AppTy split as in 'splitAppTy_maybe', but assumes that
batterseapower's avatar
batterseapower committed
656
-- any Core view stuff is already done
Simon Peyton Jones's avatar
Simon Peyton Jones committed
657
repSplitAppTy_maybe (FunTy ty1 ty2)   = Just (TyConApp funTyCon [ty1], ty2)
658
repSplitAppTy_maybe (AppTy ty1 ty2)   = Just (ty1, ty2)
ian@well-typed.com's avatar
ian@well-typed.com committed
659
repSplitAppTy_maybe (TyConApp tc tys)
660
  | mightBeUnsaturatedTyCon tc || tys `lengthExceeds` tyConArity tc
661 662
  , Just (tys', ty') <- snocView tys
  = Just (TyConApp tc tys', ty')    -- Never create unsaturated type family apps!
663
repSplitAppTy_maybe _other = Nothing
664 665 666 667 668 669 670

-- this one doesn't braek apart (c => t).
-- See Note [Decomposing fat arrow c=>t]
-- Defined here to avoid module loops between Unify and TcType.
tcRepSplitAppTy_maybe :: Type -> Maybe (Type,Type)
-- ^ Does the AppTy split as in 'tcSplitAppTy_maybe', but assumes that
-- any coreView stuff is already done. Refuses to look through (c => t)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
671
tcRepSplitAppTy_maybe (FunTy ty1 ty2)
672 673 674 675 676 677 678 679
  | isConstraintKind (typeKind ty1)     = Nothing  -- See Note [Decomposing fat arrow c=>t]
  | otherwise                           = Just (TyConApp funTyCon [ty1], ty2)
tcRepSplitAppTy_maybe (AppTy ty1 ty2)   = Just (ty1, ty2)
tcRepSplitAppTy_maybe (TyConApp tc tys)
  | mightBeUnsaturatedTyCon tc || tys `lengthExceeds` tyConArity tc
  , Just (tys', ty') <- snocView tys
  = Just (TyConApp tc tys', ty')    -- Never create unsaturated type family apps!
tcRepSplitAppTy_maybe _other = Nothing
680
-------------
681
splitAppTy :: Type -> (Type, Type)
batterseapower's avatar
batterseapower committed
682 683
-- ^ Attempts to take a type application apart, as in 'splitAppTy_maybe',
-- and panics if this is not possible
684
splitAppTy ty = case splitAppTy_maybe ty of
ian@well-typed.com's avatar
ian@well-typed.com committed
685 686
                Just pr -> pr
                Nothing -> panic "splitAppTy"
687

688
-------------
689
splitAppTys :: Type -> (Type, [Type])
batterseapower's avatar
batterseapower committed
690 691 692
-- ^ Recursively splits a type as far as is possible, leaving a residual
-- type being applied to and the type arguments applied to it. Never fails,
-- even if that means returning an empty list of type applications.
693
splitAppTys ty = split ty ty []
694
  where
695
    split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
696 697
    split _       (AppTy ty arg)        args = split ty ty (arg:args)
    split _       (TyConApp tc tc_args) args
698
      = let -- keep type families saturated
699 700
            n | mightBeUnsaturatedTyCon tc = 0
              | otherwise                  = tyConArity tc
701
            (tc_args1, tc_args2) = splitAt n tc_args
702 703
        in
        (TyConApp tc tc_args1, tc_args2 ++ args)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
704 705 706
    split _   (FunTy ty1 ty2) args = ASSERT( null args )
                                     (TyConApp funTyCon [], [ty1,ty2])
    split orig_ty _           args = (orig_ty, args)
707

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
708 709 710 711 712 713 714 715 716 717 718
-- | Like 'splitAppTys', but doesn't look through type synonyms
repSplitAppTys :: Type -> (Type, [Type])
repSplitAppTys ty = split ty []
  where
    split (AppTy ty arg) args = split ty (arg:args)
    split (TyConApp tc tc_args) args
      = let n | mightBeUnsaturatedTyCon tc = 0
              | otherwise                  = tyConArity tc
            (tc_args1, tc_args2) = splitAt n tc_args
        in
        (TyConApp tc tc_args1, tc_args2 ++ args)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
719 720
    split (FunTy ty1 ty2) args = ASSERT( null args )
                                 (TyConApp funTyCon [], [ty1, ty2])
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
721 722
    split ty args = (ty, args)

723
{-
724
                      LitTy
725
                      ~~~~~
726
-}
727

728 729
mkNumLitTy :: Integer -> Type
mkNumLitTy n = LitTy (NumTyLit n)
730

731
-- | Is this a numeric literal. We also look through type synonyms.
732
isNumLitTy :: Type -> Maybe Integer
733
isNumLitTy ty | Just ty1 <- coreView ty = isNumLitTy ty1
734 735
isNumLitTy (LitTy (NumTyLit n)) = Just n
isNumLitTy _                    = Nothing
736

737 738 739
mkStrLitTy :: FastString -> Type
mkStrLitTy s = LitTy (StrTyLit s)

740
-- | Is this a symbol literal. We also look through type synonyms.
741
isStrLitTy :: Type -> Maybe FastString
742
isStrLitTy ty | Just ty1 <- coreView ty = isStrLitTy ty1
743 744
isStrLitTy (LitTy (StrTyLit s)) = Just s
isStrLitTy _                    = Nothing
745

746 747 748

-- | Is this type a custom user error?
-- If so, give us the kind and the error message.
749 750
userTypeError_maybe :: Type -> Maybe Type
userTypeError_maybe t
751 752 753 754
  = do { (tc, _kind : msg : _) <- splitTyConApp_maybe t
          -- There may be more than 2 arguments, if the type error is
          -- used as a type constructor (e.g. at kind `Type -> Type`).

755 756
       ; guard (tyConName tc == errorMessageTypeErrorFamName)
       ; return msg }
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787

-- | Render a type corresponding to a user type error into a SDoc.
pprUserTypeErrorTy :: Type -> SDoc
pprUserTypeErrorTy ty =
  case splitTyConApp_maybe ty of

    -- Text "Something"
    Just (tc,[txt])
      | tyConName tc == typeErrorTextDataConName
      , Just str <- isStrLitTy txt -> ftext str

    -- ShowType t
    Just (tc,[_k,t])
      | tyConName tc == typeErrorShowTypeDataConName -> ppr t

    -- t1 :<>: t2
    Just (tc,[t1,t2])
      | tyConName tc == typeErrorAppendDataConName ->
        pprUserTypeErrorTy t1 <> pprUserTypeErrorTy t2

    -- t1 :$$: t2
    Just (tc,[t1,t2])
      | tyConName tc == typeErrorVAppendDataConName ->
        pprUserTypeErrorTy t1 $$ pprUserTypeErrorTy t2

    -- An uneavaluated type function
    _ -> ppr ty




788
{-
789
---------------------------------------------------------------------
ian@well-typed.com's avatar
ian@well-typed.com committed
790 791
                                FunTy
                                ~~~~~
792
-}
793

ian@well-typed.com's avatar
ian@well-typed.com committed
794
isFunTy :: Type -> Bool
795 796
isFunTy ty = isJust (splitFunTy_maybe ty)

797
splitFunTy :: Type -> (Type, Type)
batterseapower's avatar
batterseapower committed
798 799
-- ^ Attempts to extract the argument and result types from a type, and
-- panics if that is not possible. See also 'splitFunTy_maybe'
800
splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
Simon Peyton Jones's avatar
Simon Peyton Jones committed
801 802
splitFunTy (FunTy arg res) = (arg, res)
splitFunTy other           = pprPanic "splitFunTy" (ppr other)
803

804
splitFunTy_maybe :: Type -> Maybe (Type, Type)
batterseapower's avatar
batterseapower committed
805
-- ^ Attempts to extract the argument and result types from a type
806
splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
Simon Peyton Jones's avatar
Simon Peyton Jones committed
807 808
splitFunTy_maybe (FunTy arg res) = Just (arg, res)
splitFunTy_maybe _               = Nothing
809

810
splitFunTys :: Type -> ([Type], Type)
811
splitFunTys ty = split [] ty ty
812
  where
813
    split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
Simon Peyton Jones's avatar
Simon Peyton Jones committed
814 815
    split args _       (FunTy arg res) = split (arg:args) res res
    split args orig_ty _               = (reverse args, orig_ty)
816

817
funResultTy :: Type -> Type
batterseapower's avatar
batterseapower committed
818
-- ^ Extract the function result type and panic if that is not possible
819
funResultTy ty | Just ty' <- coreView ty = funResultTy ty'
Simon Peyton Jones's avatar
Simon Peyton Jones committed
820 821
funResultTy (FunTy _ res) = res
funResultTy ty            = pprPanic "funResultTy" (ppr ty)
822 823

funArgTy :: Type -> Type
batterseapower's avatar
batterseapower committed
824
-- ^ Extract the function argument type and panic if that is not possible
825
funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
Simon Peyton Jones's avatar
Simon Peyton Jones committed
826 827
funArgTy (FunTy arg _res) = arg
funArgTy ty               = pprPanic "funArgTy" (ppr ty)
828

Simon Peyton Jones's avatar
Simon Peyton Jones committed
829 830 831 832 833 834 835
piResultTy :: Type -> Type ->  Type
piResultTy ty arg = case piResultTy_maybe ty arg of
                      Just res -> res
                      Nothing  -> pprPanic "piResultTy" (ppr ty $$ ppr arg)

piResultTy_maybe :: Type -> Type -> Maybe Type

836 837 838
-- ^ Just like 'piResultTys' but for a single argument
-- Try not to iterate 'piResultTy', because it's inefficient to substitute
-- one variable at a time; instead use 'piResultTys"
Simon Peyton Jones's avatar
Simon Peyton Jones committed
839 840
piResultTy_maybe ty arg
  | Just ty' <- coreView ty = piResultTy_maybe ty' arg
841

Simon Peyton Jones's avatar
Simon Peyton Jones committed
842 843 844 845 846 847 848 849
  | FunTy _ res <- ty
  = Just res

  | ForAllTy (TvBndr tv _) res <- ty
  = let empty_subst = mkEmptyTCvSubst $ mkInScopeSet $
                      tyCoVarsOfTypes [arg,res]
    in Just (substTy (extendTvSubst empty_subst tv arg) res)

850
  | otherwise
Simon Peyton Jones's avatar
Simon Peyton Jones committed
851
  = Nothing
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879

-- | (piResultTys f_ty [ty1, .., tyn]) gives the type of (f ty1 .. tyn)
--   where f :: f_ty
-- 'piResultTys' is interesting because:
--      1. 'f_ty' may have more for-alls than there are args
--      2. Less obviously, it may have fewer for-alls
-- For case 2. think of:
--   piResultTys (forall a.a) [forall b.b, Int]
-- This really can happen, but only (I think) in situations involving
-- undefined.  For example:
--       undefined :: forall a. a
-- Term: undefined @(forall b. b->b) @Int
-- This term should have type (Int -> Int), but notice that
-- there are more type args than foralls in 'undefined's type.

-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs

-- This is a heavily used function (e.g. from typeKind),
-- so we pay attention to efficiency, especially in the special case
-- where there are no for-alls so we are just dropping arrows from
-- a function type/kind.
piResultTys :: Type -> [Type] -> Type
piResultTys ty [] = ty
piResultTys ty orig_args@(arg:args)
  | Just ty' <- coreView ty
  = piResultTys ty' orig_args

Simon Peyton Jones's avatar
Simon Peyton Jones committed
880 881 882 883 884
  | FunTy _ res <- ty
  = piResultTys res args

  | ForAllTy (TvBndr tv _) res <- ty
  = go (extendVarEnv emptyTvSubstEnv tv arg) res args
885 886

  | otherwise
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
887
  = pprPanic "piResultTys1" (ppr ty $$ ppr orig_args)
888
  where
889 890
    in_scope = mkInScopeSet (tyCoVarsOfTypes (ty:orig_args))

891 892 893 894 895 896 897
    go :: TvSubstEnv -> Type -> [Type] -> Type
    go tv_env ty [] = substTy (mkTvSubst in_scope tv_env) ty

    go tv_env ty all_args@(arg:args)
      | Just ty' <- coreView ty
      = go tv_env ty' all_args

Simon Peyton Jones's avatar
Simon Peyton Jones committed
898 899 900 901 902
      | FunTy _ res <- ty
      = go tv_env res args

      | ForAllTy (TvBndr tv _) res <- ty
      = go (extendVarEnv tv_env tv arg) res args
903 904 905 906 907 908 909

      | TyVarTy tv <- ty
      , Just ty' <- lookupVarEnv tv_env tv
        -- Deals with piResultTys (forall a. a) [forall b.b, Int]
      = piResultTys ty' all_args

      | otherwise
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
910
      = pprPanic "piResultTys2" (ppr ty $$ ppr orig_args $$ ppr all_args)
911

912 913 914 915 916 917 918 919 920 921 922 923
applyTysX :: [TyVar] -> Type -> [Type] -> Type
-- applyTyxX beta-reduces (/\tvs. body_ty) arg_tys
-- Assumes that (/\tvs. body_ty) is closed
applyTysX tvs body_ty arg_tys
  = ASSERT2( length arg_tys >= n_tvs, pp_stuff )
    ASSERT2( tyCoVarsOfType body_ty `subVarSet` mkVarSet tvs, pp_stuff )
    mkAppTys (substTyWith tvs (take n_tvs arg_tys) body_ty)
             (drop n_tvs arg_tys)
  where
    pp_stuff = vcat [ppr tvs, ppr body_ty, ppr arg_tys]
    n_tvs = length tvs

924
{-