Type.hs 86.4 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

6
{-# LANGUAGE CPP #-}
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
18
        TyThing(..), Type, VisibilityFlag(..), KindOrType, PredType, ThetaType,
        Var, TyVar, isTyVar, TyCoVar, TyBinder,
19

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

24
        mkAppTy, mkAppTys, splitAppTy, splitAppTys,
25
        splitAppTy_maybe, repSplitAppTy_maybe, tcRepSplitAppTy_maybe,
26

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

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

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
38
39
        mkForAllTy, mkForAllTys, mkInvForAllTys, mkSpecForAllTys,
        mkVisForAllTys,
40
41
42
43
44
45
46
        mkNamedForAllTy,
        splitForAllTy_maybe, splitForAllTys, splitForAllTy,
        splitPiTy_maybe, splitPiTys, splitPiTy,
        splitNamedPiTys,
        mkPiType, mkPiTypes, mkPiTypesPreferFunTy,
        piResultTy, piResultTys,
        applyTys, applyTysD, applyTysX, dropForAlls,
47

48
49
        mkNumLitTy, isNumLitTy,
        mkStrLitTy, isStrLitTy,
50

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

53
        userTypeError_maybe, pprUserTypeErrorTy,
54

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

        splitPiTysInvisible, filterOutInvisibleTypes,
        filterOutInvisibleTyVars, partitionInvisibles,
        synTyConResKind,
        tyConBinders,

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

        -- (Newtypes)
        newTyConInstRhs,

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

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

86
        -- ** Binders
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
87
        sameVis,
88
89
90
91
92
93
        mkNamedBinder, mkAnonBinder, isNamedBinder, isAnonBinder,
        isIdLikeBinder, binderVisibility, binderVar_maybe,
        binderVar, binderRelevantType_maybe, caseBinder,
        partitionBinders, partitionBindersIntoBinders,
        binderType, isVisibleBinder, isInvisibleBinder,

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

batterseapower's avatar
batterseapower committed
97
        -- ** Predicates on types
98
99
100
101
        allDistinctTyVars,
        isTyVarTy, isFunTy, isDictTy, isPredTy, isVoidTy, isCoercionTy,
        isCoercionTy_maybe, isCoercionType, isForAllTy,
        isPiTy,
batterseapower's avatar
batterseapower committed
102

ian@well-typed.com's avatar
ian@well-typed.com committed
103
        -- (Lifting and boxity)
104
        isUnliftedType, isUnboxedTupleType, isAlgType, isClosedAlgType,
ian@well-typed.com's avatar
ian@well-typed.com committed
105
        isPrimitiveType, isStrictType,
106
107
108
        isLevityTy, isLevityVar, isLevityKindedTy,
        dropLevityArgs,
        getLevity, getLevityFromKind,
109

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

        -- ** Finding the kind of a type
        typeKind,
ian@well-typed.com's avatar
ian@well-typed.com committed
115

116
117
        -- ** Common Kind
        liftedTypeKind, unliftedTypeKind,
batterseapower's avatar
batterseapower committed
118

ian@well-typed.com's avatar
ian@well-typed.com committed
119
        -- * Type free variables
120
121
122
123
124
125
        tyCoVarsOfType, tyCoVarsOfTypes, tyCoVarsOfTypeAcc,
        tyCoVarsOfTypeDSet,
        coVarsOfType,
        coVarsOfTypes, closeOverKinds,
        splitDepVarsOfType, splitDepVarsOfTypes,
        splitVisVarsOfType, splitVisVarsOfTypes,
ian@well-typed.com's avatar
ian@well-typed.com committed
126
        expandTypeSynonyms,
127
128
129
130
        typeSize,

        -- * Well-scoped lists of variables
        varSetElemsWellScoped, toposortTyVars, tyCoVarsOfTypeWellScoped,
131

ian@well-typed.com's avatar
ian@well-typed.com committed
132
        -- * Type comparison
133
134
        eqType, eqTypeX, eqTypes, cmpType, cmpTypes, cmpTypeX, cmpTypesX, cmpTc,
        eqVarBndrs,
135

ian@well-typed.com's avatar
ian@well-typed.com committed
136
        -- * Forcing evaluation of types
batterseapower's avatar
batterseapower committed
137
        seqType, seqTypes,
138

batterseapower's avatar
batterseapower committed
139
        -- * Other views onto Types
140
        coreView, coreViewOneStarKind,
batterseapower's avatar
batterseapower committed
141

142
        UnaryType, RepType(..), flattenRepType, repType,
143
        tyConsOfType,
batterseapower's avatar
batterseapower committed
144

ian@well-typed.com's avatar
ian@well-typed.com committed
145
146
147
148
149
        -- * Type representation for the code generator
        typePrimRep, typeRepArity,

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

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

niteria's avatar
niteria committed
155
        mkTCvSubst, zipTvSubst, mkTvSubstPrs,
156
        notElemTCvSubst,
157
        getTvSubstEnv, setTvSubstEnv,
158
        zapTCvSubst, getTCvInScope,
159
160
        extendTCvInScope, extendTCvInScopeList, extendTCvInScopeSet,
        extendTCvSubst, extendTCvSubstList, extendTCvSubstAndInScope,
161
162
        isInScope, composeTCvSubstEnv, composeTCvSubst, zipTyEnv, zipCoEnv,
        isEmptyTCvSubst, unionTCvSubst,
163

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

ian@well-typed.com's avatar
ian@well-typed.com committed
173
174
        -- * Pretty-printing
        pprType, pprParendType, pprTypeApp, pprTyThingCategory, pprTyThing,
175
176
        pprTvBndr, pprTvBndrs, pprForAll, pprForAllImplicit, pprUserForAll,
        pprSigmaType,
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
177
        pprTheta, pprThetaArrowTy, pprClassPred,
dreixel's avatar
dreixel committed
178
        pprKind, pprParendKind, pprSourceTyCon,
179
        TyPrec(..), maybeParen,
180
        pprTyVar, pprTcAppTy, pprPrefixApp, pprArrowChain,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
181
182
183
184
185

        -- * Tidying type related things up for printing
        tidyType,      tidyTypes,
        tidyOpenType,  tidyOpenTypes,
        tidyOpenKind,
186
187
        tidyTyCoVarBndr, tidyTyCoVarBndrs, tidyFreeTyCoVars,
        tidyOpenTyCoVar, tidyOpenTyCoVars,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
188
189
        tidyTyVarOcc,
        tidyTopType,
190
        tidyKind
191
    ) where
