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