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