Replace most occurences of foldl with foldl'.
[ghc.git] / compiler / types / Type.hs
1 -- (c) The University of Glasgow 2006
2 -- (c) The GRASP/AQUA Project, Glasgow University, 1998
3 --
4 -- Type - public interface
5
6 {-# LANGUAGE CPP, FlexibleContexts #-}
7 {-# OPTIONS_GHC -fno-warn-orphans #-}
8
9 -- | Main functions for manipulating types and type-related things
10 module Type (
11 -- Note some of this is just re-exports from TyCon..
12
13 -- * Main data types representing Types
14 -- $type_classification
15
16 -- $representation_types
17 TyThing(..), Type, ArgFlag(..), KindOrType, PredType, ThetaType,
18 Var, TyVar, isTyVar, TyCoVar, TyBinder, TyVarBinder,
19 KnotTied,
20
21 -- ** Constructing and deconstructing types
22 mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe, repGetTyVar_maybe,
23 getCastedTyVar_maybe, tyVarKind,
24
25 mkAppTy, mkAppTys, splitAppTy, splitAppTys, repSplitAppTys,
26 splitAppTy_maybe, repSplitAppTy_maybe, tcRepSplitAppTy_maybe,
27
28 mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe,
29 splitFunTys, funResultTy, funArgTy,
30
31 mkTyConApp, mkTyConTy,
32 tyConAppTyCon_maybe, tyConAppTyConPicky_maybe,
33 tyConAppArgs_maybe, tyConAppTyCon, tyConAppArgs,
34 splitTyConApp_maybe, splitTyConApp, tyConAppArgN, nextRole,
35 tcRepSplitTyConApp_maybe, tcSplitTyConApp_maybe,
36 splitListTyConApp_maybe,
37 repSplitTyConApp_maybe,
38
39 mkForAllTy, mkForAllTys, mkInvForAllTys, mkSpecForAllTys,
40 mkVisForAllTys, mkInvForAllTy,
41 splitForAllTys, splitForAllTyVarBndrs,
42 splitForAllTy_maybe, splitForAllTy,
43 splitPiTy_maybe, splitPiTy, splitPiTys,
44 mkPiTy, mkPiTys, mkTyConBindersPreferAnon,
45 mkLamType, mkLamTypes,
46 piResultTy, piResultTys,
47 applyTysX, dropForAlls,
48
49 mkNumLitTy, isNumLitTy,
50 mkStrLitTy, isStrLitTy,
51 isLitTy,
52
53 getRuntimeRep_maybe, getRuntimeRepFromKind_maybe,
54
55 mkCastTy, mkCoercionTy, splitCastTy_maybe,
56
57 userTypeError_maybe, pprUserTypeErrorTy,
58
59 coAxNthLHS,
60 stripCoercionTy, splitCoercionType_maybe,
61
62 splitPiTysInvisible, filterOutInvisibleTypes,
63 partitionInvisibles,
64 synTyConResKind,
65
66 modifyJoinResTy, setJoinResTy,
67
68 -- Analyzing types
69 TyCoMapper(..), mapType, mapCoercion,
70
71 -- (Newtypes)
72 newTyConInstRhs,
73
74 -- Pred types
75 mkFamilyTyConApp,
76 isDictLikeTy,
77 mkPrimEqPred, mkReprPrimEqPred, mkPrimEqPredRole,
78 equalityTyCon,
79 mkHeteroPrimEqPred, mkHeteroReprPrimEqPred,
80 mkClassPred,
81 isClassPred, isEqPred, isNomEqPred,
82 isIPPred, isIPPred_maybe, isIPTyCon, isIPClass,
83 isCTupleClass,
84
85 -- Deconstructing predicate types
86 PredTree(..), EqRel(..), eqRelRole, classifyPredType,
87 getClassPredTys, getClassPredTys_maybe,
88 getEqPredTys, getEqPredTys_maybe, getEqPredRole,
89 predTypeEqRel,
90
91 -- ** Binders
92 sameVis,
93 mkTyVarBinder, mkTyVarBinders,
94 mkAnonBinder,
95 isAnonTyBinder, isNamedTyBinder,
96 binderVar, binderVars, binderKind, binderArgFlag,
97 tyBinderType, tyBinderVar_maybe,
98 binderRelevantType_maybe, caseBinder,
99 isVisibleArgFlag, isInvisibleArgFlag, isVisibleBinder, isInvisibleBinder,
100 tyConBindersTyBinders,
101
102 -- ** Common type constructors
103 funTyCon,
104
105 -- ** Predicates on types
106 isTyVarTy, isFunTy, isDictTy, isPredTy, isCoercionTy,
107 isCoercionTy_maybe, isCoercionType, isForAllTy,
108 isPiTy, isTauTy, isFamFreeTy,
109
110 isValidJoinPointType,
111
112 -- (Lifting and boxity)
113 isLiftedType_maybe, isUnliftedType, isUnboxedTupleType, isUnboxedSumType,
114 isAlgType, isDataFamilyAppType,
115 isPrimitiveType, isStrictType,
116 isRuntimeRepTy, isRuntimeRepVar, isRuntimeRepKindedTy,
117 dropRuntimeRepArgs,
118 getRuntimeRep, getRuntimeRepFromKind,
119
120 -- * Main data types representing Kinds
121 Kind,
122
123 -- ** Finding the kind of a type
124 typeKind, isTypeLevPoly, resultIsLevPoly,
125 tcIsLiftedTypeKind, tcIsConstraintKind, tcReturnsConstraintKind,
126
127 -- ** Common Kind
128 liftedTypeKind,
129
130 -- * Type free variables
131 tyCoFVsOfType, tyCoFVsBndr,
132 tyCoVarsOfType, tyCoVarsOfTypes,
133 tyCoVarsOfTypeDSet,
134 coVarsOfType,
135 coVarsOfTypes, closeOverKinds, closeOverKindsList,
136 noFreeVarsOfType,
137 splitVisVarsOfType, splitVisVarsOfTypes,
138 expandTypeSynonyms,
139 typeSize, occCheckExpand,
140
141 -- * Well-scoped lists of variables
142 dVarSetElemsWellScoped, toposortTyVars, tyCoVarsOfTypeWellScoped,
143 tyCoVarsOfTypesWellScoped,
144
145 -- * Type comparison
146 eqType, eqTypeX, eqTypes, nonDetCmpType, nonDetCmpTypes, nonDetCmpTypeX,
147 nonDetCmpTypesX, nonDetCmpTc,
148 eqVarBndrs,
149
150 -- * Forcing evaluation of types
151 seqType, seqTypes,
152
153 -- * Other views onto Types
154 coreView, tcView,
155
156 tyConsOfType,
157
158 -- * Main type substitution data types
159 TvSubstEnv, -- Representation widely visible
160 TCvSubst(..), -- Representation visible to a few friends
161
162 -- ** Manipulating type substitutions
163 emptyTvSubstEnv, emptyTCvSubst, mkEmptyTCvSubst,
164
165 mkTCvSubst, zipTvSubst, mkTvSubstPrs,
166 notElemTCvSubst,
167 getTvSubstEnv, setTvSubstEnv,
168 zapTCvSubst, getTCvInScope, getTCvSubstRangeFVs,
169 extendTCvInScope, extendTCvInScopeList, extendTCvInScopeSet,
170 extendTCvSubst, extendCvSubst,
171 extendTvSubst, extendTvSubstBinderAndInScope,
172 extendTvSubstList, extendTvSubstAndInScope,
173 extendTvSubstWithClone,
174 isInScope, composeTCvSubstEnv, composeTCvSubst, zipTyEnv, zipCoEnv,
175 isEmptyTCvSubst, unionTCvSubst,
176
177 -- ** Performing substitution on types and kinds
178 substTy, substTys, substTyWith, substTysWith, substTheta,
179 substTyAddInScope,
180 substTyUnchecked, substTysUnchecked, substThetaUnchecked,
181 substTyWithUnchecked,
182 substCoUnchecked, substCoWithUnchecked,
183 substTyVarBndr, substTyVarBndrs, substTyVar, substTyVars,
184 cloneTyVarBndr, cloneTyVarBndrs, lookupTyVar,
185
186 -- * Pretty-printing
187 pprType, pprParendType, pprPrecType,
188 pprTypeApp, pprTyThingCategory, pprShortTyThing,
189 pprTvBndr, pprTvBndrs, pprForAll, pprUserForAll,
190 pprSigmaType, ppSuggestExplicitKinds,
191 pprTheta, pprThetaArrowTy, pprClassPred,
192 pprKind, pprParendKind, pprSourceTyCon,
193 PprPrec(..), topPrec, sigPrec, opPrec, funPrec, appPrec, maybeParen,
194 pprTyVar, pprTyVars,
195 pprWithTYPE,
196
197 -- * Tidying type related things up for printing
198 tidyType, tidyTypes,
199 tidyOpenType, tidyOpenTypes,
200 tidyOpenKind,
201 tidyTyCoVarBndr, tidyTyCoVarBndrs, tidyFreeTyCoVars,
202 tidyOpenTyCoVar, tidyOpenTyCoVars,
203 tidyTyVarOcc,
204 tidyTopType,
205 tidyKind,
206 tidyTyVarBinder, tidyTyVarBinders
207 ) where
208
209 #include "HsVersions.h"
210
211 import GhcPrelude
212
213 import BasicTypes
214
215 -- We import the representation and primitive functions from TyCoRep.
216 -- Many things are reexported, but not the representation!
217
218 import Kind
219 import TyCoRep
220
221 -- friends:
222 import Var
223 import VarEnv
224 import VarSet
225 import UniqSet
226
227 import Class
228 import TyCon
229 import TysPrim
230 import {-# SOURCE #-} TysWiredIn ( listTyCon, typeNatKind
231 , typeSymbolKind, liftedTypeKind )
232 import PrelNames
233 import CoAxiom
234 import {-# SOURCE #-} Coercion( mkNomReflCo, mkGReflCo, mkReflCo
235 , mkTyConAppCo, mkAppCo, mkCoVarCo, mkAxiomRuleCo
236 , mkForAllCo, mkFunCo, mkAxiomInstCo, mkUnivCo
237 , mkSymCo, mkTransCo, mkNthCo, mkLRCo, mkInstCo
238 , mkKindCo, mkSubCo, mkFunCo, mkAxiomInstCo
239 , decomposePiCos, coercionKind, coercionType
240 , isReflexiveCo, seqCo )
241
242 -- others
243 import Util
244 import Outputable
245 import FastString
246 import Pair
247 import DynFlags ( gopt_set, GeneralFlag(Opt_PrintExplicitRuntimeReps) )
248 import ListSetOps
249 import Digraph
250 import Unique ( nonDetCmpUnique )
251
252 import Maybes ( orElse )
253 import Data.Maybe ( isJust, mapMaybe )
254 import Control.Monad ( guard )
255 import Control.Arrow ( first, second )
256
257 -- $type_classification
258 -- #type_classification#
259 --
260 -- Types are one of:
261 --
262 -- [Unboxed] Iff its representation is other than a pointer
263 -- Unboxed types are also unlifted.
264 --
265 -- [Lifted] Iff it has bottom as an element.
266 -- Closures always have lifted types: i.e. any
267 -- let-bound identifier in Core must have a lifted
268 -- type. Operationally, a lifted object is one that
269 -- can be entered.
270 -- Only lifted types may be unified with a type variable.
271 --
272 -- [Algebraic] Iff it is a type with one or more constructors, whether
273 -- declared with @data@ or @newtype@.
274 -- An algebraic type is one that can be deconstructed
275 -- with a case expression. This is /not/ the same as
276 -- lifted types, because we also include unboxed
277 -- tuples in this classification.
278 --
279 -- [Data] Iff it is a type declared with @data@, or a boxed tuple.
280 --
281 -- [Primitive] Iff it is a built-in type that can't be expressed in Haskell.
282 --
283 -- Currently, all primitive types are unlifted, but that's not necessarily
284 -- the case: for example, @Int@ could be primitive.
285 --
286 -- Some primitive types are unboxed, such as @Int#@, whereas some are boxed
287 -- but unlifted (such as @ByteArray#@). The only primitive types that we
288 -- classify as algebraic are the unboxed tuples.
289 --
290 -- Some examples of type classifications that may make this a bit clearer are:
291 --
292 -- @
293 -- Type primitive boxed lifted algebraic
294 -- -----------------------------------------------------------------------------
295 -- Int# Yes No No No
296 -- ByteArray# Yes Yes No No
297 -- (\# a, b \#) Yes No No Yes
298 -- (\# a | b \#) Yes No No Yes
299 -- ( a, b ) No Yes Yes Yes
300 -- [a] No Yes Yes Yes
301 -- @
302
303 -- $representation_types
304 -- A /source type/ is a type that is a separate type as far as the type checker is
305 -- concerned, but which has a more low-level representation as far as Core-to-Core
306 -- passes and the rest of the back end is concerned.
307 --
308 -- You don't normally have to worry about this, as the utility functions in
309 -- this module will automatically convert a source into a representation type
310 -- if they are spotted, to the best of it's abilities. If you don't want this
311 -- to happen, use the equivalent functions from the "TcType" module.
312
313 {-
314 ************************************************************************
315 * *
316 Type representation
317 * *
318 ************************************************************************
319
320 Note [coreView vs tcView]
321 ~~~~~~~~~~~~~~~~~~~~~~~~~
322 So far as the typechecker is concerned, 'Constraint' and 'TYPE LiftedRep' are distinct kinds.
323
324 But in Core these two are treated as identical.
325
326 We implement this by making 'coreView' convert 'Constraint' to 'TYPE LiftedRep' on the fly.
327 The function tcView (used in the type checker) does not do this.
328
329 See also Trac #11715, which tracks removing this inconsistency.
330
331 -}
332
333 -- | Gives the typechecker view of a type. This unwraps synonyms but
334 -- leaves 'Constraint' alone. c.f. coreView, which turns Constraint into
335 -- TYPE LiftedRep. Returns Nothing if no unwrapping happens.
336 -- See also Note [coreView vs tcView]
337 {-# INLINE tcView #-}
338 tcView :: Type -> Maybe Type
339 tcView (TyConApp tc tys) | Just (tenv, rhs, tys') <- expandSynTyCon_maybe tc tys
340 = Just (mkAppTys (substTy (mkTvSubstPrs tenv) rhs) tys')
341 -- The free vars of 'rhs' should all be bound by 'tenv', so it's
342 -- ok to use 'substTy' here.
343 -- See also Note [The substitution invariant] in TyCoRep.
344 -- Its important to use mkAppTys, rather than (foldl AppTy),
345 -- because the function part might well return a
346 -- partially-applied type constructor; indeed, usually will!
347 tcView _ = Nothing
348
349 {-# INLINE coreView #-}
350 coreView :: Type -> Maybe Type
351 -- ^ This function Strips off the /top layer only/ of a type synonym
352 -- application (if any) its underlying representation type.
353 -- Returns Nothing if there is nothing to look through.
354 -- This function considers 'Constraint' to be a synonym of @TYPE LiftedRep@.
355 --
356 -- By being non-recursive and inlined, this case analysis gets efficiently
357 -- joined onto the case analysis that the caller is already doing
358 coreView ty@(TyConApp tc tys)
359 | Just (tenv, rhs, tys') <- expandSynTyCon_maybe tc tys
360 = Just (mkAppTys (substTy (mkTvSubstPrs tenv) rhs) tys')
361 -- This equation is exactly like tcView
362
363 -- At the Core level, Constraint = Type
364 -- See Note [coreView vs tcView]
365 | isConstraintKindCon tc
366 = ASSERT2( null tys, ppr ty )
367 Just liftedTypeKind
368
369 coreView _ = Nothing
370
371 -----------------------------------------------
372 expandTypeSynonyms :: Type -> Type
373 -- ^ Expand out all type synonyms. Actually, it'd suffice to expand out
374 -- just the ones that discard type variables (e.g. type Funny a = Int)
375 -- But we don't know which those are currently, so we just expand all.
376 --
377 -- 'expandTypeSynonyms' only expands out type synonyms mentioned in the type,
378 -- not in the kinds of any TyCon or TyVar mentioned in the type.
379 --
380 -- Keep this synchronized with 'synonymTyConsOfType'
381 expandTypeSynonyms ty
382 = go (mkEmptyTCvSubst in_scope) ty
383 where
384 in_scope = mkInScopeSet (tyCoVarsOfType ty)
385
386 go subst (TyConApp tc tys)
387 | Just (tenv, rhs, tys') <- expandSynTyCon_maybe tc expanded_tys
388 = let subst' = mkTvSubst in_scope (mkVarEnv tenv)
389 -- Make a fresh substitution; rhs has nothing to
390 -- do with anything that has happened so far
391 -- NB: if you make changes here, be sure to build an
392 -- /idempotent/ substitution, even in the nested case
393 -- type T a b = a -> b
394 -- type S x y = T y x
395 -- (Trac #11665)
396 in mkAppTys (go subst' rhs) tys'
397 | otherwise
398 = TyConApp tc expanded_tys
399 where
400 expanded_tys = (map (go subst) tys)
401
402 go _ (LitTy l) = LitTy l
403 go subst (TyVarTy tv) = substTyVar subst tv
404 go subst (AppTy t1 t2) = mkAppTy (go subst t1) (go subst t2)
405 go subst (FunTy arg res)
406 = mkFunTy (go subst arg) (go subst res)
407 go subst (ForAllTy (TvBndr tv vis) t)
408 = let (subst', tv') = substTyVarBndrUsing go subst tv in
409 ForAllTy (TvBndr tv' vis) (go subst' t)
410 go subst (CastTy ty co) = mkCastTy (go subst ty) (go_co subst co)
411 go subst (CoercionTy co) = mkCoercionTy (go_co subst co)
412
413 go_mco _ MRefl = MRefl
414 go_mco subst (MCo co) = MCo (go_co subst co)
415
416 go_co subst (Refl ty)
417 = mkNomReflCo (go subst ty)
418 go_co subst (GRefl r ty mco)
419 = mkGReflCo r (go subst ty) (go_mco subst mco)
420 -- NB: coercions are always expanded upon creation
421 go_co subst (TyConAppCo r tc args)
422 = mkTyConAppCo r tc (map (go_co subst) args)
423 go_co subst (AppCo co arg)
424 = mkAppCo (go_co subst co) (go_co subst arg)
425 go_co subst (ForAllCo tv kind_co co)
426 = let (subst', tv', kind_co') = go_cobndr subst tv kind_co in
427 mkForAllCo tv' kind_co' (go_co subst' co)
428 go_co subst (FunCo r co1 co2)
429 = mkFunCo r (go_co subst co1) (go_co subst co2)
430 go_co subst (CoVarCo cv)
431 = substCoVar subst cv
432 go_co subst (AxiomInstCo ax ind args)
433 = mkAxiomInstCo ax ind (map (go_co subst) args)
434 go_co subst (UnivCo p r t1 t2)
435 = mkUnivCo (go_prov subst p) r (go subst t1) (go subst t2)
436 go_co subst (SymCo co)
437 = mkSymCo (go_co subst co)
438 go_co subst (TransCo co1 co2)
439 = mkTransCo (go_co subst co1) (go_co subst co2)
440 go_co subst (NthCo r n co)
441 = mkNthCo r n (go_co subst co)
442 go_co subst (LRCo lr co)
443 = mkLRCo lr (go_co subst co)
444 go_co subst (InstCo co arg)
445 = mkInstCo (go_co subst co) (go_co subst arg)
446 go_co subst (KindCo co)
447 = mkKindCo (go_co subst co)
448 go_co subst (SubCo co)
449 = mkSubCo (go_co subst co)
450 go_co subst (AxiomRuleCo ax cs)
451 = AxiomRuleCo ax (map (go_co subst) cs)
452 go_co _ (HoleCo h)
453 = pprPanic "expandTypeSynonyms hit a hole" (ppr h)
454
455 go_prov _ UnsafeCoerceProv = UnsafeCoerceProv
456 go_prov subst (PhantomProv co) = PhantomProv (go_co subst co)
457 go_prov subst (ProofIrrelProv co) = ProofIrrelProv (go_co subst co)
458 go_prov _ p@(PluginProv _) = p
459
460 -- the "False" and "const" are to accommodate the type of
461 -- substForAllCoBndrUsing, which is general enough to
462 -- handle coercion optimization (which sometimes swaps the
463 -- order of a coercion)
464 go_cobndr subst = substForAllCoBndrUsing False (go_co subst) subst
465
466 {-
467 ************************************************************************
468 * *
469 Analyzing types
470 * *
471 ************************************************************************
472
473 These functions do a map-like operation over types, performing some operation
474 on all variables and binding sites. Primarily used for zonking.
475
476 Note [Efficiency for mapCoercion ForAllCo case]
477 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
478 As noted in Note [Forall coercions] in TyCoRep, a ForAllCo is a bit redundant.
479 It stores a TyVar and a Coercion, where the kind of the TyVar always matches
480 the left-hand kind of the coercion. This is convenient lots of the time, but
481 not when mapping a function over a coercion.
482
483 The problem is that tcm_tybinder will affect the TyVar's kind and
484 mapCoercion will affect the Coercion, and we hope that the results will be
485 the same. Even if they are the same (which should generally happen with
486 correct algorithms), then there is an efficiency issue. In particular,
487 this problem seems to make what should be a linear algorithm into a potentially
488 exponential one. But it's only going to be bad in the case where there's
489 lots of foralls in the kinds of other foralls. Like this:
490
491 forall a : (forall b : (forall c : ...). ...). ...
492
493 This construction seems unlikely. So we'll do the inefficient, easy way
494 for now.
495
496 Note [Specialising mappers]
497 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
498 These INLINABLE pragmas are indispensable. mapType/mapCoercion are used
499 to implement zonking, and it's vital that they get specialised to the TcM
500 monad. This specialisation happens automatically (that is, without a
501 SPECIALISE pragma) as long as the definitions are INLINABLE. For example,
502 this one change made a 20% allocation difference in perf/compiler/T5030.
503
504 -}
505
506 -- | This describes how a "map" operation over a type/coercion should behave
507 data TyCoMapper env m
508 = TyCoMapper
509 { tcm_smart :: Bool -- ^ Should the new type be created with smart
510 -- constructors?
511 , tcm_tyvar :: env -> TyVar -> m Type
512 , tcm_covar :: env -> CoVar -> m Coercion
513 , tcm_hole :: env -> CoercionHole -> m Coercion
514 -- ^ What to do with coercion holes.
515 -- See Note [Coercion holes] in TyCoRep.
516
517 , tcm_tybinder :: env -> TyVar -> ArgFlag -> m (env, TyVar)
518 -- ^ The returned env is used in the extended scope
519
520 , tcm_tycon :: TyCon -> m TyCon
521 -- ^ This is used only to turn 'TcTyCon's into 'TyCon's.
522 -- See Note [Type checking recursive type and class declarations]
523 -- in TcTyClsDecls
524 }
525
526 {-# INLINABLE mapType #-} -- See Note [Specialising mappers]
527 mapType :: Monad m => TyCoMapper env m -> env -> Type -> m Type
528 mapType mapper@(TyCoMapper { tcm_smart = smart, tcm_tyvar = tyvar
529 , tcm_tybinder = tybinder, tcm_tycon = tycon })
530 env ty
531 = go ty
532 where
533 go (TyVarTy tv) = tyvar env tv
534 go (AppTy t1 t2) = mkappty <$> go t1 <*> go t2
535 go t@(TyConApp tc []) | not (isTcTyCon tc)
536 = return t -- avoid allocation in this exceedingly
537 -- common case (mostly, for *)
538 go (TyConApp tc tys)
539 = do { tc' <- tycon tc
540 ; mktyconapp tc' <$> mapM go tys }
541 go (FunTy arg res) = FunTy <$> go arg <*> go res
542 go (ForAllTy (TvBndr tv vis) inner)
543 = do { (env', tv') <- tybinder env tv vis
544 ; inner' <- mapType mapper env' inner
545 ; return $ ForAllTy (TvBndr tv' vis) inner' }
546 go ty@(LitTy {}) = return ty
547 go (CastTy ty co) = mkcastty <$> go ty <*> mapCoercion mapper env co
548 go (CoercionTy co) = CoercionTy <$> mapCoercion mapper env co
549
550 (mktyconapp, mkappty, mkcastty)
551 | smart = (mkTyConApp, mkAppTy, mkCastTy)
552 | otherwise = (TyConApp, AppTy, CastTy)
553
554 {-# INLINABLE mapCoercion #-} -- See Note [Specialising mappers]
555 mapCoercion :: Monad m
556 => TyCoMapper env m -> env -> Coercion -> m Coercion
557 mapCoercion mapper@(TyCoMapper { tcm_smart = smart, tcm_covar = covar
558 , tcm_hole = cohole, tcm_tybinder = tybinder
559 , tcm_tycon = tycon })
560 env co
561 = go co
562 where
563 go_mco MRefl = return MRefl
564 go_mco (MCo co) = MCo <$> (go co)
565
566 go (Refl ty) = Refl <$> mapType mapper env ty
567 go (GRefl r ty mco) = mkgreflco r <$> mapType mapper env ty <*> (go_mco mco)
568 go (TyConAppCo r tc args)
569 = do { tc' <- tycon tc
570 ; mktyconappco r tc' <$> mapM go args }
571 go (AppCo c1 c2) = mkappco <$> go c1 <*> go c2
572 go (ForAllCo tv kind_co co)
573 = do { kind_co' <- go kind_co
574 ; (env', tv') <- tybinder env tv Inferred
575 ; co' <- mapCoercion mapper env' co
576 ; return $ mkforallco tv' kind_co' co' }
577 -- See Note [Efficiency for mapCoercion ForAllCo case]
578 go (FunCo r c1 c2) = mkFunCo r <$> go c1 <*> go c2
579 go (CoVarCo cv) = covar env cv
580 go (AxiomInstCo ax i args)
581 = mkaxiominstco ax i <$> mapM go args
582 go (HoleCo hole) = cohole env hole
583 go (UnivCo p r t1 t2)
584 = mkunivco <$> go_prov p <*> pure r
585 <*> mapType mapper env t1 <*> mapType mapper env t2
586 go (SymCo co) = mksymco <$> go co
587 go (TransCo c1 c2) = mktransco <$> go c1 <*> go c2
588 go (AxiomRuleCo r cos) = AxiomRuleCo r <$> mapM go cos
589 go (NthCo r i co) = mknthco r i <$> go co
590 go (LRCo lr co) = mklrco lr <$> go co
591 go (InstCo co arg) = mkinstco <$> go co <*> go arg
592 go (KindCo co) = mkkindco <$> go co
593 go (SubCo co) = mksubco <$> go co
594
595 go_prov UnsafeCoerceProv = return UnsafeCoerceProv
596 go_prov (PhantomProv co) = PhantomProv <$> go co
597 go_prov (ProofIrrelProv co) = ProofIrrelProv <$> go co
598 go_prov p@(PluginProv _) = return p
599
600 ( mktyconappco, mkappco, mkaxiominstco, mkunivco
601 , mksymco, mktransco, mknthco, mklrco, mkinstco
602 , mkkindco, mksubco, mkforallco, mkgreflco)
603 | smart
604 = ( mkTyConAppCo, mkAppCo, mkAxiomInstCo, mkUnivCo
605 , mkSymCo, mkTransCo, mkNthCo, mkLRCo, mkInstCo
606 , mkKindCo, mkSubCo, mkForAllCo, mkGReflCo )
607 | otherwise
608 = ( TyConAppCo, AppCo, AxiomInstCo, UnivCo
609 , SymCo, TransCo, NthCo, LRCo, InstCo
610 , KindCo, SubCo, ForAllCo, GRefl )
611
612 {-
613 ************************************************************************
614 * *
615 \subsection{Constructor-specific functions}
616 * *
617 ************************************************************************
618
619
620 ---------------------------------------------------------------------
621 TyVarTy
622 ~~~~~~~
623 -}
624
625 -- | Attempts to obtain the type variable underlying a 'Type', and panics with the
626 -- given message if this is not a type variable type. See also 'getTyVar_maybe'
627 getTyVar :: String -> Type -> TyVar
628 getTyVar msg ty = case getTyVar_maybe ty of
629 Just tv -> tv
630 Nothing -> panic ("getTyVar: " ++ msg)
631
632 isTyVarTy :: Type -> Bool
633 isTyVarTy ty = isJust (getTyVar_maybe ty)
634
635 -- | Attempts to obtain the type variable underlying a 'Type'
636 getTyVar_maybe :: Type -> Maybe TyVar
637 getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
638 | otherwise = repGetTyVar_maybe ty
639
640 -- | If the type is a tyvar, possibly under a cast, returns it, along
641 -- with the coercion. Thus, the co is :: kind tv ~N kind type
642 getCastedTyVar_maybe :: Type -> Maybe (TyVar, CoercionN)
643 getCastedTyVar_maybe ty | Just ty' <- coreView ty = getCastedTyVar_maybe ty'
644 getCastedTyVar_maybe (CastTy (TyVarTy tv) co) = Just (tv, co)
645 getCastedTyVar_maybe (TyVarTy tv)
646 = Just (tv, mkReflCo Nominal (tyVarKind tv))
647 getCastedTyVar_maybe _ = Nothing
648
649 -- | Attempts to obtain the type variable underlying a 'Type', without
650 -- any expansion
651 repGetTyVar_maybe :: Type -> Maybe TyVar
652 repGetTyVar_maybe (TyVarTy tv) = Just tv
653 repGetTyVar_maybe _ = Nothing
654
655 {-
656 ---------------------------------------------------------------------
657 AppTy
658 ~~~~~
659 We need to be pretty careful with AppTy to make sure we obey the
660 invariant that a TyConApp is always visibly so. mkAppTy maintains the
661 invariant: use it.
662
663 Note [Decomposing fat arrow c=>t]
664 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
665 Can we unify (a b) with (Eq a => ty)? If we do so, we end up with
666 a partial application like ((=>) Eq a) which doesn't make sense in
667 source Haskell. In contrast, we *can* unify (a b) with (t1 -> t2).
668 Here's an example (Trac #9858) of how you might do it:
669 i :: (Typeable a, Typeable b) => Proxy (a b) -> TypeRep
670 i p = typeRep p
671
672 j = i (Proxy :: Proxy (Eq Int => Int))
673 The type (Proxy (Eq Int => Int)) is only accepted with -XImpredicativeTypes,
674 but suppose we want that. But then in the call to 'i', we end
675 up decomposing (Eq Int => Int), and we definitely don't want that.
676
677 This really only applies to the type checker; in Core, '=>' and '->'
678 are the same, as are 'Constraint' and '*'. But for now I've put
679 the test in repSplitAppTy_maybe, which applies throughout, because
680 the other calls to splitAppTy are in Unify, which is also used by
681 the type checker (e.g. when matching type-function equations).
682
683 -}
684
685 -- | Applies a type to another, as in e.g. @k a@
686 mkAppTy :: Type -> Type -> Type
687 -- See Note [Respecting definitional equality], invariant (EQ1).
688 mkAppTy (CastTy fun_ty co) arg_ty
689 | ([arg_co], res_co) <- decomposePiCos co (coercionKind co) [arg_ty]
690 = (fun_ty `mkAppTy` (arg_ty `mkCastTy` arg_co)) `mkCastTy` res_co
691
692 mkAppTy (TyConApp tc tys) ty2 = mkTyConApp tc (tys ++ [ty2])
693 mkAppTy ty1 ty2 = AppTy ty1 ty2
694 -- Note that the TyConApp could be an
695 -- under-saturated type synonym. GHC allows that; e.g.
696 -- type Foo k = k a -> k a
697 -- type Id x = x
698 -- foo :: Foo Id -> Foo Id
699 --
700 -- Here Id is partially applied in the type sig for Foo,
701 -- but once the type synonyms are expanded all is well
702
703 mkAppTys :: Type -> [Type] -> Type
704 mkAppTys ty1 [] = ty1
705 mkAppTys (CastTy fun_ty co) arg_tys -- much more efficient then nested mkAppTy
706 -- Why do this? See (EQ1) of
707 -- Note [Respecting definitional equality]
708 -- in TyCoRep
709 = foldl' AppTy ((mkAppTys fun_ty casted_arg_tys) `mkCastTy` res_co) leftovers
710 where
711 (arg_cos, res_co) = decomposePiCos co (coercionKind co) arg_tys
712 (args_to_cast, leftovers) = splitAtList arg_cos arg_tys
713 casted_arg_tys = zipWith mkCastTy args_to_cast arg_cos
714 mkAppTys (TyConApp tc tys1) tys2 = mkTyConApp tc (tys1 ++ tys2)
715 mkAppTys ty1 tys2 = foldl' AppTy ty1 tys2
716
717 -------------
718 splitAppTy_maybe :: Type -> Maybe (Type, Type)
719 -- ^ Attempt to take a type application apart, whether it is a
720 -- function, type constructor, or plain type application. Note
721 -- that type family applications are NEVER unsaturated by this!
722 splitAppTy_maybe ty | Just ty' <- coreView ty
723 = splitAppTy_maybe ty'
724 splitAppTy_maybe ty = repSplitAppTy_maybe ty
725
726 -------------
727 repSplitAppTy_maybe :: HasDebugCallStack => Type -> Maybe (Type,Type)
728 -- ^ Does the AppTy split as in 'splitAppTy_maybe', but assumes that
729 -- any Core view stuff is already done
730 repSplitAppTy_maybe (FunTy ty1 ty2)
731 = Just (TyConApp funTyCon [rep1, rep2, ty1], ty2)
732 where
733 rep1 = getRuntimeRep ty1
734 rep2 = getRuntimeRep ty2
735
736 repSplitAppTy_maybe (AppTy ty1 ty2)
737 = Just (ty1, ty2)
738
739 repSplitAppTy_maybe (TyConApp tc tys)
740 | mightBeUnsaturatedTyCon tc || tys `lengthExceeds` tyConArity tc
741 , Just (tys', ty') <- snocView tys
742 = Just (TyConApp tc tys', ty') -- Never create unsaturated type family apps!
743
744 repSplitAppTy_maybe _other = Nothing
745
746 -- This one doesn't break apart (c => t).
747 -- See Note [Decomposing fat arrow c=>t]
748 -- Defined here to avoid module loops between Unify and TcType.
749 tcRepSplitAppTy_maybe :: Type -> Maybe (Type,Type)
750 -- ^ Does the AppTy split as in 'tcSplitAppTy_maybe', but assumes that
751 -- any coreView stuff is already done. Refuses to look through (c => t)
752 tcRepSplitAppTy_maybe (FunTy ty1 ty2)
753 | isPredTy ty1
754 = Nothing -- See Note [Decomposing fat arrow c=>t]
755
756 | otherwise
757 = Just (TyConApp funTyCon [rep1, rep2, ty1], ty2)
758 where
759 rep1 = getRuntimeRep ty1
760 rep2 = getRuntimeRep ty2
761
762 tcRepSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
763 tcRepSplitAppTy_maybe (TyConApp tc tys)
764 | mightBeUnsaturatedTyCon tc || tys `lengthExceeds` tyConArity tc
765 , Just (tys', ty') <- snocView tys
766 = Just (TyConApp tc tys', ty') -- Never create unsaturated type family apps!
767 tcRepSplitAppTy_maybe _other = Nothing
768
769 -- | Like 'tcSplitTyConApp_maybe' but doesn't look through type synonyms.
770 tcRepSplitTyConApp_maybe :: HasCallStack => Type -> Maybe (TyCon, [Type])
771 -- Defined here to avoid module loops between Unify and TcType.
772 tcRepSplitTyConApp_maybe (TyConApp tc tys)
773 = Just (tc, tys)
774
775 tcRepSplitTyConApp_maybe (FunTy arg res)
776 = Just (funTyCon, [arg_rep, res_rep, arg, res])
777 where
778 arg_rep = getRuntimeRep arg
779 res_rep = getRuntimeRep res
780
781 tcRepSplitTyConApp_maybe _
782 = Nothing
783
784 -------------
785 splitAppTy :: Type -> (Type, Type)
786 -- ^ Attempts to take a type application apart, as in 'splitAppTy_maybe',
787 -- and panics if this is not possible
788 splitAppTy ty = case splitAppTy_maybe ty of
789 Just pr -> pr
790 Nothing -> panic "splitAppTy"
791
792 -------------
793 splitAppTys :: Type -> (Type, [Type])
794 -- ^ Recursively splits a type as far as is possible, leaving a residual
795 -- type being applied to and the type arguments applied to it. Never fails,
796 -- even if that means returning an empty list of type applications.
797 splitAppTys ty = split ty ty []
798 where
799 split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
800 split _ (AppTy ty arg) args = split ty ty (arg:args)
801 split _ (TyConApp tc tc_args) args
802 = let -- keep type families saturated
803 n | mightBeUnsaturatedTyCon tc = 0
804 | otherwise = tyConArity tc
805 (tc_args1, tc_args2) = splitAt n tc_args
806 in
807 (TyConApp tc tc_args1, tc_args2 ++ args)
808 split _ (FunTy ty1 ty2) args
809 = ASSERT( null args )
810 (TyConApp funTyCon [], [rep1, rep2, ty1, ty2])
811 where
812 rep1 = getRuntimeRep ty1
813 rep2 = getRuntimeRep ty2
814
815 split orig_ty _ args = (orig_ty, args)
816
817 -- | Like 'splitAppTys', but doesn't look through type synonyms
818 repSplitAppTys :: HasDebugCallStack => Type -> (Type, [Type])
819 repSplitAppTys ty = split ty []
820 where
821 split (AppTy ty arg) args = split ty (arg:args)
822 split (TyConApp tc tc_args) args
823 = let n | mightBeUnsaturatedTyCon tc = 0
824 | otherwise = tyConArity tc
825 (tc_args1, tc_args2) = splitAt n tc_args
826 in
827 (TyConApp tc tc_args1, tc_args2 ++ args)
828 split (FunTy ty1 ty2) args
829 = ASSERT( null args )
830 (TyConApp funTyCon [], [rep1, rep2, ty1, ty2])
831 where
832 rep1 = getRuntimeRep ty1
833 rep2 = getRuntimeRep ty2
834
835 split ty args = (ty, args)
836
837 {-
838 LitTy
839 ~~~~~
840 -}
841
842 mkNumLitTy :: Integer -> Type
843 mkNumLitTy n = LitTy (NumTyLit n)
844
845 -- | Is this a numeric literal. We also look through type synonyms.
846 isNumLitTy :: Type -> Maybe Integer
847 isNumLitTy ty | Just ty1 <- coreView ty = isNumLitTy ty1
848 isNumLitTy (LitTy (NumTyLit n)) = Just n
849 isNumLitTy _ = Nothing
850
851 mkStrLitTy :: FastString -> Type
852 mkStrLitTy s = LitTy (StrTyLit s)
853
854 -- | Is this a symbol literal. We also look through type synonyms.
855 isStrLitTy :: Type -> Maybe FastString
856 isStrLitTy ty | Just ty1 <- coreView ty = isStrLitTy ty1
857 isStrLitTy (LitTy (StrTyLit s)) = Just s
858 isStrLitTy _ = Nothing
859
860 -- | Is this a type literal (symbol or numeric).
861 isLitTy :: Type -> Maybe TyLit
862 isLitTy ty | Just ty1 <- coreView ty = isLitTy ty1
863 isLitTy (LitTy l) = Just l
864 isLitTy _ = Nothing
865
866 -- | Is this type a custom user error?
867 -- If so, give us the kind and the error message.
868 userTypeError_maybe :: Type -> Maybe Type
869 userTypeError_maybe t
870 = do { (tc, _kind : msg : _) <- splitTyConApp_maybe t
871 -- There may be more than 2 arguments, if the type error is
872 -- used as a type constructor (e.g. at kind `Type -> Type`).
873
874 ; guard (tyConName tc == errorMessageTypeErrorFamName)
875 ; return msg }
876
877 -- | Render a type corresponding to a user type error into a SDoc.
878 pprUserTypeErrorTy :: Type -> SDoc
879 pprUserTypeErrorTy ty =
880 case splitTyConApp_maybe ty of
881
882 -- Text "Something"
883 Just (tc,[txt])
884 | tyConName tc == typeErrorTextDataConName
885 , Just str <- isStrLitTy txt -> ftext str
886
887 -- ShowType t
888 Just (tc,[_k,t])
889 | tyConName tc == typeErrorShowTypeDataConName -> ppr t
890
891 -- t1 :<>: t2
892 Just (tc,[t1,t2])
893 | tyConName tc == typeErrorAppendDataConName ->
894 pprUserTypeErrorTy t1 <> pprUserTypeErrorTy t2
895
896 -- t1 :$$: t2
897 Just (tc,[t1,t2])
898 | tyConName tc == typeErrorVAppendDataConName ->
899 pprUserTypeErrorTy t1 $$ pprUserTypeErrorTy t2
900
901 -- An unevaluated type function
902 _ -> ppr ty
903
904
905
906
907 {-
908 ---------------------------------------------------------------------
909 FunTy
910 ~~~~~
911
912 Note [Representation of function types]
913 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
914
915 Functions (e.g. Int -> Char) are can be thought of as being applications
916 of funTyCon (known in Haskell surface syntax as (->)),
917
918 (->) :: forall (r1 :: RuntimeRep) (r2 :: RuntimeRep)
919 (a :: TYPE r1) (b :: TYPE r2).
920 a -> b -> Type
921
922 However, for efficiency's sake we represent saturated applications of (->)
923 with FunTy. For instance, the type,
924
925 (->) r1 r2 a b
926
927 is equivalent to,
928
929 FunTy (Anon a) b
930
931 Note how the RuntimeReps are implied in the FunTy representation. For this
932 reason we must be careful when recontructing the TyConApp representation (see,
933 for instance, splitTyConApp_maybe).
934
935 In the compiler we maintain the invariant that all saturated applications of
936 (->) are represented with FunTy.
937
938 See #11714.
939 -}
940
941 isFunTy :: Type -> Bool
942 isFunTy ty = isJust (splitFunTy_maybe ty)
943
944 splitFunTy :: Type -> (Type, Type)
945 -- ^ Attempts to extract the argument and result types from a type, and
946 -- panics if that is not possible. See also 'splitFunTy_maybe'
947 splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
948 splitFunTy (FunTy arg res) = (arg, res)
949 splitFunTy other = pprPanic "splitFunTy" (ppr other)
950
951 splitFunTy_maybe :: Type -> Maybe (Type, Type)
952 -- ^ Attempts to extract the argument and result types from a type
953 splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
954 splitFunTy_maybe (FunTy arg res) = Just (arg, res)
955 splitFunTy_maybe _ = Nothing
956
957 splitFunTys :: Type -> ([Type], Type)
958 splitFunTys ty = split [] ty ty
959 where
960 split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
961 split args _ (FunTy arg res) = split (arg:args) res res
962 split args orig_ty _ = (reverse args, orig_ty)
963
964 funResultTy :: Type -> Type
965 -- ^ Extract the function result type and panic if that is not possible
966 funResultTy ty | Just ty' <- coreView ty = funResultTy ty'
967 funResultTy (FunTy _ res) = res
968 funResultTy ty = pprPanic "funResultTy" (ppr ty)
969
970 funArgTy :: Type -> Type
971 -- ^ Extract the function argument type and panic if that is not possible
972 funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
973 funArgTy (FunTy arg _res) = arg
974 funArgTy ty = pprPanic "funArgTy" (ppr ty)
975
976 piResultTy :: HasDebugCallStack => Type -> Type -> Type
977 piResultTy ty arg = case piResultTy_maybe ty arg of
978 Just res -> res
979 Nothing -> pprPanic "piResultTy" (ppr ty $$ ppr arg)
980
981 piResultTy_maybe :: Type -> Type -> Maybe Type
982
983 -- ^ Just like 'piResultTys' but for a single argument
984 -- Try not to iterate 'piResultTy', because it's inefficient to substitute
985 -- one variable at a time; instead use 'piResultTys"
986 piResultTy_maybe ty arg
987 | Just ty' <- coreView ty = piResultTy_maybe ty' arg
988
989 | FunTy _ res <- ty
990 = Just res
991
992 | ForAllTy (TvBndr tv _) res <- ty
993 = let empty_subst = mkEmptyTCvSubst $ mkInScopeSet $
994 tyCoVarsOfTypes [arg,res]
995 in Just (substTy (extendTvSubst empty_subst tv arg) res)
996
997 | otherwise
998 = Nothing
999
1000 -- | (piResultTys f_ty [ty1, .., tyn]) gives the type of (f ty1 .. tyn)
1001 -- where f :: f_ty
1002 -- 'piResultTys' is interesting because:
1003 -- 1. 'f_ty' may have more for-alls than there are args
1004 -- 2. Less obviously, it may have fewer for-alls
1005 -- For case 2. think of:
1006 -- piResultTys (forall a.a) [forall b.b, Int]
1007 -- This really can happen, but only (I think) in situations involving
1008 -- undefined. For example:
1009 -- undefined :: forall a. a
1010 -- Term: undefined @(forall b. b->b) @Int
1011 -- This term should have type (Int -> Int), but notice that
1012 -- there are more type args than foralls in 'undefined's type.
1013
1014 -- If you edit this function, you may need to update the GHC formalism
1015 -- See Note [GHC Formalism] in coreSyn/CoreLint.hs
1016
1017 -- This is a heavily used function (e.g. from typeKind),
1018 -- so we pay attention to efficiency, especially in the special case
1019 -- where there are no for-alls so we are just dropping arrows from
1020 -- a function type/kind.
1021 piResultTys :: HasDebugCallStack => Type -> [Type] -> Type
1022 piResultTys ty [] = ty
1023 piResultTys ty orig_args@(arg:args)
1024 | Just ty' <- coreView ty
1025 = piResultTys ty' orig_args
1026
1027 | FunTy _ res <- ty
1028 = piResultTys res args
1029
1030 | ForAllTy (TvBndr tv _) res <- ty
1031 = go (extendVarEnv emptyTvSubstEnv tv arg) res args
1032
1033 | otherwise
1034 = pprPanic "piResultTys1" (ppr ty $$ ppr orig_args)
1035 where
1036 in_scope = mkInScopeSet (tyCoVarsOfTypes (ty:orig_args))
1037
1038 go :: TvSubstEnv -> Type -> [Type] -> Type
1039 go tv_env ty [] = substTy (mkTvSubst in_scope tv_env) ty
1040
1041 go tv_env ty all_args@(arg:args)
1042 | Just ty' <- coreView ty
1043 = go tv_env ty' all_args
1044
1045 | FunTy _ res <- ty
1046 = go tv_env res args
1047
1048 | ForAllTy (TvBndr tv _) res <- ty
1049 = go (extendVarEnv tv_env tv arg) res args
1050
1051 | otherwise -- See Note [Care with kind instantiation]
1052 = ASSERT2( not (isEmptyVarEnv tv_env)
1053 , ppr ty $$ ppr orig_args $$ ppr all_args )
1054 go emptyTvSubstEnv
1055 (substTy (mkTvSubst in_scope tv_env) ty)
1056 all_args
1057
1058 applyTysX :: [TyVar] -> Type -> [Type] -> Type
1059 -- applyTyxX beta-reduces (/\tvs. body_ty) arg_tys
1060 -- Assumes that (/\tvs. body_ty) is closed
1061 applyTysX tvs body_ty arg_tys
1062 = ASSERT2( arg_tys `lengthAtLeast` n_tvs, pp_stuff )
1063 ASSERT2( tyCoVarsOfType body_ty `subVarSet` mkVarSet tvs, pp_stuff )
1064 mkAppTys (substTyWith tvs (take n_tvs arg_tys) body_ty)
1065 (drop n_tvs arg_tys)
1066 where
1067 pp_stuff = vcat [ppr tvs, ppr body_ty, ppr arg_tys]
1068 n_tvs = length tvs
1069
1070
1071
1072 {- Note [Care with kind instantiation]
1073 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1074 Suppose we have
1075 T :: forall k. k
1076 and we are finding the kind of
1077 T (forall b. b -> b) * Int
1078 Then
1079 T (forall b. b->b) :: k[ k :-> forall b. b->b]
1080 :: forall b. b -> b
1081 So
1082 T (forall b. b->b) * :: (b -> b)[ b :-> *]
1083 :: * -> *
1084
1085 In other words wwe must intantiate the forall!
1086
1087 Similarly (Trac #154218)
1088 S :: forall k f. k -> f k
1089 and we are finding the kind of
1090 S * (* ->) Int Bool
1091 We have
1092 S * (* ->) :: (k -> f k)[ k :-> *, f :-> (* ->)]
1093 :: * -> * -> *
1094 So again we must instantiate.
1095
1096 The same thing happens in ToIface.toIfaceAppArgsX.
1097
1098
1099 ---------------------------------------------------------------------
1100 TyConApp
1101 ~~~~~~~~
1102 -}
1103
1104 -- | A key function: builds a 'TyConApp' or 'FunTy' as appropriate to
1105 -- its arguments. Applies its arguments to the constructor from left to right.
1106 mkTyConApp :: TyCon -> [Type] -> Type
1107 mkTyConApp tycon tys
1108 | isFunTyCon tycon
1109 , [_rep1,_rep2,ty1,ty2] <- tys
1110 = FunTy ty1 ty2
1111
1112 | otherwise
1113 = TyConApp tycon tys
1114
1115 -- splitTyConApp "looks through" synonyms, because they don't
1116 -- mean a distinct type, but all other type-constructor applications
1117 -- including functions are returned as Just ..
1118
1119 -- | Retrieve the tycon heading this type, if there is one. Does /not/
1120 -- look through synonyms.
1121 tyConAppTyConPicky_maybe :: Type -> Maybe TyCon
1122 tyConAppTyConPicky_maybe (TyConApp tc _) = Just tc
1123 tyConAppTyConPicky_maybe (FunTy {}) = Just funTyCon
1124 tyConAppTyConPicky_maybe _ = Nothing
1125
1126
1127 -- | The same as @fst . splitTyConApp@
1128 tyConAppTyCon_maybe :: Type -> Maybe TyCon
1129 tyConAppTyCon_maybe ty | Just ty' <- coreView ty = tyConAppTyCon_maybe ty'
1130 tyConAppTyCon_maybe (TyConApp tc _) = Just tc
1131 tyConAppTyCon_maybe (FunTy {}) = Just funTyCon
1132 tyConAppTyCon_maybe _ = Nothing
1133
1134 tyConAppTyCon :: Type -> TyCon
1135 tyConAppTyCon ty = tyConAppTyCon_maybe ty `orElse` pprPanic "tyConAppTyCon" (ppr ty)
1136
1137 -- | The same as @snd . splitTyConApp@
1138 tyConAppArgs_maybe :: Type -> Maybe [Type]
1139 tyConAppArgs_maybe ty | Just ty' <- coreView ty = tyConAppArgs_maybe ty'
1140 tyConAppArgs_maybe (TyConApp _ tys) = Just tys
1141 tyConAppArgs_maybe (FunTy arg res)
1142 | Just rep1 <- getRuntimeRep_maybe arg
1143 , Just rep2 <- getRuntimeRep_maybe res
1144 = Just [rep1, rep2, arg, res]
1145 tyConAppArgs_maybe _ = Nothing
1146
1147 tyConAppArgs :: Type -> [Type]
1148 tyConAppArgs ty = tyConAppArgs_maybe ty `orElse` pprPanic "tyConAppArgs" (ppr ty)
1149
1150 tyConAppArgN :: Int -> Type -> Type
1151 -- Executing Nth
1152 tyConAppArgN n ty
1153 = case tyConAppArgs_maybe ty of
1154 Just tys -> ASSERT2( tys `lengthExceeds` n, ppr n <+> ppr tys ) tys `getNth` n
1155 Nothing -> pprPanic "tyConAppArgN" (ppr n <+> ppr ty)
1156
1157 -- | Attempts to tease a type apart into a type constructor and the application
1158 -- of a number of arguments to that constructor. Panics if that is not possible.
1159 -- See also 'splitTyConApp_maybe'
1160 splitTyConApp :: Type -> (TyCon, [Type])
1161 splitTyConApp ty = case splitTyConApp_maybe ty of
1162 Just stuff -> stuff
1163 Nothing -> pprPanic "splitTyConApp" (ppr ty)
1164
1165 -- | Attempts to tease a type apart into a type constructor and the application
1166 -- of a number of arguments to that constructor
1167 splitTyConApp_maybe :: HasDebugCallStack => Type -> Maybe (TyCon, [Type])
1168 splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty'
1169 splitTyConApp_maybe ty = repSplitTyConApp_maybe ty
1170
1171 -- | Like 'splitTyConApp_maybe', but doesn't look through synonyms. This
1172 -- assumes the synonyms have already been dealt with.
1173 repSplitTyConApp_maybe :: HasDebugCallStack => Type -> Maybe (TyCon, [Type])
1174 repSplitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
1175 repSplitTyConApp_maybe (FunTy arg res)
1176 | Just arg_rep <- getRuntimeRep_maybe arg
1177 , Just res_rep <- getRuntimeRep_maybe res
1178 = Just (funTyCon, [arg_rep, res_rep, arg, res])
1179 repSplitTyConApp_maybe _ = Nothing
1180
1181 -- | Attempts to tease a list type apart and gives the type of the elements if
1182 -- successful (looks through type synonyms)
1183 splitListTyConApp_maybe :: Type -> Maybe Type
1184 splitListTyConApp_maybe ty = case splitTyConApp_maybe ty of
1185 Just (tc,[e]) | tc == listTyCon -> Just e
1186 _other -> Nothing
1187
1188 nextRole :: Type -> Role
1189 nextRole ty
1190 | Just (tc, tys) <- splitTyConApp_maybe ty
1191 , let num_tys = length tys
1192 , num_tys < tyConArity tc
1193 = tyConRoles tc `getNth` num_tys
1194
1195 | otherwise
1196 = Nominal
1197
1198 newTyConInstRhs :: TyCon -> [Type] -> Type
1199 -- ^ Unwrap one 'layer' of newtype on a type constructor and its
1200 -- arguments, using an eta-reduced version of the @newtype@ if possible.
1201 -- This requires tys to have at least @newTyConInstArity tycon@ elements.
1202 newTyConInstRhs tycon tys
1203 = ASSERT2( tvs `leLength` tys, ppr tycon $$ ppr tys $$ ppr tvs )
1204 applyTysX tvs rhs tys
1205 where
1206 (tvs, rhs) = newTyConEtadRhs tycon
1207
1208 {-
1209 ---------------------------------------------------------------------
1210 CastTy
1211 ~~~~~~
1212 A casted type has its *kind* casted into something new.
1213
1214 -}
1215
1216 splitCastTy_maybe :: Type -> Maybe (Type, Coercion)
1217 splitCastTy_maybe ty | Just ty' <- coreView ty = splitCastTy_maybe ty'
1218 splitCastTy_maybe (CastTy ty co) = Just (ty, co)
1219 splitCastTy_maybe _ = Nothing
1220
1221 -- | Make a 'CastTy'. The Coercion must be nominal. Checks the
1222 -- Coercion for reflexivity, dropping it if it's reflexive.
1223 -- See Note [Respecting definitional equality] in TyCoRep
1224 mkCastTy :: Type -> Coercion -> Type
1225 mkCastTy ty co | isReflexiveCo co = ty -- (EQ2) from the Note
1226 -- NB: Do the slow check here. This is important to keep the splitXXX
1227 -- functions working properly. Otherwise, we may end up with something
1228 -- like (((->) |> something_reflexive_but_not_obviously_so) biz baz)
1229 -- fails under splitFunTy_maybe. This happened with the cheaper check
1230 -- in test dependent/should_compile/dynamic-paper.
1231
1232 mkCastTy (CastTy ty co1) co2 = mkCastTy ty (co1 `mkTransCo` co2) -- (EQ3) from the Note
1233 -- call mkCastTy again for the reflexivity check
1234 mkCastTy ty co = CastTy ty co
1235
1236 tyConBindersTyBinders :: [TyConBinder] -> [TyBinder]
1237 -- Return the tyConBinders in TyBinder form
1238 tyConBindersTyBinders = map to_tyb
1239 where
1240 to_tyb (TvBndr tv (NamedTCB vis)) = Named (TvBndr tv vis)
1241 to_tyb (TvBndr tv AnonTCB) = Anon (tyVarKind tv)
1242
1243 {-
1244 --------------------------------------------------------------------
1245 CoercionTy
1246 ~~~~~~~~~~
1247 CoercionTy allows us to inject coercions into types. A CoercionTy
1248 should appear only in the right-hand side of an application.
1249 -}
1250
1251 mkCoercionTy :: Coercion -> Type
1252 mkCoercionTy = CoercionTy
1253
1254 isCoercionTy :: Type -> Bool
1255 isCoercionTy (CoercionTy _) = True
1256 isCoercionTy _ = False
1257
1258 isCoercionTy_maybe :: Type -> Maybe Coercion
1259 isCoercionTy_maybe (CoercionTy co) = Just co
1260 isCoercionTy_maybe _ = Nothing
1261
1262 stripCoercionTy :: Type -> Coercion
1263 stripCoercionTy (CoercionTy co) = co
1264 stripCoercionTy ty = pprPanic "stripCoercionTy" (ppr ty)
1265
1266 {-
1267 ---------------------------------------------------------------------
1268 SynTy
1269 ~~~~~
1270
1271 Notes on type synonyms
1272 ~~~~~~~~~~~~~~~~~~~~~~
1273 The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
1274 to return type synonyms wherever possible. Thus
1275
1276 type Foo a = a -> a
1277
1278 we want
1279 splitFunTys (a -> Foo a) = ([a], Foo a)
1280 not ([a], a -> a)
1281
1282 The reason is that we then get better (shorter) type signatures in
1283 interfaces. Notably this plays a role in tcTySigs in TcBinds.hs.
1284
1285
1286 ---------------------------------------------------------------------
1287 ForAllTy
1288 ~~~~~~~~
1289 -}
1290
1291 -- | Make a dependent forall over an Inferred (as opposed to Specified)
1292 -- variable
1293 mkInvForAllTy :: TyVar -> Type -> Type
1294 mkInvForAllTy tv ty = ASSERT( isTyVar tv )
1295 ForAllTy (TvBndr tv Inferred) ty
1296
1297 -- | Like mkForAllTys, but assumes all variables are dependent and Inferred,
1298 -- a common case
1299 mkInvForAllTys :: [TyVar] -> Type -> Type
1300 mkInvForAllTys tvs ty = ASSERT( all isTyVar tvs )
1301 foldr mkInvForAllTy ty tvs
1302
1303 -- | Like mkForAllTys, but assumes all variables are dependent and specified,
1304 -- a common case
1305 mkSpecForAllTys :: [TyVar] -> Type -> Type
1306 mkSpecForAllTys tvs = ASSERT( all isTyVar tvs )
1307 mkForAllTys [ TvBndr tv Specified | tv <- tvs ]
1308
1309 -- | Like mkForAllTys, but assumes all variables are dependent and visible
1310 mkVisForAllTys :: [TyVar] -> Type -> Type
1311 mkVisForAllTys tvs = ASSERT( all isTyVar tvs )
1312 mkForAllTys [ TvBndr tv Required | tv <- tvs ]
1313
1314 mkLamType :: Var -> Type -> Type
1315 -- ^ Makes a @(->)@ type or an implicit forall type, depending
1316 -- on whether it is given a type variable or a term variable.
1317 -- This is used, for example, when producing the type of a lambda.
1318 -- Always uses Inferred binders.
1319 mkLamTypes :: [Var] -> Type -> Type
1320 -- ^ 'mkLamType' for multiple type or value arguments
1321
1322 mkLamType v ty
1323 | isTyVar v = ForAllTy (TvBndr v Inferred) ty
1324 | otherwise = FunTy (varType v) ty
1325
1326 mkLamTypes vs ty = foldr mkLamType ty vs
1327
1328 -- | Given a list of type-level vars and a result kind,
1329 -- makes TyBinders, preferring anonymous binders
1330 -- if the variable is, in fact, not dependent.
1331 -- e.g. mkTyConBindersPreferAnon [(k:*),(b:k),(c:k)] (k->k)
1332 -- We want (k:*) Named, (a;k) Anon, (c:k) Anon
1333 --
1334 -- All binders are /visible/.
1335 mkTyConBindersPreferAnon :: [TyVar] -> Type -> [TyConBinder]
1336 mkTyConBindersPreferAnon vars inner_ty = fst (go vars)
1337 where
1338 go :: [TyVar] -> ([TyConBinder], VarSet) -- also returns the free vars
1339 go [] = ([], tyCoVarsOfType inner_ty)
1340 go (v:vs) | v `elemVarSet` fvs
1341 = ( TvBndr v (NamedTCB Required) : binders
1342 , fvs `delVarSet` v `unionVarSet` kind_vars )
1343 | otherwise
1344 = ( TvBndr v AnonTCB : binders
1345 , fvs `unionVarSet` kind_vars )
1346 where
1347 (binders, fvs) = go vs
1348 kind_vars = tyCoVarsOfType $ tyVarKind v
1349
1350 -- | Take a ForAllTy apart, returning the list of tyvars and the result type.
1351 -- This always succeeds, even if it returns only an empty list. Note that the
1352 -- result type returned may have free variables that were bound by a forall.
1353 splitForAllTys :: Type -> ([TyVar], Type)
1354 splitForAllTys ty = split ty ty []
1355 where
1356 split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs
1357 split _ (ForAllTy (TvBndr tv _) ty) tvs = split ty ty (tv:tvs)
1358 split orig_ty _ tvs = (reverse tvs, orig_ty)
1359
1360 -- | Like 'splitPiTys' but split off only /named/ binders.
1361 splitForAllTyVarBndrs :: Type -> ([TyVarBinder], Type)
1362 splitForAllTyVarBndrs ty = split ty ty []
1363 where
1364 split orig_ty ty bs | Just ty' <- coreView ty = split orig_ty ty' bs
1365 split _ (ForAllTy b res) bs = split res res (b:bs)
1366 split orig_ty _ bs = (reverse bs, orig_ty)
1367 {-# INLINE splitForAllTyVarBndrs #-}
1368
1369 -- | Checks whether this is a proper forall (with a named binder)
1370 isForAllTy :: Type -> Bool
1371 isForAllTy ty | Just ty' <- coreView ty = isForAllTy ty'
1372 isForAllTy (ForAllTy {}) = True
1373 isForAllTy _ = False
1374
1375 -- | Is this a function or forall?
1376 isPiTy :: Type -> Bool
1377 isPiTy ty | Just ty' <- coreView ty = isForAllTy ty'
1378 isPiTy (ForAllTy {}) = True
1379 isPiTy (FunTy {}) = True
1380 isPiTy _ = False
1381
1382 -- | Take a forall type apart, or panics if that is not possible.
1383 splitForAllTy :: Type -> (TyVar, Type)
1384 splitForAllTy ty
1385 | Just answer <- splitForAllTy_maybe ty = answer
1386 | otherwise = pprPanic "splitForAllTy" (ppr ty)
1387
1388 -- | Drops all ForAllTys
1389 dropForAlls :: Type -> Type
1390 dropForAlls ty = go ty
1391 where
1392 go ty | Just ty' <- coreView ty = go ty'
1393 go (ForAllTy _ res) = go res
1394 go res = res
1395
1396 -- | Attempts to take a forall type apart, but only if it's a proper forall,
1397 -- with a named binder
1398 splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
1399 splitForAllTy_maybe ty = go ty
1400 where
1401 go ty | Just ty' <- coreView ty = go ty'
1402 go (ForAllTy (TvBndr tv _) ty) = Just (tv, ty)
1403 go _ = Nothing
1404
1405 -- | Attempts to take a forall type apart; works with proper foralls and
1406 -- functions
1407 splitPiTy_maybe :: Type -> Maybe (TyBinder, Type)
1408 splitPiTy_maybe ty = go ty
1409 where
1410 go ty | Just ty' <- coreView ty = go ty'
1411 go (ForAllTy bndr ty) = Just (Named bndr, ty)
1412 go (FunTy arg res) = Just (Anon arg, res)
1413 go _ = Nothing
1414
1415 -- | Takes a forall type apart, or panics
1416 splitPiTy :: Type -> (TyBinder, Type)
1417 splitPiTy ty
1418 | Just answer <- splitPiTy_maybe ty = answer
1419 | otherwise = pprPanic "splitPiTy" (ppr ty)
1420
1421 -- | Split off all TyBinders to a type, splitting both proper foralls
1422 -- and functions
1423 splitPiTys :: Type -> ([TyBinder], Type)
1424 splitPiTys ty = split ty ty
1425 where
1426 split orig_ty ty | Just ty' <- coreView ty = split orig_ty ty'
1427 split _ (ForAllTy b res) = let (bs, ty) = split res res
1428 in (Named b : bs, ty)
1429 split _ (FunTy arg res) = let (bs, ty) = split res res
1430 in (Anon arg : bs, ty)
1431 split orig_ty _ = ([], orig_ty)
1432
1433 -- Like splitPiTys, but returns only *invisible* binders, including constraints
1434 -- Stops at the first visible binder
1435 splitPiTysInvisible :: Type -> ([TyBinder], Type)
1436 splitPiTysInvisible ty = split ty ty []
1437 where
1438 split orig_ty ty bs | Just ty' <- coreView ty = split orig_ty ty' bs
1439 split _ (ForAllTy b@(TvBndr _ vis) res) bs
1440 | isInvisibleArgFlag vis = split res res (Named b : bs)
1441 split _ (FunTy arg res) bs
1442 | isPredTy arg = split res res (Anon arg : bs)
1443 split orig_ty _ bs = (reverse bs, orig_ty)
1444
1445 -- | Given a tycon and its arguments, filters out any invisible arguments
1446 filterOutInvisibleTypes :: TyCon -> [Type] -> [Type]
1447 filterOutInvisibleTypes tc tys = snd $ partitionInvisibles tc id tys
1448
1449 -- | Given a tycon and a list of things (which correspond to arguments),
1450 -- partitions the things into
1451 -- Inferred or Specified ones and
1452 -- Required ones
1453 -- The callback function is necessary for this scenario:
1454 --
1455 -- > T :: forall k. k -> k
1456 -- > partitionInvisibles T [forall m. m -> m -> m, S, R, Q]
1457 --
1458 -- After substituting, we get
1459 --
1460 -- > T (forall m. m -> m -> m) :: (forall m. m -> m -> m) -> forall n. n -> n -> n
1461 --
1462 -- Thus, the first argument is invisible, @S@ is visible, @R@ is invisible again,
1463 -- and @Q@ is visible.
1464 --
1465 -- If you're absolutely sure that your tycon's kind doesn't end in a variable,
1466 -- it's OK if the callback function panics, as that's the only time it's
1467 -- consulted.
1468 partitionInvisibles :: TyCon -> (a -> Type) -> [a] -> ([a], [a])
1469 partitionInvisibles tc get_ty = go emptyTCvSubst (tyConKind tc)
1470 where
1471 go _ _ [] = ([], [])
1472 go subst (ForAllTy (TvBndr tv vis) res_ki) (x:xs)
1473 | isVisibleArgFlag vis = second (x :) (go subst' res_ki xs)
1474 | otherwise = first (x :) (go subst' res_ki xs)
1475 where
1476 subst' = extendTvSubst subst tv (get_ty x)
1477 go subst (TyVarTy tv) xs
1478 | Just ki <- lookupTyVar subst tv = go subst ki xs
1479 go _ _ xs = ([], xs) -- something is ill-kinded. But this can happen
1480 -- when printing errors. Assume everything is visible.
1481
1482 -- @isTauTy@ tests if a type has no foralls
1483 isTauTy :: Type -> Bool
1484 isTauTy ty | Just ty' <- coreView ty = isTauTy ty'
1485 isTauTy (TyVarTy _) = True
1486 isTauTy (LitTy {}) = True
1487 isTauTy (TyConApp tc tys) = all isTauTy tys && isTauTyCon tc
1488 isTauTy (AppTy a b) = isTauTy a && isTauTy b
1489 isTauTy (FunTy a b) = isTauTy a && isTauTy b
1490 isTauTy (ForAllTy {}) = False
1491 isTauTy (CastTy ty _) = isTauTy ty
1492 isTauTy (CoercionTy _) = False -- Not sure about this
1493
1494 {-
1495 %************************************************************************
1496 %* *
1497 TyBinders
1498 %* *
1499 %************************************************************************
1500 -}
1501
1502 -- | Make an anonymous binder
1503 mkAnonBinder :: Type -> TyBinder
1504 mkAnonBinder = Anon
1505
1506 -- | Does this binder bind a variable that is /not/ erased? Returns
1507 -- 'True' for anonymous binders.
1508 isAnonTyBinder :: TyBinder -> Bool
1509 isAnonTyBinder (Named {}) = False
1510 isAnonTyBinder (Anon {}) = True
1511
1512 isNamedTyBinder :: TyBinder -> Bool
1513 isNamedTyBinder (Named {}) = True
1514 isNamedTyBinder (Anon {}) = False
1515
1516 tyBinderVar_maybe :: TyBinder -> Maybe TyVar
1517 tyBinderVar_maybe (Named tv) = Just $ binderVar tv
1518 tyBinderVar_maybe _ = Nothing
1519
1520 tyBinderType :: TyBinder -> Type
1521 -- Barely used
1522 tyBinderType (Named tvb) = binderKind tvb
1523 tyBinderType (Anon ty) = ty
1524
1525 -- | Extract a relevant type, if there is one.
1526 binderRelevantType_maybe :: TyBinder -> Maybe Type
1527 binderRelevantType_maybe (Named {}) = Nothing
1528 binderRelevantType_maybe (Anon ty) = Just ty
1529
1530 -- | Like 'maybe', but for binders.
1531 caseBinder :: TyBinder -- ^ binder to scrutinize
1532 -> (TyVarBinder -> a) -- ^ named case
1533 -> (Type -> a) -- ^ anonymous case
1534 -> a
1535 caseBinder (Named v) f _ = f v
1536 caseBinder (Anon t) _ d = d t
1537
1538
1539 {-
1540 %************************************************************************
1541 %* *
1542 Pred
1543 * *
1544 ************************************************************************
1545
1546 Predicates on PredType
1547
1548 Note [isPredTy complications]
1549 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1550 You would think that we could define
1551 isPredTy ty = isConstraintKind (typeKind ty)
1552 But there are a number of complications:
1553
1554 * isPredTy is used when printing types, which can happen in debug
1555 printing during type checking of not-fully-zonked types. So it's
1556 not cool to say isConstraintKind (typeKind ty) because, absent
1557 zonking, the type might be ill-kinded, and typeKind crashes. Hence the
1558 rather tiresome story here
1559
1560 * isPredTy must return "True" to *unlifted* coercions, such as (t1 ~# t2)
1561 and (t1 ~R# t2), which are not of kind Constraint! Currently they are
1562 of kind #.
1563
1564 * If we do form the type '(C a => C [a]) => blah', then we'd like to
1565 print it as such. But that means that isPredTy must return True for
1566 (C a => C [a]). Admittedly that type is illegal in Haskell, but we
1567 want to print it nicely in error messages.
1568 -}
1569
1570 -- | Split a type constructor application into its type constructor and
1571 -- applied types. Note that this may fail in the case of a 'FunTy' with an
1572 -- argument of unknown kind 'FunTy' (e.g. @FunTy (a :: k) Int@. since the kind
1573 -- of @a@ isn't of the form @TYPE rep@). Consequently, you may need to zonk your
1574 -- type before using this function.
1575 --
1576 -- If you only need the 'TyCon', consider using 'tcTyConAppTyCon_maybe'.
1577 tcSplitTyConApp_maybe :: HasCallStack => Type -> Maybe (TyCon, [Type])
1578 -- Defined here to avoid module loops between Unify and TcType.
1579 tcSplitTyConApp_maybe ty | Just ty' <- tcView ty = tcSplitTyConApp_maybe ty'
1580 tcSplitTyConApp_maybe ty = tcRepSplitTyConApp_maybe ty
1581
1582 -- tcIsConstraintKind stuf only makes sense in the typechecker
1583 -- After that Constraint = Type
1584 -- See Note [coreView vs tcView]
1585 -- Defined here because it is used in isPredTy and tcRepSplitAppTy_maybe (sigh)
1586 tcIsConstraintKind :: Kind -> Bool
1587 tcIsConstraintKind ty
1588 | Just (tc, args) <- tcSplitTyConApp_maybe ty -- Note: tcSplit here
1589 , isConstraintKindCon tc
1590 = ASSERT2( null args, ppr ty ) True
1591
1592 | otherwise
1593 = False
1594
1595 -- | Is this kind equivalent to @*@?
1596 --
1597 -- This considers 'Constraint' to be distinct from @*@. For a version that
1598 -- treats them as the same type, see 'isLiftedTypeKind'.
1599 tcIsLiftedTypeKind :: Kind -> Bool
1600 tcIsLiftedTypeKind ty
1601 | Just (type_tc, [arg]) <- tcSplitTyConApp_maybe ty
1602 , type_tc `hasKey` tYPETyConKey
1603 , Just (lifted_rep_tc, args) <- tcSplitTyConApp_maybe arg
1604 , lifted_rep_tc `hasKey` liftedRepDataConKey
1605 = ASSERT2( null args, ppr ty ) True
1606 | otherwise
1607 = False
1608
1609 tcReturnsConstraintKind :: Kind -> Bool
1610 -- True <=> the Kind ultimately returns a Constraint
1611 -- E.g. * -> Constraint
1612 -- forall k. k -> Constraint
1613 tcReturnsConstraintKind kind
1614 | Just kind' <- tcView kind = tcReturnsConstraintKind kind'
1615 tcReturnsConstraintKind (ForAllTy _ ty) = tcReturnsConstraintKind ty
1616 tcReturnsConstraintKind (FunTy _ ty) = tcReturnsConstraintKind ty
1617 tcReturnsConstraintKind (TyConApp tc _) = isConstraintKindCon tc
1618 tcReturnsConstraintKind _ = False
1619
1620 -- | Is the type suitable to classify a given/wanted in the typechecker?
1621 isPredTy :: Type -> Bool
1622 -- See Note [isPredTy complications]
1623 isPredTy ty = go ty []
1624 where
1625 go :: Type -> [KindOrType] -> Bool
1626 go (AppTy ty1 ty2) args = go ty1 (ty2 : args)
1627 go (TyVarTy tv) args = go_k (tyVarKind tv) args
1628 go (TyConApp tc tys) args = ASSERT( null args ) -- TyConApp invariant
1629 go_tc tc tys
1630 go (FunTy arg res) []
1631 | isPredTy arg = isPredTy res -- (Eq a => C a)
1632 | otherwise = False -- (Int -> Bool)
1633 go (ForAllTy _ ty) [] = go ty []
1634 go (CastTy _ co) args = go_k (pSnd (coercionKind co)) args
1635 go _ _ = False
1636
1637 go_tc :: TyCon -> [KindOrType] -> Bool
1638 go_tc tc args
1639 | tc `hasKey` eqPrimTyConKey || tc `hasKey` eqReprPrimTyConKey
1640 = args `lengthIs` 4 -- ~# and ~R# sadly have result kind #
1641 -- not Constraint; but we still want
1642 -- isPredTy to reply True.
1643 | otherwise = go_k (tyConKind tc) args
1644
1645 go_k :: Kind -> [KindOrType] -> Bool
1646 -- True <=> ('k' applied to 'kts') = Constraint
1647 go_k k [] = tcIsConstraintKind k
1648 go_k k (arg:args) = case piResultTy_maybe k arg of
1649 Just k' -> go_k k' args
1650 Nothing -> WARN( True, text "isPredTy" <+> ppr ty )
1651 False
1652 -- This last case shouldn't happen under most circumstances. It can
1653 -- occur if we call isPredTy during kind checking, especially if one
1654 -- of the following happens:
1655 --
1656 -- 1. There is actually a kind error. Example in which this showed up:
1657 -- polykinds/T11399
1658 --
1659 -- 2. A type constructor application appears to be oversaturated. An
1660 -- example of this occurred in GHC Trac #13187:
1661 --
1662 -- {-# LANGUAGE PolyKinds #-}
1663 -- type Const a b = b
1664 -- f :: Const Int (,) Bool Char -> Char
1665 --
1666 -- We call isPredTy (Const k1 k2 Int (,) Bool Char
1667 -- where k1,k2 are unification variables that have been
1668 -- unified to *, and (*->*->*) resp, /but not zonked/.
1669 -- This shows that isPredTy can report a false negative
1670 -- if a constraint is similarly oversaturated, but
1671 -- it's hard to do better than isPredTy currently does without
1672 -- zonking, so we punt on such cases for now. This only happens
1673 -- during debug-printing, so it doesn't matter.
1674
1675 isClassPred, isEqPred, isNomEqPred, isIPPred :: PredType -> Bool
1676 isClassPred ty = case tyConAppTyCon_maybe ty of
1677 Just tyCon | isClassTyCon tyCon -> True
1678 _ -> False
1679 isEqPred ty = case tyConAppTyCon_maybe ty of
1680 Just tyCon -> tyCon `hasKey` eqPrimTyConKey
1681 || tyCon `hasKey` eqReprPrimTyConKey
1682 _ -> False
1683
1684 isNomEqPred ty = case tyConAppTyCon_maybe ty of
1685 Just tyCon -> tyCon `hasKey` eqPrimTyConKey
1686 _ -> False
1687
1688 isIPPred ty = case tyConAppTyCon_maybe ty of
1689 Just tc -> isIPTyCon tc
1690 _ -> False
1691
1692 isIPTyCon :: TyCon -> Bool
1693 isIPTyCon tc = tc `hasKey` ipClassKey
1694 -- Class and its corresponding TyCon have the same Unique
1695
1696 isIPClass :: Class -> Bool
1697 isIPClass cls = cls `hasKey` ipClassKey
1698
1699 isCTupleClass :: Class -> Bool
1700 isCTupleClass cls = isTupleTyCon (classTyCon cls)
1701
1702 isIPPred_maybe :: Type -> Maybe (FastString, Type)
1703 isIPPred_maybe ty =
1704 do (tc,[t1,t2]) <- splitTyConApp_maybe ty
1705 guard (isIPTyCon tc)
1706 x <- isStrLitTy t1
1707 return (x,t2)
1708
1709 {-
1710 Make PredTypes
1711
1712 --------------------- Equality types ---------------------------------
1713 -}
1714
1715 -- | Makes a lifted equality predicate at the given role
1716 mkPrimEqPredRole :: Role -> Type -> Type -> PredType
1717 mkPrimEqPredRole Nominal = mkPrimEqPred
1718 mkPrimEqPredRole Representational = mkReprPrimEqPred
1719 mkPrimEqPredRole Phantom = panic "mkPrimEqPredRole phantom"
1720
1721 -- | Creates a primitive type equality predicate.
1722 -- Invariant: the types are not Coercions
1723 mkPrimEqPred :: Type -> Type -> Type
1724 mkPrimEqPred ty1 ty2
1725 = TyConApp eqPrimTyCon [k1, k2, ty1, ty2]
1726 where
1727 k1 = typeKind ty1
1728 k2 = typeKind ty2
1729
1730 -- | Creates a primite type equality predicate with explicit kinds
1731 mkHeteroPrimEqPred :: Kind -> Kind -> Type -> Type -> Type
1732 mkHeteroPrimEqPred k1 k2 ty1 ty2 = TyConApp eqPrimTyCon [k1, k2, ty1, ty2]
1733
1734 -- | Creates a primitive representational type equality predicate
1735 -- with explicit kinds
1736 mkHeteroReprPrimEqPred :: Kind -> Kind -> Type -> Type -> Type
1737 mkHeteroReprPrimEqPred k1 k2 ty1 ty2
1738 = TyConApp eqReprPrimTyCon [k1, k2, ty1, ty2]
1739
1740 -- | Try to split up a coercion type into the types that it coerces
1741 splitCoercionType_maybe :: Type -> Maybe (Type, Type)
1742 splitCoercionType_maybe ty
1743 = do { (tc, [_, _, ty1, ty2]) <- splitTyConApp_maybe ty
1744 ; guard $ tc `hasKey` eqPrimTyConKey || tc `hasKey` eqReprPrimTyConKey
1745 ; return (ty1, ty2) }
1746
1747 mkReprPrimEqPred :: Type -> Type -> Type
1748 mkReprPrimEqPred ty1 ty2
1749 = TyConApp eqReprPrimTyCon [k1, k2, ty1, ty2]
1750 where
1751 k1 = typeKind ty1
1752 k2 = typeKind ty2
1753
1754 equalityTyCon :: Role -> TyCon
1755 equalityTyCon Nominal = eqPrimTyCon
1756 equalityTyCon Representational = eqReprPrimTyCon
1757 equalityTyCon Phantom = eqPhantPrimTyCon
1758
1759 -- --------------------- Dictionary types ---------------------------------
1760
1761 mkClassPred :: Class -> [Type] -> PredType
1762 mkClassPred clas tys = TyConApp (classTyCon clas) tys
1763
1764 isDictTy :: Type -> Bool
1765 isDictTy = isClassPred
1766
1767 isDictLikeTy :: Type -> Bool
1768 -- Note [Dictionary-like types]
1769 isDictLikeTy ty | Just ty' <- coreView ty = isDictLikeTy ty'
1770 isDictLikeTy ty = case splitTyConApp_maybe ty of
1771 Just (tc, tys) | isClassTyCon tc -> True
1772 | isTupleTyCon tc -> all isDictLikeTy tys
1773 _other -> False
1774
1775 {-
1776 Note [Dictionary-like types]
1777 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1778 Being "dictionary-like" means either a dictionary type or a tuple thereof.
1779 In GHC 6.10 we build implication constraints which construct such tuples,
1780 and if we land up with a binding
1781 t :: (C [a], Eq [a])
1782 t = blah
1783 then we want to treat t as cheap under "-fdicts-cheap" for example.
1784 (Implication constraints are normally inlined, but sadly not if the
1785 occurrence is itself inside an INLINE function! Until we revise the
1786 handling of implication constraints, that is.) This turned out to
1787 be important in getting good arities in DPH code. Example:
1788
1789 class C a
1790 class D a where { foo :: a -> a }
1791 instance C a => D (Maybe a) where { foo x = x }
1792
1793 bar :: (C a, C b) => a -> b -> (Maybe a, Maybe b)
1794 {-# INLINE bar #-}
1795 bar x y = (foo (Just x), foo (Just y))
1796
1797 Then 'bar' should jolly well have arity 4 (two dicts, two args), but
1798 we ended up with something like
1799 bar = __inline_me__ (\d1,d2. let t :: (D (Maybe a), D (Maybe b)) = ...
1800 in \x,y. <blah>)
1801
1802 This is all a bit ad-hoc; eg it relies on knowing that implication
1803 constraints build tuples.
1804
1805
1806 Decomposing PredType
1807 -}
1808
1809 -- | A choice of equality relation. This is separate from the type 'Role'
1810 -- because 'Phantom' does not define a (non-trivial) equality relation.
1811 data EqRel = NomEq | ReprEq
1812 deriving (Eq, Ord)
1813
1814 instance Outputable EqRel where
1815 ppr NomEq = text "nominal equality"
1816 ppr ReprEq = text "representational equality"
1817
1818 eqRelRole :: EqRel -> Role
1819 eqRelRole NomEq = Nominal
1820 eqRelRole ReprEq = Representational
1821
1822 data PredTree
1823 = ClassPred Class [Type]
1824 | EqPred EqRel Type Type
1825 | IrredPred PredType
1826 | ForAllPred [TyVarBinder] [PredType] PredType
1827 -- ForAllPred: see Note [Quantified constraints] in TcCanonical
1828 -- NB: There is no TuplePred case
1829 -- Tuple predicates like (Eq a, Ord b) are just treated
1830 -- as ClassPred, as if we had a tuple class with two superclasses
1831 -- class (c1, c2) => (%,%) c1 c2
1832
1833 classifyPredType :: PredType -> PredTree
1834 classifyPredType ev_ty = case splitTyConApp_maybe ev_ty of
1835 Just (tc, [_, _, ty1, ty2])
1836 | tc `hasKey` eqReprPrimTyConKey -> EqPred ReprEq ty1 ty2
1837 | tc `hasKey` eqPrimTyConKey -> EqPred NomEq ty1 ty2
1838
1839 Just (tc, tys)
1840 | Just clas <- tyConClass_maybe tc
1841 -> ClassPred clas tys
1842
1843 _ | (tvs, rho) <- splitForAllTyVarBndrs ev_ty
1844 , (theta, pred) <- splitFunTys rho
1845 , not (null tvs && null theta)
1846 -> ForAllPred tvs theta pred
1847
1848 | otherwise
1849 -> IrredPred ev_ty
1850
1851 getClassPredTys :: HasDebugCallStack => PredType -> (Class, [Type])
1852 getClassPredTys ty = case getClassPredTys_maybe ty of
1853 Just (clas, tys) -> (clas, tys)
1854 Nothing -> pprPanic "getClassPredTys" (ppr ty)
1855
1856 getClassPredTys_maybe :: PredType -> Maybe (Class, [Type])
1857 getClassPredTys_maybe ty = case splitTyConApp_maybe ty of
1858 Just (tc, tys) | Just clas <- tyConClass_maybe tc -> Just (clas, tys)
1859 _ -> Nothing
1860
1861 getEqPredTys :: PredType -> (Type, Type)
1862 getEqPredTys ty
1863 = case splitTyConApp_maybe ty of
1864 Just (tc, [_, _, ty1, ty2])
1865 | tc `hasKey` eqPrimTyConKey
1866 || tc `hasKey` eqReprPrimTyConKey
1867 -> (ty1, ty2)
1868 _ -> pprPanic "getEqPredTys" (ppr ty)
1869
1870 getEqPredTys_maybe :: PredType -> Maybe (Role, Type, Type)
1871 getEqPredTys_maybe ty
1872 = case splitTyConApp_maybe ty of
1873 Just (tc, [_, _, ty1, ty2])
1874 | tc `hasKey` eqPrimTyConKey -> Just (Nominal, ty1, ty2)
1875 | tc `hasKey` eqReprPrimTyConKey -> Just (Representational, ty1, ty2)
1876 _ -> Nothing
1877
1878 getEqPredRole :: PredType -> Role
1879 getEqPredRole ty = eqRelRole (predTypeEqRel ty)
1880
1881 -- | Get the equality relation relevant for a pred type.
1882 predTypeEqRel :: PredType -> EqRel
1883 predTypeEqRel ty
1884 | Just (tc, _) <- splitTyConApp_maybe ty
1885 , tc `hasKey` eqReprPrimTyConKey
1886 = ReprEq
1887 | otherwise
1888 = NomEq
1889
1890 {-
1891 %************************************************************************
1892 %* *
1893 Well-scoped tyvars
1894 * *
1895 ************************************************************************
1896 -}
1897
1898 -- | Do a topological sort on a list of tyvars,
1899 -- so that binders occur before occurrences
1900 -- E.g. given [ a::k, k::*, b::k ]
1901 -- it'll return a well-scoped list [ k::*, a::k, b::k ]
1902 --
1903 -- This is a deterministic sorting operation
1904 -- (that is, doesn't depend on Uniques).
1905 --
1906 -- It is also meant to be stable: that is, variables should not
1907 -- be reordered unnecessarily. The implementation of this
1908 -- has been observed to be stable, though it is not proven to
1909 -- be so. See also Note [Ordering of implicit variables] in HsTypes
1910 toposortTyVars :: [TyCoVar] -> [TyCoVar]
1911 toposortTyVars tvs = reverse $
1912 [ node_payload node | node <- topologicalSortG $
1913 graphFromEdgedVerticesOrd nodes ]
1914 where
1915 var_ids :: VarEnv Int
1916 var_ids = mkVarEnv (zip tvs [1..])
1917
1918 nodes :: [ Node Int TyVar ]
1919 nodes = [ DigraphNode
1920 tv
1921 (lookupVarEnv_NF var_ids tv)
1922 (mapMaybe (lookupVarEnv var_ids)
1923 (tyCoVarsOfTypeList (tyVarKind tv)))
1924 | tv <- tvs ]
1925
1926 -- | Extract a well-scoped list of variables from a deterministic set of
1927 -- variables. The result is deterministic.
1928 -- NB: There used to exist varSetElemsWellScoped :: VarSet -> [Var] which
1929 -- took a non-deterministic set and produced a non-deterministic
1930 -- well-scoped list. If you care about the list being well-scoped you also
1931 -- most likely care about it being in deterministic order.
1932 dVarSetElemsWellScoped :: DVarSet -> [Var]
1933 dVarSetElemsWellScoped = toposortTyVars . dVarSetElems
1934
1935 -- | Get the free vars of a type in scoped order
1936 tyCoVarsOfTypeWellScoped :: Type -> [TyVar]
1937 tyCoVarsOfTypeWellScoped = toposortTyVars . tyCoVarsOfTypeList
1938
1939 -- | Get the free vars of types in scoped order
1940 tyCoVarsOfTypesWellScoped :: [Type] -> [TyVar]
1941 tyCoVarsOfTypesWellScoped = toposortTyVars . tyCoVarsOfTypesList
1942
1943 {-
1944 ************************************************************************
1945 * *
1946 \subsection{Type families}
1947 * *
1948 ************************************************************************
1949 -}
1950
1951 mkFamilyTyConApp :: TyCon -> [Type] -> Type
1952 -- ^ Given a family instance TyCon and its arg types, return the
1953 -- corresponding family type. E.g:
1954 --
1955 -- > data family T a
1956 -- > data instance T (Maybe b) = MkT b
1957 --
1958 -- Where the instance tycon is :RTL, so:
1959 --
1960 -- > mkFamilyTyConApp :RTL Int = T (Maybe Int)
1961 mkFamilyTyConApp tc tys
1962 | Just (fam_tc, fam_tys) <- tyConFamInst_maybe tc
1963 , let tvs = tyConTyVars tc
1964 fam_subst = ASSERT2( tvs `equalLength` tys, ppr tc <+> ppr tys )
1965 zipTvSubst tvs tys
1966 = mkTyConApp fam_tc (substTys fam_subst fam_tys)
1967 | otherwise
1968 = mkTyConApp tc tys
1969
1970 -- | Get the type on the LHS of a coercion induced by a type/data
1971 -- family instance.
1972 coAxNthLHS :: CoAxiom br -> Int -> Type
1973 coAxNthLHS ax ind =
1974 mkTyConApp (coAxiomTyCon ax) (coAxBranchLHS (coAxiomNthBranch ax ind))
1975
1976 -- | Pretty prints a 'TyCon', using the family instance in case of a
1977 -- representation tycon. For example:
1978 --
1979 -- > data T [a] = ...
1980 --
1981 -- In that case we want to print @T [a]@, where @T@ is the family 'TyCon'
1982 pprSourceTyCon :: TyCon -> SDoc
1983 pprSourceTyCon tycon
1984 | Just (fam_tc, tys) <- tyConFamInst_maybe tycon
1985 = ppr $ fam_tc `TyConApp` tys -- can't be FunTyCon
1986 | otherwise
1987 = ppr tycon
1988
1989 -- @isTauTy@ tests if a type has no foralls
1990 isFamFreeTy :: Type -> Bool
1991 isFamFreeTy ty | Just ty' <- coreView ty = isFamFreeTy ty'
1992 isFamFreeTy (TyVarTy _) = True
1993 isFamFreeTy (LitTy {}) = True
1994 isFamFreeTy (TyConApp tc tys) = all isFamFreeTy tys && isFamFreeTyCon tc
1995 isFamFreeTy (AppTy a b) = isFamFreeTy a && isFamFreeTy b
1996 isFamFreeTy (FunTy a b) = isFamFreeTy a && isFamFreeTy b
1997 isFamFreeTy (ForAllTy _ ty) = isFamFreeTy ty
1998 isFamFreeTy (CastTy ty _) = isFamFreeTy ty
1999 isFamFreeTy (CoercionTy _) = False -- Not sure about this
2000
2001 {-
2002 ************************************************************************
2003 * *
2004 \subsection{Liftedness}
2005 * *
2006 ************************************************************************
2007 -}
2008
2009 -- | Returns Just True if this type is surely lifted, Just False
2010 -- if it is surely unlifted, Nothing if we can't be sure (i.e., it is
2011 -- levity polymorphic), and panics if the kind does not have the shape
2012 -- TYPE r.
2013 isLiftedType_maybe :: HasDebugCallStack => Type -> Maybe Bool
2014 isLiftedType_maybe ty = go (getRuntimeRep ty)
2015 where
2016 go rr | Just rr' <- coreView rr = go rr'
2017 go (TyConApp lifted_rep [])
2018 | lifted_rep `hasKey` liftedRepDataConKey = Just True
2019 go (TyConApp {}) = Just False -- everything else is unlifted
2020 go _ = Nothing -- levity polymorphic
2021
2022 -- | See "Type#type_classification" for what an unlifted type is.
2023 -- Panics on levity polymorphic types.
2024 isUnliftedType :: HasDebugCallStack => Type -> Bool
2025 -- isUnliftedType returns True for forall'd unlifted types:
2026 -- x :: forall a. Int#
2027 -- I found bindings like these were getting floated to the top level.
2028 -- They are pretty bogus types, mind you. It would be better never to
2029 -- construct them
2030 isUnliftedType ty
2031 = not (isLiftedType_maybe ty `orElse`
2032 pprPanic "isUnliftedType" (ppr ty <+> dcolon <+> ppr (typeKind ty)))
2033
2034 -- | Is this a type of kind RuntimeRep? (e.g. LiftedRep)
2035 isRuntimeRepKindedTy :: Type -> Bool
2036 isRuntimeRepKindedTy = isRuntimeRepTy . typeKind
2037
2038 -- | Drops prefix of RuntimeRep constructors in 'TyConApp's. Useful for e.g.
2039 -- dropping 'LiftedRep arguments of unboxed tuple TyCon applications:
2040 --
2041 -- dropRuntimeRepArgs [ 'LiftedRep, 'IntRep
2042 -- , String, Int# ] == [String, Int#]
2043 --
2044 dropRuntimeRepArgs :: [Type] -> [Type]
2045 dropRuntimeRepArgs = dropWhile isRuntimeRepKindedTy
2046
2047 -- | Extract the RuntimeRep classifier of a type. For instance,
2048 -- @getRuntimeRep_maybe Int = LiftedRep@. Returns 'Nothing' if this is not
2049 -- possible.
2050 getRuntimeRep_maybe :: HasDebugCallStack
2051 => Type -> Maybe Type
2052 getRuntimeRep_maybe = getRuntimeRepFromKind_maybe . typeKind
2053
2054 -- | Extract the RuntimeRep classifier of a type. For instance,
2055 -- @getRuntimeRep_maybe Int = LiftedRep@. Panics if this is not possible.
2056 getRuntimeRep :: HasDebugCallStack => Type -> Type
2057 getRuntimeRep ty
2058 = case getRuntimeRep_maybe ty of
2059 Just r -> r
2060 Nothing -> pprPanic "getRuntimeRep" (ppr ty <+> dcolon <+> ppr (typeKind ty))
2061
2062 -- | Extract the RuntimeRep classifier of a type from its kind. For example,
2063 -- @getRuntimeRepFromKind * = LiftedRep@; Panics if this is not possible.
2064 getRuntimeRepFromKind :: HasDebugCallStack
2065 => Type -> Type
2066 getRuntimeRepFromKind k =
2067 case getRuntimeRepFromKind_maybe k of
2068 Just r -> r
2069 Nothing -> pprPanic "getRuntimeRepFromKind"
2070 (ppr k <+> dcolon <+> ppr (typeKind k))
2071
2072 -- | Extract the RuntimeRep classifier of a type from its kind. For example,
2073 -- @getRuntimeRepFromKind * = LiftedRep@; Returns 'Nothing' if this is not
2074 -- possible.
2075 getRuntimeRepFromKind_maybe :: HasDebugCallStack
2076 => Type -> Maybe Type
2077 getRuntimeRepFromKind_maybe = go
2078 where
2079 go k | Just k' <- coreView k = go k'
2080 go k
2081 | Just (_tc, [arg]) <- splitTyConApp_maybe k
2082 = ASSERT2( _tc `hasKey` tYPETyConKey, ppr k )
2083 Just arg
2084 go _ = Nothing
2085
2086 isUnboxedTupleType :: Type -> Bool
2087 isUnboxedTupleType ty
2088 = tyConAppTyCon (getRuntimeRep ty) `hasKey` tupleRepDataConKey
2089 -- NB: Do not use typePrimRep, as that can't tell the difference between
2090 -- unboxed tuples and unboxed sums
2091
2092
2093 isUnboxedSumType :: Type -> Bool
2094 isUnboxedSumType ty
2095 = tyConAppTyCon (getRuntimeRep ty) `hasKey` sumRepDataConKey
2096
2097 -- | See "Type#type_classification" for what an algebraic type is.
2098 -- Should only be applied to /types/, as opposed to e.g. partially
2099 -- saturated type constructors
2100 isAlgType :: Type -> Bool
2101 isAlgType ty
2102 = case splitTyConApp_maybe ty of
2103 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
2104 isAlgTyCon tc
2105 _other -> False
2106
2107 -- | Check whether a type is a data family type
2108 isDataFamilyAppType :: Type -> Bool
2109 isDataFamilyAppType ty = case tyConAppTyCon_maybe ty of
2110 Just tc -> isDataFamilyTyCon tc
2111 _ -> False
2112
2113 -- | Computes whether an argument (or let right hand side) should
2114 -- be computed strictly or lazily, based only on its type.
2115 -- Currently, it's just 'isUnliftedType'. Panics on levity-polymorphic types.
2116 isStrictType :: HasDebugCallStack => Type -> Bool
2117 isStrictType = isUnliftedType
2118
2119 isPrimitiveType :: Type -> Bool
2120 -- ^ Returns true of types that are opaque to Haskell.
2121 isPrimitiveType ty = case splitTyConApp_maybe ty of
2122 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
2123 isPrimTyCon tc
2124 _ -> False
2125
2126 {-
2127 ************************************************************************
2128 * *
2129 \subsection{Join points}
2130 * *
2131 ************************************************************************
2132 -}
2133
2134 -- | Determine whether a type could be the type of a join point of given total
2135 -- arity, according to the polymorphism rule. A join point cannot be polymorphic
2136 -- in its return type, since given
2137 -- join j @a @b x y z = e1 in e2,
2138 -- the types of e1 and e2 must be the same, and a and b are not in scope for e2.
2139 -- (See Note [The polymorphism rule of join points] in CoreSyn.) Returns False
2140 -- also if the type simply doesn't have enough arguments.
2141 --
2142 -- Note that we need to know how many arguments (type *and* value) the putative
2143 -- join point takes; for instance, if
2144 -- j :: forall a. a -> Int
2145 -- then j could be a binary join point returning an Int, but it could *not* be a
2146 -- unary join point returning a -> Int.
2147 --
2148 -- TODO: See Note [Excess polymorphism and join points]
2149 isValidJoinPointType :: JoinArity -> Type -> Bool
2150 isValidJoinPointType arity ty
2151 = valid_under emptyVarSet arity ty
2152 where
2153 valid_under tvs arity ty
2154 | arity == 0
2155 = isEmptyVarSet (tvs `intersectVarSet` tyCoVarsOfType ty)
2156 | Just (t, ty') <- splitForAllTy_maybe ty
2157 = valid_under (tvs `extendVarSet` t) (arity-1) ty'
2158 | Just (_, res_ty) <- splitFunTy_maybe ty
2159 = valid_under tvs (arity-1) res_ty
2160 | otherwise
2161 = False
2162
2163 {- Note [Excess polymorphism and join points]
2164 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2165 In principle, if a function would be a join point except that it fails
2166 the polymorphism rule (see Note [The polymorphism rule of join points] in
2167 CoreSyn), it can still be made a join point with some effort. This is because
2168 all tail calls must return the same type (they return to the same context!), and
2169 thus if the return type depends on an argument, that argument must always be the
2170 same.
2171
2172 For instance, consider:
2173
2174 let f :: forall a. a -> Char -> [a]
2175 f @a x c = ... f @a y 'a' ...
2176 in ... f @Int 1 'b' ... f @Int 2 'c' ...
2177
2178 (where the calls are tail calls). `f` fails the polymorphism rule because its
2179 return type is [a], where [a] is bound. But since the type argument is always
2180 'Int', we can rewrite it as:
2181
2182 let f' :: Int -> Char -> [Int]
2183 f' x c = ... f' y 'a' ...
2184 in ... f' 1 'b' ... f 2 'c' ...
2185
2186 and now we can make f' a join point:
2187
2188 join f' :: Int -> Char -> [Int]
2189 f' x c = ... jump f' y 'a' ...
2190 in ... jump f' 1 'b' ... jump f' 2 'c' ...
2191
2192 It's not clear that this comes up often, however. TODO: Measure how often and
2193 add this analysis if necessary. See Trac #14620.
2194
2195
2196 ************************************************************************
2197 * *
2198 \subsection{Sequencing on types}
2199 * *
2200 ************************************************************************
2201 -}
2202
2203 seqType :: Type -> ()
2204 seqType (LitTy n) = n `seq` ()
2205 seqType (TyVarTy tv) = tv `seq` ()
2206 seqType (AppTy t1 t2) = seqType t1 `seq` seqType t2
2207 seqType (FunTy t1 t2) = seqType t1 `seq` seqType t2
2208 seqType (TyConApp tc tys) = tc `seq` seqTypes tys
2209 seqType (ForAllTy (TvBndr tv _) ty) = seqType (tyVarKind tv) `seq` seqType ty
2210 seqType (CastTy ty co) = seqType ty `seq` seqCo co
2211 seqType (CoercionTy co) = seqCo co
2212
2213 seqTypes :: [Type] -> ()
2214 seqTypes [] = ()
2215 seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
2216
2217 {-
2218 ************************************************************************
2219 * *
2220 Comparison for types
2221 (We don't use instances so that we know where it happens)
2222 * *
2223 ************************************************************************
2224
2225 Note [Equality on AppTys]
2226 ~~~~~~~~~~~~~~~~~~~~~~~~~
2227 In our cast-ignoring equality, we want to say that the following two
2228 are equal:
2229
2230 (Maybe |> co) (Int |> co') ~? Maybe Int
2231
2232 But the left is an AppTy while the right is a TyConApp. The solution is
2233 to use repSplitAppTy_maybe to break up the TyConApp into its pieces and
2234 then continue. Easy to do, but also easy to forget to do.
2235
2236 -}
2237
2238 eqType :: Type -> Type -> Bool
2239 -- ^ Type equality on source types. Does not look through @newtypes@ or
2240 -- 'PredType's, but it does look through type synonyms.
2241 -- This first checks that the kinds of the types are equal and then
2242 -- checks whether the types are equal, ignoring casts and coercions.
2243 -- (The kind check is a recursive call, but since all kinds have type
2244 -- @Type@, there is no need to check the types of kinds.)
2245 -- See also Note [Non-trivial definitional equality] in TyCoRep.
2246 eqType t1 t2 = isEqual $ nonDetCmpType t1 t2
2247 -- It's OK to use nonDetCmpType here and eqType is deterministic,
2248 -- nonDetCmpType does equality deterministically
2249
2250 -- | Compare types with respect to a (presumably) non-empty 'RnEnv2'.
2251 eqTypeX :: RnEnv2 -> Type -> Type -> Bool
2252 eqTypeX env t1 t2 = isEqual $ nonDetCmpTypeX env t1 t2
2253 -- It's OK to use nonDetCmpType here and eqTypeX is deterministic,
2254 -- nonDetCmpTypeX does equality deterministically
2255
2256 -- | Type equality on lists of types, looking through type synonyms
2257 -- but not newtypes.
2258 eqTypes :: [Type] -> [Type] -> Bool
2259 eqTypes tys1 tys2 = isEqual $ nonDetCmpTypes tys1 tys2
2260 -- It's OK to use nonDetCmpType here and eqTypes is deterministic,
2261 -- nonDetCmpTypes does equality deterministically
2262
2263 eqVarBndrs :: RnEnv2 -> [Var] -> [Var] -> Maybe RnEnv2
2264 -- Check that the var lists are the same length
2265 -- and have matching kinds; if so, extend the RnEnv2
2266 -- Returns Nothing if they don't match
2267 eqVarBndrs env [] []
2268 = Just env
2269 eqVarBndrs env (tv1:tvs1) (tv2:tvs2)
2270 | eqTypeX env (tyVarKind tv1) (tyVarKind tv2)
2271 = eqVarBndrs (rnBndr2 env tv1 tv2) tvs1 tvs2
2272 eqVarBndrs _ _ _= Nothing
2273
2274 -- Now here comes the real worker
2275
2276 {-
2277 Note [nonDetCmpType nondeterminism]
2278 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2279 nonDetCmpType is implemented in terms of nonDetCmpTypeX. nonDetCmpTypeX
2280 uses nonDetCmpTc which compares TyCons by their Unique value. Using Uniques for
2281 ordering leads to nondeterminism. We hit the same problem in the TyVarTy case,
2282 comparing type variables is nondeterministic, note the call to nonDetCmpVar in
2283 nonDetCmpTypeX.
2284 See Note [Unique Determinism] for more details.
2285 -}
2286
2287 nonDetCmpType :: Type -> Type -> Ordering
2288 nonDetCmpType t1 t2
2289 -- we know k1 and k2 have the same kind, because they both have kind *.
2290 = nonDetCmpTypeX rn_env t1 t2
2291 where
2292 rn_env = mkRnEnv2 (mkInScopeSet (tyCoVarsOfTypes [t1, t2]))
2293
2294 nonDetCmpTypes :: [Type] -> [Type] -> Ordering
2295 nonDetCmpTypes ts1 ts2 = nonDetCmpTypesX rn_env ts1 ts2
2296 where
2297 rn_env = mkRnEnv2 (mkInScopeSet (tyCoVarsOfTypes (ts1 ++ ts2)))
2298
2299 -- | An ordering relation between two 'Type's (known below as @t1 :: k1@
2300 -- and @t2 :: k2@)
2301 data TypeOrdering = TLT -- ^ @t1 < t2@
2302 | TEQ -- ^ @t1 ~ t2@ and there are no casts in either,
2303 -- therefore we can conclude @k1 ~ k2@
2304 | TEQX -- ^ @t1 ~ t2@ yet one of the types contains a cast so
2305 -- they may differ in kind.
2306 | TGT -- ^ @t1 > t2@
2307 deriving (Eq, Ord, Enum, Bounded)
2308
2309 nonDetCmpTypeX :: RnEnv2 -> Type -> Type -> Ordering -- Main workhorse
2310 -- See Note [Non-trivial definitional equality] in TyCoRep
2311 nonDetCmpTypeX env orig_t1 orig_t2 =
2312 case go env orig_t1 orig_t2 of
2313 -- If there are casts then we also need to do a comparison of the kinds of
2314 -- the types being compared
2315 TEQX -> toOrdering $ go env k1 k2
2316 ty_ordering -> toOrdering ty_ordering
2317 where
2318 k1 = typeKind orig_t1
2319 k2 = typeKind orig_t2
2320
2321 toOrdering :: TypeOrdering -> Ordering
2322 toOrdering TLT = LT
2323 toOrdering TEQ = EQ
2324 toOrdering TEQX = EQ
2325 toOrdering TGT = GT
2326
2327 liftOrdering :: Ordering -> TypeOrdering
2328 liftOrdering LT = TLT
2329 liftOrdering EQ = TEQ
2330 liftOrdering GT = TGT
2331
2332 thenCmpTy :: TypeOrdering -> TypeOrdering -> TypeOrdering
2333 thenCmpTy TEQ rel = rel
2334 thenCmpTy TEQX rel = hasCast rel
2335 thenCmpTy rel _ = rel
2336
2337 hasCast :: TypeOrdering -> TypeOrdering
2338 hasCast TEQ = TEQX
2339 hasCast rel = rel
2340
2341 -- Returns both the resulting ordering relation between the two types
2342 -- and whether either contains a cast.
2343 go :: RnEnv2 -> Type -> Type -> TypeOrdering
2344 go env t1 t2
2345 | Just t1' <- coreView t1 = go env t1' t2
2346 | Just t2' <- coreView t2 = go env t1 t2'
2347
2348 go env (TyVarTy tv1) (TyVarTy tv2)
2349 = liftOrdering $ rnOccL env tv1 `nonDetCmpVar` rnOccR env tv2
2350 go env (ForAllTy (TvBndr tv1 _) t1) (ForAllTy (TvBndr tv2 _) t2)
2351 = go env (tyVarKind tv1) (tyVarKind tv2)
2352 `thenCmpTy` go (rnBndr2 env tv1 tv2) t1 t2
2353 -- See Note [Equality on AppTys]
2354 go env (AppTy s1 t1) ty2
2355 | Just (s2, t2) <- repSplitAppTy_maybe ty2
2356 = go env s1 s2 `thenCmpTy` go env t1 t2
2357 go env ty1 (AppTy s2 t2)
2358 | Just (s1, t1) <- repSplitAppTy_maybe ty1
2359 = go env s1 s2 `thenCmpTy` go env t1 t2
2360 go env (FunTy s1 t1) (FunTy s2 t2)
2361 = go env s1 s2 `thenCmpTy` go env t1 t2
2362 go env (TyConApp tc1 tys1) (TyConApp tc2 tys2)
2363 = liftOrdering (tc1 `nonDetCmpTc` tc2) `thenCmpTy` gos env tys1 tys2
2364 go _ (LitTy l1) (LitTy l2) = liftOrdering (compare l1 l2)
2365 go env (CastTy t1 _) t2 = hasCast $ go env t1 t2
2366 go env t1 (CastTy t2 _) = hasCast $ go env t1 t2
2367
2368 go _ (CoercionTy {}) (CoercionTy {}) = TEQ
2369
2370 -- Deal with the rest: TyVarTy < CoercionTy < AppTy < LitTy < TyConApp < ForAllTy
2371 go _ ty1 ty2
2372 = liftOrdering $ (get_rank ty1) `compare` (get_rank ty2)
2373 where get_rank :: Type -> Int
2374 get_rank (CastTy {})
2375 = pprPanic "nonDetCmpTypeX.get_rank" (ppr [ty1,ty2])
2376 get_rank (TyVarTy {}) = 0
2377 get_rank (CoercionTy {}) = 1
2378 get_rank (AppTy {}) = 3
2379 get_rank (LitTy {}) = 4
2380 get_rank (TyConApp {}) = 5
2381 get_rank (FunTy {}) = 6
2382 get_rank (ForAllTy {}) = 7
2383
2384 gos :: RnEnv2 -> [Type] -> [Type] -> TypeOrdering
2385 gos _ [] [] = TEQ
2386 gos _ [] _ = TLT
2387 gos _ _ [] = TGT
2388 gos env (ty1:tys1) (ty2:tys2) = go env ty1 ty2 `thenCmpTy` gos env tys1 tys2
2389
2390 -------------
2391 nonDetCmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
2392 nonDetCmpTypesX _ [] [] = EQ
2393 nonDetCmpTypesX env (t1:tys1) (t2:tys2) = nonDetCmpTypeX env t1 t2
2394 `thenCmp`
2395 nonDetCmpTypesX env tys1 tys2
2396 nonDetCmpTypesX _ [] _ = LT
2397 nonDetCmpTypesX _ _ [] = GT
2398
2399 -------------
2400 -- | Compare two 'TyCon's. NB: This should /never/ see 'Constraint' (as
2401 -- recognized by Kind.isConstraintKindCon) which is considered a synonym for
2402 -- 'Type' in Core.
2403 -- See Note [Kind Constraint and kind Type] in Kind.
2404 -- See Note [nonDetCmpType nondeterminism]
2405 nonDetCmpTc :: TyCon -> TyCon -> Ordering
2406 nonDetCmpTc tc1 tc2
2407 = ASSERT( not (isConstraintKindCon tc1) && not (isConstraintKindCon tc2) )
2408 u1 `nonDetCmpUnique` u2
2409 where
2410 u1 = tyConUnique tc1
2411 u2 = tyConUnique tc2
2412
2413 {-
2414 ************************************************************************
2415 * *
2416 The kind of a type
2417 * *
2418 ************************************************************************
2419 -}
2420
2421 typeKind :: HasDebugCallStack => Type -> Kind
2422 typeKind (TyConApp tc tys) = piResultTys (tyConKind tc) tys
2423 typeKind (AppTy fun arg) = typeKind_apps fun [arg]
2424 typeKind (LitTy l) = typeLiteralKind l
2425 typeKind (FunTy {}) = liftedTypeKind
2426 typeKind (TyVarTy tyvar) = tyVarKind tyvar
2427 typeKind (CastTy _ty co) = pSnd $ coercionKind co
2428 typeKind (CoercionTy co) = coercionType co
2429 typeKind ty@(ForAllTy {}) = case occCheckExpand tvs k of
2430 Just k' -> k'
2431 Nothing -> pprPanic "typeKind"
2432 (ppr ty $$ ppr k $$ ppr tvs $$ ppr body)
2433 where
2434 (tvs, body) = splitForAllTys ty
2435 k = typeKind body
2436
2437 typeKind_apps :: HasDebugCallStack => Type -> [Type] -> Kind
2438 -- The sole purpose of the function is to accumulate
2439 -- the type arugments, so we can call piResultTys, rather than
2440 -- a succession of calls to piResultTy (which is asymptotically
2441 -- less efficient as the number of arguments increases)
2442 typeKind_apps (AppTy fun arg) args = typeKind_apps fun (arg:args)
2443 typeKind_apps fun args = piResultTys (typeKind fun) args
2444
2445 --------------------------
2446 typeLiteralKind :: TyLit -> Kind
2447 typeLiteralKind l =
2448 case l of
2449 NumTyLit _ -> typeNatKind
2450 StrTyLit _ -> typeSymbolKind
2451
2452 -- | Returns True if a type is levity polymorphic. Should be the same
2453 -- as (isKindLevPoly . typeKind) but much faster.
2454 -- Precondition: The type has kind (TYPE blah)
2455 isTypeLevPoly :: Type -> Bool
2456 isTypeLevPoly = go
2457 where
2458 go ty@(TyVarTy {}) = check_kind ty
2459 go ty@(AppTy {}) = check_kind ty
2460 go ty@(TyConApp tc _) | not (isTcLevPoly tc) = False
2461 | otherwise = check_kind ty
2462 go (ForAllTy _ ty) = go ty
2463 go (FunTy {}) = False
2464 go (LitTy {}) = False
2465 go ty@(CastTy {}) = check_kind ty
2466 go ty@(CoercionTy {}) = pprPanic "isTypeLevPoly co" (ppr ty)
2467
2468 check_kind = isKindLevPoly . typeKind
2469
2470 -- | Looking past all pi-types, is the end result potentially levity polymorphic?
2471 -- Example: True for (forall r (a :: TYPE r). String -> a)
2472 -- Example: False for (forall r1 r2 (a :: TYPE r1) (b :: TYPE r2). a -> b -> Type)
2473 resultIsLevPoly :: Type -> Bool
2474 resultIsLevPoly = isTypeLevPoly . snd . splitPiTys
2475
2476
2477 {- **********************************************************************
2478 * *
2479 Occurs check expansion
2480 %* *
2481 %********************************************************************* -}
2482
2483 {- Note [Occurs check expansion]
2484 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2485 (occurCheckExpand tv xi) expands synonyms in xi just enough to get rid
2486 of occurrences of tv outside type function arguments, if that is
2487 possible; otherwise, it returns Nothing.
2488
2489 For example, suppose we have
2490 type F a b = [a]
2491 Then
2492 occCheckExpand b (F Int b) = Just [Int]
2493 but
2494 occCheckExpand a (F a Int) = Nothing
2495
2496 We don't promise to do the absolute minimum amount of expanding
2497 necessary, but we try not to do expansions we don't need to. We
2498 prefer doing inner expansions first. For example,
2499 type F a b = (a, Int, a, [a])
2500 type G b = Char
2501 We have
2502 occCheckExpand b (F (G b)) = Just (F Char)
2503 even though we could also expand F to get rid of b.
2504 -}
2505
2506 occCheckExpand :: [Var] -> Type -> Maybe Type
2507 -- See Note [Occurs check expansion]
2508 -- We may have needed to do some type synonym unfolding in order to
2509 -- get rid of the variable (or forall), so we also return the unfolded
2510 -- version of the type, which is guaranteed to be syntactically free
2511 -- of the given type variable. If the type is already syntactically
2512 -- free of the variable, then the same type is returned.
2513 occCheckExpand vs_to_avoid ty
2514 = go (mkVarSet vs_to_avoid, emptyVarEnv) ty
2515 where
2516 go :: (VarSet, VarEnv TyVar) -> Type -> Maybe Type
2517 -- The VarSet is the set of variables we are trying to avoid
2518 -- The VarEnv carries mappings necessary
2519 -- because of kind expansion
2520 go cxt@(as, env) (TyVarTy tv')
2521 | tv' `elemVarSet` as = Nothing
2522 | Just tv'' <- lookupVarEnv env tv' = return (mkTyVarTy tv'')
2523 | otherwise = do { tv'' <- go_var cxt tv'
2524 ; return (mkTyVarTy tv'') }
2525
2526 go _ ty@(LitTy {}) = return ty
2527 go cxt (AppTy ty1 ty2) = do { ty1' <- go cxt ty1
2528 ; ty2' <- go cxt ty2
2529 ; return (mkAppTy ty1' ty2') }
2530 go cxt (FunTy ty1 ty2) = do { ty1' <- go cxt ty1
2531 ; ty2' <- go cxt ty2
2532 ; return (mkFunTy ty1' ty2') }
2533 go cxt@(as, env) (ForAllTy (TvBndr tv vis) body_ty)
2534 = do { ki' <- go cxt (tyVarKind tv)
2535 ; let tv' = setTyVarKind tv ki'
2536 env' = extendVarEnv env tv tv'
2537 as' = as `delVarSet` tv
2538 ; body' <- go (as', env') body_ty
2539 ; return (ForAllTy (TvBndr tv' vis) body') }
2540
2541 -- For a type constructor application, first try expanding away the
2542 -- offending variable from the arguments. If that doesn't work, next
2543 -- see if the type constructor is a type synonym, and if so, expand
2544 -- it and try again.
2545 go cxt ty@(TyConApp tc tys)
2546 = case mapM (go cxt) tys of
2547 Just tys' -> return (mkTyConApp tc tys')
2548 Nothing | Just ty' <- tcView ty -> go cxt ty'
2549 | otherwise -> Nothing
2550 -- Failing that, try to expand a synonym
2551
2552 go cxt (CastTy ty co) = do { ty' <- go cxt ty
2553 ; co' <- go_co cxt co
2554 ; return (mkCastTy ty' co') }
2555 go cxt (CoercionTy co) = do { co' <- go_co cxt co
2556 ; return (mkCoercionTy co') }
2557
2558 ------------------
2559 go_var cxt v = do { k' <- go cxt (varType v)
2560 ; return (setVarType v k') }
2561 -- Works for TyVar and CoVar
2562 -- See Note [Occurrence checking: look inside kinds]
2563
2564 ------------------
2565 go_mco _ MRefl = return MRefl
2566 go_mco ctx (MCo co) = MCo <$> go_co ctx co
2567
2568 ------------------
2569 go_co cxt (Refl ty) = do { ty' <- go cxt ty
2570 ; return (mkNomReflCo ty') }
2571 go_co cxt (GRefl r ty mco) = do { mco' <- go_mco cxt mco
2572 ; ty' <- go cxt ty
2573 ; return (mkGReflCo r ty' mco') }
2574 -- Note: Coercions do not contain type synonyms
2575 go_co cxt (TyConAppCo r tc args) = do { args' <- mapM (go_co cxt) args
2576 ; return (mkTyConAppCo r tc args') }
2577 go_co cxt (AppCo co arg) = do { co' <- go_co cxt co
2578 ; arg' <- go_co cxt arg
2579 ; return (mkAppCo co' arg') }
2580 go_co cxt@(as, env) (ForAllCo tv kind_co body_co)
2581 = do { kind_co' <- go_co cxt kind_co
2582 ; let tv' = setTyVarKind tv $
2583 pFst (coercionKind kind_co')
2584 env' = extendVarEnv env tv tv'
2585 as' = as `delVarSet` tv
2586 ; body' <- go_co (as', env') body_co
2587 ; return (ForAllCo tv' kind_co' body') }
2588 go_co cxt (FunCo r co1 co2) = do { co1' <- go_co cxt co1
2589 ; co2' <- go_co cxt co2
2590 ; return (mkFunCo r co1' co2') }
2591 go_co cxt (CoVarCo c) = do { c' <- go_var cxt c
2592 ; return (mkCoVarCo c') }
2593 go_co cxt (HoleCo h) = do { c' <- go_var cxt (ch_co_var h)
2594 ; return (HoleCo (h { ch_co_var = c' })) }
2595 go_co cxt (AxiomInstCo ax ind args) = do { args' <- mapM (go_co cxt) args
2596 ; return (mkAxiomInstCo ax ind args') }
2597 go_co cxt (UnivCo p r ty1 ty2) = do { p' <- go_prov cxt p
2598 ; ty1' <- go cxt ty1
2599 ; ty2' <- go cxt ty2
2600 ; return (mkUnivCo p' r ty1' ty2') }
2601 go_co cxt (SymCo co) = do { co' <- go_co cxt co
2602 ; return (mkSymCo co') }
2603 go_co cxt (TransCo co1 co2) = do { co1' <- go_co cxt co1
2604 ; co2' <- go_co cxt co2
2605 ; return (mkTransCo co1' co2') }
2606 go_co cxt (NthCo r n co) = do { co' <- go_co cxt co
2607 ; return (mkNthCo r n co') }
2608 go_co cxt (LRCo lr co) = do { co' <- go_co cxt co
2609 ; return (mkLRCo lr co') }
2610 go_co cxt (InstCo co arg) = do { co' <- go_co cxt co
2611 ; arg' <- go_co cxt arg
2612 ; return (mkInstCo co' arg') }
2613 go_co cxt (KindCo co) = do { co' <- go_co cxt co
2614 ; return (mkKindCo co') }
2615 go_co cxt (SubCo co) = do { co' <- go_co cxt co
2616 ; return (mkSubCo co') }
2617 go_co cxt (AxiomRuleCo ax cs) = do { cs' <- mapM (go_co cxt) cs
2618 ; return (mkAxiomRuleCo ax cs') }
2619
2620 ------------------
2621 go_prov _ UnsafeCoerceProv = return UnsafeCoerceProv
2622 go_prov cxt (PhantomProv co) = PhantomProv <$> go_co cxt co
2623 go_prov cxt (ProofIrrelProv co) = ProofIrrelProv <$> go_co cxt co
2624 go_prov _ p@(PluginProv _) = return p
2625
2626
2627 {-
2628 %************************************************************************
2629 %* *
2630 Miscellaneous functions
2631 %* *
2632 %************************************************************************
2633
2634 -}
2635 -- | All type constructors occurring in the type; looking through type
2636 -- synonyms, but not newtypes.
2637 -- When it finds a Class, it returns the class TyCon.
2638 tyConsOfType :: Type -> UniqSet TyCon
2639 tyConsOfType ty
2640 = go ty
2641 where
2642 go :: Type -> UniqSet TyCon -- The UniqSet does duplicate elim
2643 go ty | Just ty' <- coreView ty = go ty'
2644 go (TyVarTy {}) = emptyUniqSet
2645 go (LitTy {}) = emptyUniqSet
2646 go (TyConApp tc tys) = go_tc tc `unionUniqSets` go_s tys
2647 go (AppTy a b) = go a `unionUniqSets` go b
2648 go (FunTy a b) = go a `unionUniqSets` go b `unionUniqSets` go_tc funTyCon
2649 go (ForAllTy (TvBndr tv _) ty) = go ty `unionUniqSets` go (tyVarKind tv)
2650 go (CastTy ty co) = go ty `unionUniqSets` go_co co
2651 go (CoercionTy co) = go_co co
2652
2653 go_co (Refl ty) = go ty
2654 go_co (GRefl _ ty mco) = go ty `unionUniqSets` go_mco mco
2655 go_co (TyConAppCo _ tc args) = go_tc tc `unionUniqSets` go_cos args
2656 go_co (AppCo co arg) = go_co co `unionUniqSets` go_co arg
2657 go_co (ForAllCo _ kind_co co) = go_co kind_co `unionUniqSets` go_co co
2658 go_co (FunCo _ co1 co2) = go_co co1 `unionUniqSets` go_co co2
2659 go_co (AxiomInstCo ax _ args) = go_ax ax `unionUniqSets` go_cos args
2660 go_co (UnivCo p _ t1 t2) = go_prov p `unionUniqSets` go t1 `unionUniqSets` go t2
2661 go_co (CoVarCo {}) = emptyUniqSet
2662 go_co (HoleCo {}) = emptyUniqSet
2663 go_co (SymCo co) = go_co co
2664 go_co (TransCo co1 co2) = go_co co1 `unionUniqSets` go_co co2
2665 go_co (NthCo _ _ co) = go_co co
2666 go_co (LRCo _ co) = go_co co
2667 go_co (InstCo co arg) = go_co co `unionUniqSets` go_co arg
2668 go_co (KindCo co) = go_co co
2669 go_co (SubCo co) = go_co co
2670 go_co (AxiomRuleCo _ cs) = go_cos cs
2671
2672 go_mco MRefl = emptyUniqSet
2673 go_mco (MCo co) = go_co co
2674
2675 go_prov UnsafeCoerceProv = emptyUniqSet
2676 go_prov (PhantomProv co) = go_co co
2677 go_prov (ProofIrrelProv co) = go_co co
2678 go_prov (PluginProv _) = emptyUniqSet
2679 -- this last case can happen from the tyConsOfType used from
2680 -- checkTauTvUpdate
2681
2682 go_s tys = foldr (unionUniqSets . go) emptyUniqSet tys
2683 go_cos cos = foldr (unionUniqSets . go_co) emptyUniqSet cos
2684
2685 go_tc tc = unitUniqSet tc
2686 go_ax ax = go_tc $ coAxiomTyCon ax
2687
2688 -- | Find the result 'Kind' of a type synonym,
2689 -- after applying it to its 'arity' number of type variables
2690 -- Actually this function works fine on data types too,
2691 -- but they'd always return '*', so we never need to ask
2692 synTyConResKind :: TyCon -> Kind
2693 synTyConResKind tycon = piResultTys (tyConKind tycon) (mkTyVarTys (tyConTyVars tycon))
2694
2695 -- | Retrieve the free variables in this type, splitting them based
2696 -- on whether they are used visibly or invisibly. Invisible ones come
2697 -- first.
2698 splitVisVarsOfType :: Type -> Pair TyCoVarSet
2699 splitVisVarsOfType orig_ty = Pair invis_vars vis_vars
2700 where
2701 Pair invis_vars1 vis_vars = go orig_ty
2702 invis_vars = invis_vars1 `minusVarSet` vis_vars
2703
2704 go (TyVarTy tv) = Pair (tyCoVarsOfType $ tyVarKind tv) (unitVarSet tv)
2705 go (AppTy t1 t2) = go t1 `mappend` go t2
2706 go (TyConApp tc tys) = go_tc tc tys
2707 go (FunTy t1 t2) = go t1 `mappend` go t2
2708 go (ForAllTy (TvBndr tv _) ty)
2709 = ((`delVarSet` tv) <$> go ty) `mappend`
2710 (invisible (tyCoVarsOfType $ tyVarKind tv))
2711 go (LitTy {}) = mempty
2712 go (CastTy ty co) = go ty `mappend` invisible (tyCoVarsOfCo co)
2713 go (CoercionTy co) = invisible $ tyCoVarsOfCo co
2714
2715 invisible vs = Pair vs emptyVarSet
2716
2717 go_tc tc tys = let (invis, vis) = partitionInvisibles tc id tys in
2718 invisible (tyCoVarsOfTypes invis) `mappend` foldMap go vis
2719
2720 splitVisVarsOfTypes :: [Type] -> Pair TyCoVarSet
2721 splitVisVarsOfTypes = foldMap splitVisVarsOfType
2722
2723 modifyJoinResTy :: Int -- Number of binders to skip
2724 -> (Type -> Type) -- Function to apply to result type
2725 -> Type -- Type of join point
2726 -> Type -- New type
2727 -- INVARIANT: If any of the first n binders are foralls, those tyvars cannot
2728 -- appear in the original result type. See isValidJoinPointType.
2729 modifyJoinResTy orig_ar f orig_ty
2730 = go orig_ar orig_ty
2731 where
2732 go 0 ty = f ty
2733 go n ty | Just (arg_bndr, res_ty) <- splitPiTy_maybe ty
2734 = mkPiTy arg_bndr (go (n-1) res_ty)
2735 | otherwise
2736 = pprPanic "modifyJoinResTy" (ppr orig_ar <+> ppr orig_ty)
2737
2738 setJoinResTy :: Int -- Number of binders to skip
2739 -> Type -- New result type
2740 -> Type -- Type of join point
2741 -> Type -- New type
2742 -- INVARIANT: Same as for modifyJoinResTy
2743 setJoinResTy ar new_res_ty ty
2744 = modifyJoinResTy ar (const new_res_ty) ty
2745
2746 {-
2747 %************************************************************************
2748 %* *
2749 Pretty-printing
2750 %* *
2751 %************************************************************************
2752
2753 Most pretty-printing is either in TyCoRep or IfaceType.
2754
2755 -}
2756
2757 -- | This variant preserves any use of TYPE in a type, effectively
2758 -- locally setting -fprint-explicit-runtime-reps.
2759 pprWithTYPE :: Type -> SDoc
2760 pprWithTYPE ty = updSDocDynFlags (flip gopt_set Opt_PrintExplicitRuntimeReps) $
2761 ppr ty