192

193
194
#include "HsVersions.h"

195
-- We import the representation and primitive functions from TyCoRep.
196
197
-- Many things are reexported, but not the representation!

dreixel's avatar
dreixel committed
198
import Kind
199
import TyCoRep
200

201
-- friends:
202
import Var
203
204
import VarEnv
import VarSet
205
import NameEnv
206

207
208
import Class
import TyCon
209
import TysPrim
210
211
212
import {-# SOURCE #-} TysWiredIn ( listTyCon, typeNatKind
                                 , typeSymbolKind, liftedTypeKind )
import PrelNames
213
import CoAxiom
214
import {-# SOURCE #-} Coercion
215

216
-- others
ian@well-typed.com's avatar
ian@well-typed.com committed
217
import BasicTypes       ( Arity, RepArity )
218
import Util
219
import Outputable
220
import FastString
221
222
223
import Pair
import ListSetOps
import Digraph
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
224

ian@well-typed.com's avatar
ian@well-typed.com committed
225
import Maybes           ( orElse )
226
import Data.Maybe       ( isJust, mapMaybe )
227
import Control.Monad    ( guard )
228
import Control.Arrow    ( first, second )
229

batterseapower's avatar
batterseapower committed
230
231
-- $type_classification
-- #type_classification#
ian@well-typed.com's avatar
ian@well-typed.com committed
232
--
batterseapower's avatar
batterseapower committed
233
-- Types are one of:
ian@well-typed.com's avatar
ian@well-typed.com committed
234
--
batterseapower's avatar
batterseapower committed
235
-- [Unboxed]            Iff its representation is other than a pointer
ian@well-typed.com's avatar
ian@well-typed.com committed
236
237
--                      Unboxed types are also unlifted.
--
batterseapower's avatar
batterseapower committed
238
-- [Lifted]             Iff it has bottom as an element.
ian@well-typed.com's avatar
ian@well-typed.com committed
239
240
241
242
243
244
--                      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
245
-- [Algebraic]          Iff it is a type with one or more constructors, whether
ian@well-typed.com's avatar
ian@well-typed.com committed
246
247
248
249
250
251
--                      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
252
-- [Data]               Iff it is a type declared with @data@, or a boxed tuple.
ian@well-typed.com's avatar
ian@well-typed.com committed
253
--
batterseapower's avatar
batterseapower committed
254
-- [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
255
--
batterseapower's avatar
batterseapower committed
256
257
-- 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
258
--
batterseapower's avatar
batterseapower committed
259
260
261
-- 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
262
--
batterseapower's avatar
batterseapower committed
263
-- Some examples of type classifications that may make this a bit clearer are:
ian@well-typed.com's avatar
ian@well-typed.com committed
264
--
batterseapower's avatar
batterseapower committed
265
266
267
268
269
270
271
272
273
274
275
276
277
-- @
-- Type         primitive       boxed           lifted          algebraic
-- -----------------------------------------------------------------------------
-- Int#         Yes             No              No              No
-- ByteArray#   Yes             Yes             No              No
-- (\# a, b \#)   Yes             No              No              Yes
-- (  a, b  )   No              Yes             Yes             Yes
-- [a]          No              Yes             Yes             Yes
-- @

-- $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
278
-- passes and the rest of the back end is concerned.
batterseapower's avatar
batterseapower committed
279
280
281
282
283
--
-- 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.
284

285
286
287
{-
************************************************************************
*                                                                      *
ian@well-typed.com's avatar
ian@well-typed.com committed
288
                Type representation
289
290
291
*                                                                      *
************************************************************************
-}
292
293
294

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

311
312
313
-- | Like 'coreView', but it also "expands" @Constraint@ to become
-- @TYPE Lifted@.
coreViewOneStarKind :: Type -> Maybe Type
314
315
316
317
318
coreViewOneStarKind ty
  | Just ty' <- coreView ty   = Just ty'
  | TyConApp tc [] <- ty
  , isStarKindSynonymTyCon tc = Just liftedTypeKind
  | otherwise                 = Nothing
319

320
321
322
323
324
-----------------------------------------------
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.
325
326
327
--
-- 'expandTypeSynonyms' only expands out type synonyms mentioned in the type,
-- not in the kinds of any TyCon or TyVar mentioned in the type.
ian@well-typed.com's avatar
ian@well-typed.com committed
328
expandTypeSynonyms ty
329
  = go (mkEmptyTCvSubst (mkTyCoInScopeSet [ty] [])) ty
330
  where
331
    go subst (TyConApp tc tys)
332
      | Just (tenv, rhs, tys') <- expandSynTyCon_maybe tc tys
niteria's avatar
niteria committed
333
      = let subst' = unionTCvSubst subst (mkTvSubstPrs tenv) in
334
        go subst' (mkAppTys rhs tys')
335
      | otherwise
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
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
      = TyConApp tc (map (go subst) tys)
    go _     (LitTy l)     = LitTy l
    go subst (TyVarTy tv)  = substTyVar subst tv
    go subst (AppTy t1 t2) = mkAppTy (go subst t1) (go subst t2)
    go subst (ForAllTy (Anon arg) res)
      = mkFunTy (go subst arg) (go subst res)
    go subst (ForAllTy (Named tv vis) t)
      = let (subst', tv') = substTyVarBndrCallback go subst tv in
        ForAllTy (Named tv' vis) (go subst' t)
    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.

      , tcm_tybinder :: env -> TyVar -> VisibilityFlag -> m (env, TyVar)
          -- ^ The returned env is used in the extended scope
      }

{-# INLINABLE mapType #-}  -- See Note [Specialising mappers]
451
mapType :: Monad m => TyCoMapper env m -> env -> Type -> m Type
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
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
    go (TyConApp tc tys) = mktyconapp tc <$> mapM go tys
    go (ForAllTy (Anon arg) res) = mkfunty <$> go arg <*> go res
    go (ForAllTy (Named tv vis) inner)
      = do { (env', tv') <- tybinder env tv vis
           ; inner' <- mapType mapper env' inner
           ; return $ ForAllTy (Named tv' vis) inner' }
    go ty@(LitTy {}) = return ty
    go (CastTy ty co) = mkcastty <$> go ty <*> mapCoercion mapper env co
    go (CoercionTy co) = CoercionTy <$> mapCoercion mapper env co

    (mktyconapp, mkappty, mkcastty, mkfunty)
      | smart     = (mkTyConApp, mkAppTy, mkCastTy, mkFunTy)
      | otherwise = (TyConApp,   AppTy,   CastTy,   ForAllTy . Anon)

{-# INLINABLE mapCoercion #-}  -- See Note [Specialising mappers]
474
mapCoercion :: Monad m
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
            => 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
           ; (env', tv') <- tybinder env tv Invisible
           ; 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 )
526

527
528
529
{-
************************************************************************
*                                                                      *
530
\subsection{Constructor-specific functions}
531
532
*                                                                      *
************************************************************************
sof's avatar
sof committed
533
534


535
---------------------------------------------------------------------
ian@well-typed.com's avatar
ian@well-typed.com committed
536
537
                                TyVarTy
                                ~~~~~~~
538
539
-}

batterseapower's avatar
batterseapower committed
540
541
-- | 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'
542
getTyVar :: String -> Type -> TyVar
543
getTyVar msg ty = case getTyVar_maybe ty of
ian@well-typed.com's avatar
ian@well-typed.com committed
544
545
                    Just tv -> tv
                    Nothing -> panic ("getTyVar: " ++ msg)
546

547
isTyVarTy :: Type -> Bool
548
549
isTyVarTy ty = isJust (getTyVar_maybe ty)

batterseapower's avatar
batterseapower committed
550
-- | Attempts to obtain the type variable underlying a 'Type'
551
getTyVar_maybe :: Type -> Maybe TyVar
552
getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
                  | 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
569

570
571
572
573
574
575
576
577
578
allDistinctTyVars :: [KindOrType] -> Bool
allDistinctTyVars tkvs = go emptyVarSet tkvs
  where
    go _      [] = True
    go so_far (ty : tys)
       = case getTyVar_maybe ty of
             Nothing -> False
             Just tv | tv `elemVarSet` so_far -> False
                     | otherwise -> go (so_far `extendVarSet` tv) tys
579

580
{-
581
---------------------------------------------------------------------
ian@well-typed.com's avatar
ian@well-typed.com committed
582
583
584
                                AppTy
                                ~~~~~
We need to be pretty careful with AppTy to make sure we obey the
585
586
invariant that a TyConApp is always visibly so.  mkAppTy maintains the
invariant: use it.
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606

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).
607

608
-}
609

batterseapower's avatar
batterseapower committed
610
-- | Applies a type to another, as in e.g. @k a@
611
mkAppTy :: Type -> Type -> Type
612
613
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
614
615
616
617
618
619
620
621
        -- 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
622

623
mkAppTys :: Type -> [Type] -> Type
ian@well-typed.com's avatar
ian@well-typed.com committed
624
mkAppTys ty1                []   = ty1
625
626
627
mkAppTys (TyConApp tc tys1) tys2 = mkTyConApp tc (tys1 ++ tys2)
mkAppTys ty1                tys2 = foldl AppTy ty1 tys2

628
-------------
629
splitAppTy_maybe :: Type -> Maybe (Type, Type)
batterseapower's avatar
batterseapower committed
630
631
632
-- ^ 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!
633
splitAppTy_maybe ty | Just ty' <- coreView ty
ian@well-typed.com's avatar
ian@well-typed.com committed
634
                    = splitAppTy_maybe ty'
635
splitAppTy_maybe ty = repSplitAppTy_maybe ty
636

637
638
-------------
repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
ian@well-typed.com's avatar
ian@well-typed.com committed
639
-- ^ Does the AppTy split as in 'splitAppTy_maybe', but assumes that
batterseapower's avatar
batterseapower committed
640
-- any Core view stuff is already done
641
642
repSplitAppTy_maybe (ForAllTy (Anon ty1) ty2)
                                      = Just (TyConApp funTyCon [ty1], ty2)
643
repSplitAppTy_maybe (AppTy ty1 ty2)   = Just (ty1, ty2)
ian@well-typed.com's avatar
ian@well-typed.com committed
644
repSplitAppTy_maybe (TyConApp tc tys)
645
  | mightBeUnsaturatedTyCon tc || tys `lengthExceeds` tyConArity tc
646
647
  , Just (tys', ty') <- snocView tys
  = Just (TyConApp tc tys', ty')    -- Never create unsaturated type family apps!
648
repSplitAppTy_maybe _other = Nothing
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664

-- 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)
tcRepSplitAppTy_maybe (ForAllTy (Anon ty1) ty2)
  | 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
665
-------------
666
splitAppTy :: Type -> (Type, Type)
batterseapower's avatar
batterseapower committed
667
668
-- ^ Attempts to take a type application apart, as in 'splitAppTy_maybe',
-- and panics if this is not possible
669
splitAppTy ty = case splitAppTy_maybe ty of
ian@well-typed.com's avatar
ian@well-typed.com committed
670
671
                Just pr -> pr
                Nothing -> panic "splitAppTy"
672

673
-------------
674
splitAppTys :: Type -> (Type, [Type])
batterseapower's avatar
batterseapower committed
675
676
677
-- ^ 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.
678
splitAppTys ty = split ty ty []
679
  where
680
    split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
681
682
    split _       (AppTy ty arg)        args = split ty ty (arg:args)
    split _       (TyConApp tc tc_args) args
683
      = let -- keep type families saturated
684
685
            n | mightBeUnsaturatedTyCon tc = 0
              | otherwise                  = tyConArity tc
686
            (tc_args1, tc_args2) = splitAt n tc_args
687
688
        in
        (TyConApp tc tc_args1, tc_args2 ++ args)
689
    split _   (ForAllTy (Anon ty1) ty2) args = ASSERT( null args )
ian@well-typed.com's avatar
ian@well-typed.com committed
690
                                               (TyConApp funTyCon [], [ty1,ty2])
691
    split orig_ty _                     args = (orig_ty, args)
692

693
{-
694
                      LitTy
695
                      ~~~~~
696
-}
697

698
699
mkNumLitTy :: Integer -> Type
mkNumLitTy n = LitTy (NumTyLit n)
700

701
-- | Is this a numeric literal. We also look through type synonyms.
702
isNumLitTy :: Type -> Maybe Integer
703
isNumLitTy ty | Just ty1 <- coreView ty = isNumLitTy ty1
704
705
isNumLitTy (LitTy (NumTyLit n)) = Just n
isNumLitTy _                    = Nothing
706

707
708
709
mkStrLitTy :: FastString -> Type
mkStrLitTy s = LitTy (StrTyLit s)

710
-- | Is this a symbol literal. We also look through type synonyms.
711
isStrLitTy :: Type -> Maybe FastString
712
isStrLitTy ty | Just ty1 <- coreView ty = isStrLitTy ty1
713
714
isStrLitTy (LitTy (StrTyLit s)) = Just s
isStrLitTy _                    = Nothing
715

716
717
718

-- | Is this type a custom user error?
-- If so, give us the kind and the error message.
719
720
userTypeError_maybe :: Type -> Maybe Type
userTypeError_maybe t
721
722
723
724
  = 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`).

725
726
       ; guard (tyConName tc == errorMessageTypeErrorFamName)
       ; return msg }
727
728
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

-- | 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




758
{-
759
---------------------------------------------------------------------
ian@well-typed.com's avatar
ian@well-typed.com committed
760
761
                                FunTy
                                ~~~~~
762

763
764
Function types are represented with (ForAllTy (Anon ...) ...)
-}
765

ian@well-typed.com's avatar
ian@well-typed.com committed
766
isFunTy :: Type -> Bool
767
768
isFunTy ty = isJust (splitFunTy_maybe ty)

769
splitFunTy :: Type -> (Type, Type)
batterseapower's avatar
batterseapower committed
770
771
-- ^ Attempts to extract the argument and result types from a type, and
-- panics if that is not possible. See also 'splitFunTy_maybe'
772
splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
773
774
splitFunTy (ForAllTy (Anon arg) res)    = (arg, res)
splitFunTy other                        = pprPanic "splitFunTy" (ppr other)
775

776
splitFunTy_maybe :: Type -> Maybe (Type, Type)
batterseapower's avatar
batterseapower committed
777
-- ^ Attempts to extract the argument and result types from a type
778
splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
779
780
splitFunTy_maybe (ForAllTy (Anon arg) res) = Just (arg, res)
splitFunTy_maybe _                         = Nothing
781

782
splitFunTys :: Type -> ([Type], Type)
783
splitFunTys ty = split [] ty ty
784
  where
785
    split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
786
787
    split args _       (ForAllTy (Anon arg) res) = split (arg:args) res res
    split args orig_ty _                         = (reverse args, orig_ty)
788

789
splitFunTysN :: Int -> Type -> ([Type], Type)
batterseapower's avatar
batterseapower committed
790
-- ^ Split off exactly the given number argument types, and panics if that is not possible
791
splitFunTysN 0 ty = ([], ty)
simonpj@microsoft.com's avatar
Assert    
simonpj@microsoft.com committed
792
793
splitFunTysN n ty = ASSERT2( isFunTy ty, int n <+> ppr ty )
                    case splitFunTy ty of { (arg, res) ->
ian@well-typed.com's avatar
ian@well-typed.com committed
794
795
                    case splitFunTysN (n-1) res of { (args, res) ->
                    (arg:args, res) }}
796

797
funResultTy :: Type -> Type
batterseapower's avatar
batterseapower committed
798
-- ^ Extract the function result type and panic if that is not possible
799
800
801
802
funResultTy ty = piResultTy ty (pprPanic "funResultTy" (ppr ty))

-- | Essentially 'funResultTy' on kinds handling pi-types too
piResultTy :: Type -> Type -> Type
803
804
805
806
807
piResultTy ty arg | Just ty' <- coreView ty = piResultTy ty' arg
piResultTy (ForAllTy (Anon _) res)     _   = res
piResultTy (ForAllTy (Named tv _) res) arg = substTyWithUnchecked [tv] [arg] res
piResultTy ty arg                          = pprPanic "piResultTy"
                                                 (ppr ty $$ ppr arg)
808
809
810

-- | Fold 'piResultTy' over many types
piResultTys :: Type -> [Type] -> Type
811
piResultTys = foldl piResultTy
812
813

funArgTy :: Type -> Type
batterseapower's avatar
batterseapower committed
814
-- ^ Extract the function argument type and panic if that is not possible
815
funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
816
817
funArgTy (ForAllTy (Anon arg) _res) = arg
funArgTy ty                         = pprPanic "funArgTy" (ppr ty)
818

819
{-
820
---------------------------------------------------------------------
ian@well-typed.com's avatar
ian@well-typed.com committed
821
822
                                TyConApp
                                ~~~~~~~~
823
-}
824

Gabor Greif's avatar
Typo    
Gabor Greif committed
825
-- | A key function: builds a 'TyConApp' or 'FunTy' as appropriate to
826
827
828
829
-- its arguments.  Applies its arguments to the constructor from left to right.
mkTyConApp :: TyCon -> [Type] -> Type
mkTyConApp tycon tys
  | isFunTyCon tycon, [ty1,ty2] <- tys
830
  = ForAllTy (Anon ty1) ty2
831
832
833
834

  | otherwise
  = TyConApp tycon tys

835
836
837
838
-- splitTyConApp "looks through" synonyms, because they don't
-- mean a distinct type, but all other type-constructor applications
-- including functions are returned as Just ..

839
840
841
842
843
844
845
846
-- | Retrieve the tycon heading this type, if there is one. Does /not/
-- look through synonyms.
tyConAppTyConPicky_maybe :: Type -> Maybe TyCon
tyConAppTyConPicky_maybe (TyConApp tc _)       = Just tc
tyConAppTyConPicky_maybe (ForAllTy (Anon _) _) = Just funTyCon
tyConAppTyConPicky_maybe _                     = Nothing


batterseapower's avatar
batterseapower committed
847
-- | The same as @fst . splitTyConApp@
848
849
tyConAppTyCon_maybe :: Type -> Maybe TyCon
tyConAppTyCon_maybe ty | Just ty' <- coreView ty = tyConAppTyCon_maybe ty'
850
851
852
tyConAppTyCon_maybe (TyConApp tc _)       = Just tc
tyConAppTyCon_maybe (ForAllTy (Anon _) _) = Just funTyCon
tyConAppTyCon_maybe _                     = Nothing
853

854
tyConAppTyCon :: Type -> TyCon
855
tyConAppTyCon ty = tyConAppTyCon_maybe ty `orElse` pprPanic "tyConAppTyCon" (ppr ty)
856

batterseapower's avatar
batterseapower committed
857
-- | The same as @snd . splitTyConApp@
858
859
tyConAppArgs_maybe :: Type -> Maybe [Type]
tyConAppArgs_maybe ty | Just ty' <- coreView ty = tyConAppArgs_maybe ty'
860
861
862
tyConAppArgs_maybe (TyConApp _ tys)          = Just tys
tyConAppArgs_maybe (ForAllTy (Anon arg) res) = Just [arg,res]
tyConAppArgs_maybe _                         = Nothing
863

864
tyConAppArgs :: Type -> [Type]
865
tyConAppArgs ty = tyConAppArgs_maybe ty `orElse` pprPanic "tyConAppArgs" (ppr ty)
866

867
868
tyConAppArgN :: Int -> Type -> Type
-- Executing Nth
ian@well-typed.com's avatar
ian@well-typed.com committed
869
tyConAppArgN n ty
870
  = case tyConAppArgs_maybe ty of
871
      Just tys -> ASSERT2( n < length tys, ppr n <+> ppr tys ) tys `getNth` n
872
873
      Nothing  -> pprPanic "tyConAppArgN" (ppr n <+> ppr ty)

batterseapower's avatar
batterseapower committed
874
875
876
-- | Attempts to tease a type apart into a type constructor and the application
-- of a number of arguments to that constructor. Panics if that is not possible.
-- See also 'splitTyConApp_maybe'
877
878
splitTyConApp :: Type -> (TyCon, [Type])
splitTyConApp ty = case splitTyConApp_maybe ty of
ian@well-typed.com's avatar
ian@well-typed.com committed
879
880
                   Just stuff -> stuff
                   Nothing    -> pprPanic "splitTyConApp" (ppr ty)
881

batterseapower's avatar
batterseapower committed
882
883
-- | Attempts to tease a type apart into a type constructor and the application
-- of a number of arguments to that constructor
884
splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
885
splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty'
886
887
888
889
890
891
892
893
splitTyConApp_maybe ty                           = repSplitTyConApp_maybe ty

-- | Like 'splitTyConApp_maybe', but doesn't look through synonyms. This
-- assumes the synonyms have already been dealt with.
repSplitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
repSplitTyConApp_maybe (TyConApp tc tys)         = Just (tc, tys)
repSplitTyConApp_maybe (ForAllTy (Anon arg) res) = Just (funTyCon, [arg,res])
repSplitTyConApp_maybe _                         = Nothing
894

895
896
897
898
899
900
901
-- | Attempts to tease a list type apart and gives the type of the elements if
-- successful (looks through type synonyms)
splitListTyConApp_maybe :: Type -> Maybe Type
splitListTyConApp_maybe ty = case splitTyConApp_maybe ty of
  Just (tc,[e]) | tc == listTyCon -> Just e
  _other                          -> Nothing

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
902
903
904
905
906
907
908
909
910
911
912
913
914
915
-- | What is the role assigned to the next parameter of this type? Usually,
-- this will be 'Nominal', but if the type is a 'TyConApp', we may be able to
-- do better. The type does *not* have to be well-kinded when applied for this
-- to work!
nextRole :: Type -> Role
nextRole ty
  | Just (tc, tys) <- splitTyConApp_maybe ty
  , let num_tys = length tys
  , num_tys < tyConArity tc
  = tyConRoles tc `getNth` num_tys

  | otherwise
  = Nominal

916
newTyConInstRhs :: TyCon -> [Type] -> Type
ian@well-typed.com's avatar
ian@well-typed.com committed
917
-- ^ Unwrap one 'layer' of newtype on a type constructor and its
918
919
-- arguments, using an eta-reduced version of the @newtype@ if possible.
-- This requires tys to have at least @newTyConInstArity tycon@ elements.
ian@well-typed.com's avatar
ian@well-typed.com committed
920
newTyConInstRhs tycon tys
921
922
    = ASSERT2( tvs `leLength` tys, ppr tycon $$ ppr tys $$ ppr tvs )
      applyTysX tvs rhs tys
923
  where
924
    (tvs, rhs) = newTyConEtadRhs tycon
925

926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
{-
---------------------------------------------------------------------
                           CastTy
                           ~~~~~~
A casted type has its *kind* casted into something new.

Note [Weird typing rule for ForAllTy]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here is the (truncated) typing rule for the dependent ForAllTy:

inner : kind
------------------------------------
ForAllTy (Named tv vis) inner : kind

Note that neither the inner type nor for ForAllTy itself have to have
kind *! But, it means that we should push any kind casts through the
ForAllTy. The only trouble is avoiding capture.

-}

Simon Peyton Jones's avatar
Simon Peyton Jones committed
947
948
949
950
951
splitCastTy_maybe :: Type -> Maybe (Type, Coercion)
splitCastTy_maybe ty | Just ty' <- coreView ty = splitCastTy_maybe ty'
splitCastTy_maybe (CastTy ty co)               = Just (ty, co)
splitCastTy_maybe _                            = Nothing

952
953
954
955
-- | Make a 'CastTy'. The Coercion must be nominal. This function looks
-- at the entire structure of the type and coercion in an attempt to
-- maintain representation invariance (that is, any two types that are `eqType`
-- look the same). Be very wary of calling this in a loop.
956
957
958
959
960
961
962
963
964
965
966
967
968
mkCastTy :: Type -> Coercion -> Type
-- Running example:
--   T :: forall k1. k1 -> forall k2. k2 -> Bool -> Maybe k1 -> *
--   co :: * ~R X    (maybe X is a newtype around *)
--   ty = T Nat 3 Symbol "foo" True (Just 2)
--
-- We wish to "push" the cast down as far as possible. See also
-- Note [Pushing down casts] in TyCoRep. Here is where we end
-- up:
--
--   (T Nat 3 Symbol |> <Symbol> -> <Bool> -> <Maybe Nat> -> co)
--      "foo" True (Just 2)
--
969
970
971
972
973
974
975
mkCastTy ty co | isReflexiveCo co = ty
-- NB: Do the slow check here. This is important to keep the splitXXX
-- functions working properly. Otherwise, we may end up with something
-- like (((->) |> something_reflexive_but_not_obviously_so) biz baz)
-- fails under splitFunTy_maybe. This happened with the cheaper check
-- in test dependent/should_compile/dynamic-paper.

976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
mkCastTy (CastTy ty co1) co2 = mkCastTy ty (co1 `mkTransCo` co2)
-- See Note [Weird typing rule for ForAllTy]
mkCastTy (ForAllTy (Named tv vis) inner_ty) co
  = -- have to make sure that pushing the co in doesn't capture the bound var
    let fvs = tyCoVarsOfCo co
        empty_subst = mkEmptyTCvSubst (mkInScopeSet fvs)
        (subst, tv') = substTyVarBndr empty_subst tv
    in
    ForAllTy (Named tv' vis) (substTy subst inner_ty `mkCastTy` co)
mkCastTy ty co = -- NB: don't check if the coercion "from" type matches here;
                 -- there may be unzonked variables about
                 let result = split_apps [] ty co in
                 ASSERT2( CastTy ty co `eqType` result
                        , ppr ty <+> dcolon <+> ppr (typeKind ty) $$
                          ppr co <+> dcolon <+> ppr (coercionKind co) $$
                          ppr result <+> dcolon <+> ppr (typeKind result) )
                 result
  where
    -- split_apps breaks apart any type applications, so we can see how far down
    -- to push the cast
    split_apps args (AppTy t1 t2) co
      = split_apps (t2:args) t1 co
    split_apps args (TyConApp tc tc_args) co
      | mightBeUnsaturatedTyCon tc
      = affix_co (tyConKind tc) (mkTyConTy tc) (tc_args `chkAppend` args) co
      | otherwise -- not decomposable... but it may still be oversaturated
      = let (non_decomp_args, decomp_args) = splitAt (tyConArity tc) tc_args
            saturated_tc = mkTyConApp tc non_decomp_args
        in
        affix_co (typeKind saturated_tc) saturated_tc (decomp_args `chkAppend` args) co

    split_apps args (ForAllTy (Anon arg) res) co
      = affix_co (tyConKind funTyCon) (mkTyConTy funTyCon)
                 (arg : res : args) co
    split_apps args ty co
      = affix_co (typeKind ty) ty args co

    -- having broken everything apart, this figures out the point at which there
    -- are no more dependent quantifications, and puts the cast there
    affix_co _ ty [] co = no_double_casts ty co
    affix_co kind ty args co
      -- if kind contains any dependent quantifications, we can't push.
      -- apply arguments until it doesn't
      = let (bndrs, _inner_ki) = splitPiTys kind
            (no_dep_bndrs, some_dep_bndrs) = spanEnd isAnonBinder bndrs
            (some_dep_args, rest_args) = splitAtList some_dep_bndrs args
niteria's avatar
niteria committed
1022
            dep_subst = zipTyBinderSubst some_dep_bndrs some_dep_args
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
            used_no_dep_bndrs = takeList rest_args no_dep_bndrs
            rest_arg_tys = substTys dep_subst (map binderType used_no_dep_bndrs)
            co' = mkFunCos Nominal
                           (map (mkReflCo Nominal) rest_arg_tys)
                           co
        in
        ((ty `mkAppTys` some_dep_args) `no_double_casts` co') `mkAppTys` rest_args

    no_double_casts (CastTy ty co1) co2 = CastTy ty (co1 `mkTransCo` co2)
    no_double_casts ty              co  = CastTy ty co

{-
--------------------------------------------------------------------
                            CoercionTy
                            ~~~~~~~~~~
CoercionTy allows us to inject coercions into types. A CoercionTy
should appear only in the right-hand side of an application.
-}

mkCoercionTy :: Coercion -> Type
mkCoercionTy = CoercionTy

isCoercionTy :: Type -> Bool
isCoercionTy (CoercionTy _) = True
isCoercionTy _              = False

isCoercionTy_maybe :: Type -> Maybe Coercion
isCoercionTy_maybe (CoercionTy co) = Just co
isCoercionTy_maybe _               = Nothing

stripCoercionTy :: Type -> Coercion
stripCoercionTy (CoercionTy co) = co
stripCoercionTy ty              = pprPanic "stripCoercionTy" (ppr ty)

1057
{-
1058
---------------------------------------------------------------------
ian@well-typed.com's avatar
ian@well-typed.com committed
1059
1060
                                SynTy
                                ~~~~~
1061
1062
1063
1064

Notes on type synonyms
~~~~~~~~~~~~~~~~~~~~~~
The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
Krzysztof Gogolewski's avatar
Typos    
Krzysztof Gogolewski committed
1065
to return type synonyms wherever possible. Thus
1066

ian@well-typed.com's avatar
ian@well-typed.com committed
1067
        type Foo a = a -> a
1068

ian@well-typed.com's avatar
ian@well-typed.com committed
1069
1070
1071
we want
        splitFunTys (a -> Foo a) = ([a], Foo a)
not                                ([a], a -> a)
1072

ian@well-typed.com's avatar
ian@well-typed.com committed
1073
The reason is that we then get better (shorter) type signatures in
1074
interfaces.  Notably this plays a role in tcTySigs in TcBinds.hs.
1075
1076


ian@well-typed.com's avatar
ian@well-typed.com committed
1077
1078
                Representation types
                ~~~~~~~~~~~~~~~~~~~~
1079

1080
1081
Note [Nullary unboxed tuple]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1082
We represent the nullary unboxed tuple as the unary (but void) type
1083
Void#.  The reason for this is that the ReprArity is never
1084
1085
1086
1087
1088
1089
less than the Arity (as it would otherwise be for a function type like
(# #) -> Int).

As a result, ReprArity is always strictly positive if Arity is. This
is important because it allows us to distinguish at runtime between a
thunk and a function takes a nullary unboxed tuple as an argument!
1090
-}
1091
1092
1093
1094
1095
1096

type UnaryType = Type

data RepType = UbxTupleRep [UnaryType] -- INVARIANT: never an empty list (see Note [Nullary unboxed tuple])
             | UnaryRep UnaryType

1097
instance Outputable RepType where
1098
1099
  ppr (UbxTupleRep tys) = text "UbxTupleRep" <+> ppr tys
  ppr (UnaryRep ty)     = text "UnaryRep"    <+> ppr ty
1100

1101
1102