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