Convert pprTrace in isPredTy to a WARN
[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 Constraint; 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 -> WARN( True, text "isPredTy" <+> ppr ty )
1529 False
1530 -- This last case shouldn't happen under most circumstances. It can
1531 -- occur if we call isPredTy during kind checking, especially if one
1532 -- of the following happens:
1533 --
1534 -- 1. There is actually a kind error. Example in which this showed up:
1535 -- polykinds/T11399
1536 -- 2. A type constructor application appears to be oversaturated. An
1537 -- example of this occurred in GHC Trac #13187:
1538 --
1539 -- {-# LANGUAGE PolyKinds #-}
1540 -- type Const a b = b
1541 -- f :: Const Int (,) Bool Char -> Char
1542 --
1543 -- This code is actually fine, since Const is polymorphic in its
1544 -- return kind. It does show that isPredTy could possibly report a
1545 -- false negative if a constraint is similarly oversaturated, but
1546 -- it's hard to do better than isPredTy currently does without
1547 -- zonking, so we punt on such cases for now.
1548
1549 isClassPred, isEqPred, isNomEqPred, isIPPred :: PredType -> Bool
1550 isClassPred ty = case tyConAppTyCon_maybe ty of
1551 Just tyCon | isClassTyCon tyCon -> True
1552 _ -> False
1553 isEqPred ty = case tyConAppTyCon_maybe ty of
1554 Just tyCon -> tyCon `hasKey` eqPrimTyConKey
1555 || tyCon `hasKey` eqReprPrimTyConKey
1556 _ -> False
1557
1558 isNomEqPred ty = case tyConAppTyCon_maybe ty of
1559 Just tyCon -> tyCon `hasKey` eqPrimTyConKey
1560 _ -> False
1561
1562 isIPPred ty = case tyConAppTyCon_maybe ty of
1563 Just tc -> isIPTyCon tc
1564 _ -> False
1565
1566 isIPTyCon :: TyCon -> Bool
1567 isIPTyCon tc = tc `hasKey` ipClassKey
1568 -- Class and its corresponding TyCon have the same Unique
1569
1570 isIPClass :: Class -> Bool
1571 isIPClass cls = cls `hasKey` ipClassKey
1572
1573 isCTupleClass :: Class -> Bool
1574 isCTupleClass cls = isTupleTyCon (classTyCon cls)
1575
1576 isIPPred_maybe :: Type -> Maybe (FastString, Type)
1577 isIPPred_maybe ty =
1578 do (tc,[t1,t2]) <- splitTyConApp_maybe ty
1579 guard (isIPTyCon tc)
1580 x <- isStrLitTy t1
1581 return (x,t2)
1582
1583 {-
1584 Make PredTypes
1585
1586 --------------------- Equality types ---------------------------------
1587 -}
1588
1589 -- | Makes a lifted equality predicate at the given role
1590 mkPrimEqPredRole :: Role -> Type -> Type -> PredType
1591 mkPrimEqPredRole Nominal = mkPrimEqPred
1592 mkPrimEqPredRole Representational = mkReprPrimEqPred
1593 mkPrimEqPredRole Phantom = panic "mkPrimEqPredRole phantom"
1594
1595 -- | Creates a primitive type equality predicate.
1596 -- Invariant: the types are not Coercions
1597 mkPrimEqPred :: Type -> Type -> Type
1598 mkPrimEqPred ty1 ty2
1599 = TyConApp eqPrimTyCon [k1, k2, ty1, ty2]
1600 where
1601 k1 = typeKind ty1
1602 k2 = typeKind ty2
1603
1604 -- | Creates a primite type equality predicate with explicit kinds
1605 mkHeteroPrimEqPred :: Kind -> Kind -> Type -> Type -> Type
1606 mkHeteroPrimEqPred k1 k2 ty1 ty2 = TyConApp eqPrimTyCon [k1, k2, ty1, ty2]
1607
1608 -- | Creates a primitive representational type equality predicate
1609 -- with explicit kinds
1610 mkHeteroReprPrimEqPred :: Kind -> Kind -> Type -> Type -> Type
1611 mkHeteroReprPrimEqPred k1 k2 ty1 ty2
1612 = TyConApp eqReprPrimTyCon [k1, k2, ty1, ty2]
1613
1614 -- | Try to split up a coercion type into the types that it coerces
1615 splitCoercionType_maybe :: Type -> Maybe (Type, Type)
1616 splitCoercionType_maybe ty
1617 = do { (tc, [_, _, ty1, ty2]) <- splitTyConApp_maybe ty
1618 ; guard $ tc `hasKey` eqPrimTyConKey || tc `hasKey` eqReprPrimTyConKey
1619 ; return (ty1, ty2) }
1620
1621 mkReprPrimEqPred :: Type -> Type -> Type
1622 mkReprPrimEqPred ty1 ty2
1623 = TyConApp eqReprPrimTyCon [k1, k2, ty1, ty2]
1624 where
1625 k1 = typeKind ty1
1626 k2 = typeKind ty2
1627
1628 equalityTyCon :: Role -> TyCon
1629 equalityTyCon Nominal = eqPrimTyCon
1630 equalityTyCon Representational = eqReprPrimTyCon
1631 equalityTyCon Phantom = eqPhantPrimTyCon
1632
1633 -- --------------------- Dictionary types ---------------------------------
1634
1635 mkClassPred :: Class -> [Type] -> PredType
1636 mkClassPred clas tys = TyConApp (classTyCon clas) tys
1637
1638 isDictTy :: Type -> Bool
1639 isDictTy = isClassPred
1640
1641 isDictLikeTy :: Type -> Bool
1642 -- Note [Dictionary-like types]
1643 isDictLikeTy ty | Just ty' <- coreView ty = isDictLikeTy ty'
1644 isDictLikeTy ty = case splitTyConApp_maybe ty of
1645 Just (tc, tys) | isClassTyCon tc -> True
1646 | isTupleTyCon tc -> all isDictLikeTy tys
1647 _other -> False
1648
1649 {-
1650 Note [Dictionary-like types]
1651 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1652 Being "dictionary-like" means either a dictionary type or a tuple thereof.
1653 In GHC 6.10 we build implication constraints which construct such tuples,
1654 and if we land up with a binding
1655 t :: (C [a], Eq [a])
1656 t = blah
1657 then we want to treat t as cheap under "-fdicts-cheap" for example.
1658 (Implication constraints are normally inlined, but sadly not if the
1659 occurrence is itself inside an INLINE function! Until we revise the
1660 handling of implication constraints, that is.) This turned out to
1661 be important in getting good arities in DPH code. Example:
1662
1663 class C a
1664 class D a where { foo :: a -> a }
1665 instance C a => D (Maybe a) where { foo x = x }
1666
1667 bar :: (C a, C b) => a -> b -> (Maybe a, Maybe b)
1668 {-# INLINE bar #-}
1669 bar x y = (foo (Just x), foo (Just y))
1670
1671 Then 'bar' should jolly well have arity 4 (two dicts, two args), but
1672 we ended up with something like
1673 bar = __inline_me__ (\d1,d2. let t :: (D (Maybe a), D (Maybe b)) = ...
1674 in \x,y. <blah>)
1675
1676 This is all a bit ad-hoc; eg it relies on knowing that implication
1677 constraints build tuples.
1678
1679
1680 Decomposing PredType
1681 -}
1682
1683 -- | A choice of equality relation. This is separate from the type 'Role'
1684 -- because 'Phantom' does not define a (non-trivial) equality relation.
1685 data EqRel = NomEq | ReprEq
1686 deriving (Eq, Ord)
1687
1688 instance Outputable EqRel where
1689 ppr NomEq = text "nominal equality"
1690 ppr ReprEq = text "representational equality"
1691
1692 eqRelRole :: EqRel -> Role
1693 eqRelRole NomEq = Nominal
1694 eqRelRole ReprEq = Representational
1695
1696 data PredTree = ClassPred Class [Type]
1697 | EqPred EqRel Type Type
1698 | IrredPred PredType
1699
1700 classifyPredType :: PredType -> PredTree
1701 classifyPredType ev_ty = case splitTyConApp_maybe ev_ty of
1702 Just (tc, [_, _, ty1, ty2])
1703 | tc `hasKey` eqReprPrimTyConKey -> EqPred ReprEq ty1 ty2
1704 | tc `hasKey` eqPrimTyConKey -> EqPred NomEq ty1 ty2
1705 Just (tc, tys)
1706 | Just clas <- tyConClass_maybe tc -> ClassPred clas tys
1707 _ -> IrredPred ev_ty
1708
1709 getClassPredTys :: PredType -> (Class, [Type])
1710 getClassPredTys ty = case getClassPredTys_maybe ty of
1711 Just (clas, tys) -> (clas, tys)
1712 Nothing -> pprPanic "getClassPredTys" (ppr ty)
1713
1714 getClassPredTys_maybe :: PredType -> Maybe (Class, [Type])
1715 getClassPredTys_maybe ty = case splitTyConApp_maybe ty of
1716 Just (tc, tys) | Just clas <- tyConClass_maybe tc -> Just (clas, tys)
1717 _ -> Nothing
1718
1719 getEqPredTys :: PredType -> (Type, Type)
1720 getEqPredTys ty
1721 = case splitTyConApp_maybe ty of
1722 Just (tc, [_, _, ty1, ty2])
1723 | tc `hasKey` eqPrimTyConKey
1724 || tc `hasKey` eqReprPrimTyConKey
1725 -> (ty1, ty2)
1726 _ -> pprPanic "getEqPredTys" (ppr ty)
1727
1728 getEqPredTys_maybe :: PredType -> Maybe (Role, Type, Type)
1729 getEqPredTys_maybe ty
1730 = case splitTyConApp_maybe ty of
1731 Just (tc, [_, _, ty1, ty2])
1732 | tc `hasKey` eqPrimTyConKey -> Just (Nominal, ty1, ty2)
1733 | tc `hasKey` eqReprPrimTyConKey -> Just (Representational, ty1, ty2)
1734 _ -> Nothing
1735
1736 getEqPredRole :: PredType -> Role
1737 getEqPredRole ty = eqRelRole (predTypeEqRel ty)
1738
1739 -- | Get the equality relation relevant for a pred type.
1740 predTypeEqRel :: PredType -> EqRel
1741 predTypeEqRel ty
1742 | Just (tc, _) <- splitTyConApp_maybe ty
1743 , tc `hasKey` eqReprPrimTyConKey
1744 = ReprEq
1745 | otherwise
1746 = NomEq
1747
1748 {-
1749 %************************************************************************
1750 %* *
1751 Well-scoped tyvars
1752 * *
1753 ************************************************************************
1754 -}
1755
1756 -- | Do a topological sort on a list of tyvars,
1757 -- so that binders occur before occurrences
1758 -- E.g. given [ a::k, k::*, b::k ]
1759 -- it'll return a well-scoped list [ k::*, a::k, b::k ]
1760 --
1761 -- This is a deterministic sorting operation
1762 -- (that is, doesn't depend on Uniques).
1763 toposortTyVars :: [TyVar] -> [TyVar]
1764 toposortTyVars tvs = reverse $
1765 [ tv | (tv, _, _) <- topologicalSortG $
1766 graphFromEdgedVerticesOrd nodes ]
1767 where
1768 var_ids :: VarEnv Int
1769 var_ids = mkVarEnv (zip tvs [1..])
1770
1771 nodes = [ ( tv
1772 , lookupVarEnv_NF var_ids tv
1773 , mapMaybe (lookupVarEnv var_ids)
1774 (tyCoVarsOfTypeList (tyVarKind tv)) )
1775 | tv <- tvs ]
1776
1777 -- | Extract a well-scoped list of variables from a deterministic set of
1778 -- variables. The result is deterministic.
1779 -- NB: There used to exist varSetElemsWellScoped :: VarSet -> [Var] which
1780 -- took a non-deterministic set and produced a non-deterministic
1781 -- well-scoped list. If you care about the list being well-scoped you also
1782 -- most likely care about it being in deterministic order.
1783 dVarSetElemsWellScoped :: DVarSet -> [Var]
1784 dVarSetElemsWellScoped = toposortTyVars . dVarSetElems
1785
1786 -- | Get the free vars of a type in scoped order
1787 tyCoVarsOfTypeWellScoped :: Type -> [TyVar]
1788 tyCoVarsOfTypeWellScoped = toposortTyVars . tyCoVarsOfTypeList
1789
1790 -- | Get the free vars of types in scoped order
1791 tyCoVarsOfTypesWellScoped :: [Type] -> [TyVar]
1792 tyCoVarsOfTypesWellScoped = toposortTyVars . tyCoVarsOfTypesList
1793
1794 {-
1795 ************************************************************************
1796 * *
1797 \subsection{Type families}
1798 * *
1799 ************************************************************************
1800 -}
1801
1802 mkFamilyTyConApp :: TyCon -> [Type] -> Type
1803 -- ^ Given a family instance TyCon and its arg types, return the
1804 -- corresponding family type. E.g:
1805 --
1806 -- > data family T a
1807 -- > data instance T (Maybe b) = MkT b
1808 --
1809 -- Where the instance tycon is :RTL, so:
1810 --
1811 -- > mkFamilyTyConApp :RTL Int = T (Maybe Int)
1812 mkFamilyTyConApp tc tys
1813 | Just (fam_tc, fam_tys) <- tyConFamInst_maybe tc
1814 , let tvs = tyConTyVars tc
1815 fam_subst = ASSERT2( length tvs == length tys, ppr tc <+> ppr tys )
1816 zipTvSubst tvs tys
1817 = mkTyConApp fam_tc (substTys fam_subst fam_tys)
1818 | otherwise
1819 = mkTyConApp tc tys
1820
1821 -- | Get the type on the LHS of a coercion induced by a type/data
1822 -- family instance.
1823 coAxNthLHS :: CoAxiom br -> Int -> Type
1824 coAxNthLHS ax ind =
1825 mkTyConApp (coAxiomTyCon ax) (coAxBranchLHS (coAxiomNthBranch ax ind))
1826
1827 -- | Pretty prints a 'TyCon', using the family instance in case of a
1828 -- representation tycon. For example:
1829 --
1830 -- > data T [a] = ...
1831 --
1832 -- In that case we want to print @T [a]@, where @T@ is the family 'TyCon'
1833 pprSourceTyCon :: TyCon -> SDoc
1834 pprSourceTyCon tycon
1835 | Just (fam_tc, tys) <- tyConFamInst_maybe tycon
1836 = ppr $ fam_tc `TyConApp` tys -- can't be FunTyCon
1837 | otherwise
1838 = ppr tycon
1839
1840 -- @isTauTy@ tests if a type has no foralls
1841 isFamFreeTy :: Type -> Bool
1842 isFamFreeTy ty | Just ty' <- coreView ty = isFamFreeTy ty'
1843 isFamFreeTy (TyVarTy _) = True
1844 isFamFreeTy (LitTy {}) = True
1845 isFamFreeTy (TyConApp tc tys) = all isFamFreeTy tys && isFamFreeTyCon tc
1846 isFamFreeTy (AppTy a b) = isFamFreeTy a && isFamFreeTy b
1847 isFamFreeTy (FunTy a b) = isFamFreeTy a && isFamFreeTy b
1848 isFamFreeTy (ForAllTy _ ty) = isFamFreeTy ty
1849 isFamFreeTy (CastTy ty _) = isFamFreeTy ty
1850 isFamFreeTy (CoercionTy _) = False -- Not sure about this
1851
1852 {-
1853 ************************************************************************
1854 * *
1855 \subsection{Liftedness}
1856 * *
1857 ************************************************************************
1858 -}
1859
1860 -- | Returns Just True if this type is surely lifted, Just False
1861 -- if it is surely unlifted, Nothing if we can't be sure (i.e., it is
1862 -- levity polymorphic), and panics if the kind does not have the shape
1863 -- TYPE r.
1864 isLiftedType_maybe :: HasDebugCallStack => Type -> Maybe Bool
1865 isLiftedType_maybe ty = go (getRuntimeRep "isLiftedType_maybe" ty)
1866 where
1867 go rr | Just rr' <- coreView rr = go rr'
1868 go (TyConApp lifted_rep [])
1869 | lifted_rep `hasKey` liftedRepDataConKey = Just True
1870 go (TyConApp {}) = Just False -- everything else is unlifted
1871 go _ = Nothing -- levity polymorphic
1872
1873 -- | See "Type#type_classification" for what an unlifted type is.
1874 -- Panics on levity polymorphic types.
1875 isUnliftedType :: HasDebugCallStack => Type -> Bool
1876 -- isUnliftedType returns True for forall'd unlifted types:
1877 -- x :: forall a. Int#
1878 -- I found bindings like these were getting floated to the top level.
1879 -- They are pretty bogus types, mind you. It would be better never to
1880 -- construct them
1881 isUnliftedType ty
1882 = not (isLiftedType_maybe ty `orElse`
1883 pprPanic "isUnliftedType" (ppr ty <+> dcolon <+> ppr (typeKind ty)))
1884
1885 -- | Extract the RuntimeRep classifier of a type. Panics if this is not possible.
1886 getRuntimeRep :: HasDebugCallStack
1887 => String -- ^ Printed in case of an error
1888 -> Type -> Type
1889 getRuntimeRep err ty = getRuntimeRepFromKind err (typeKind ty)
1890
1891 -- | Extract the RuntimeRep classifier of a type from its kind.
1892 -- For example, getRuntimeRepFromKind * = LiftedRep;
1893 -- Panics if this is not possible.
1894 getRuntimeRepFromKind :: HasDebugCallStack
1895 => String -- ^ Printed in case of an error
1896 -> Type -> Type
1897 getRuntimeRepFromKind err = go
1898 where
1899 go k | Just k' <- coreViewOneStarKind k = go k'
1900 go k
1901 | (_tc, [arg]) <- splitTyConApp k
1902 = ASSERT2( _tc `hasKey` tYPETyConKey, text err $$ ppr k )
1903 arg
1904 go k = pprPanic "getRuntimeRep" (text err $$
1905 ppr k <+> dcolon <+> ppr (typeKind k))
1906
1907 isUnboxedTupleType :: Type -> Bool
1908 isUnboxedTupleType ty
1909 = tyConAppTyCon (getRuntimeRep "isUnboxedTupleType" ty) `hasKey` tupleRepDataConKey
1910 -- NB: Do not use typePrimRep, as that can't tell the difference between
1911 -- unboxed tuples and unboxed sums
1912
1913
1914 isUnboxedSumType :: Type -> Bool
1915 isUnboxedSumType ty
1916 = tyConAppTyCon (getRuntimeRep "isUnboxedSumType" ty) `hasKey` sumRepDataConKey
1917
1918 -- | See "Type#type_classification" for what an algebraic type is.
1919 -- Should only be applied to /types/, as opposed to e.g. partially
1920 -- saturated type constructors
1921 isAlgType :: Type -> Bool
1922 isAlgType ty
1923 = case splitTyConApp_maybe ty of
1924 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
1925 isAlgTyCon tc
1926 _other -> False
1927
1928 -- | See "Type#type_classification" for what an algebraic type is.
1929 -- Should only be applied to /types/, as opposed to e.g. partially
1930 -- saturated type constructors. Closed type constructors are those
1931 -- with a fixed right hand side, as opposed to e.g. associated types
1932 isClosedAlgType :: Type -> Bool
1933 isClosedAlgType ty
1934 = case splitTyConApp_maybe ty of
1935 Just (tc, ty_args) | isAlgTyCon tc && not (isFamilyTyCon tc)
1936 -> ASSERT2( ty_args `lengthIs` tyConArity tc, ppr ty ) True
1937 _other -> False
1938
1939 -- | Computes whether an argument (or let right hand side) should
1940 -- be computed strictly or lazily, based only on its type.
1941 -- Currently, it's just 'isUnliftedType'. Panics on levity-polymorphic types.
1942 isStrictType :: HasDebugCallStack => Type -> Bool
1943 isStrictType = isUnliftedType
1944
1945 isPrimitiveType :: Type -> Bool
1946 -- ^ Returns true of types that are opaque to Haskell.
1947 isPrimitiveType ty = case splitTyConApp_maybe ty of
1948 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
1949 isPrimTyCon tc
1950 _ -> False
1951
1952 {-
1953 ************************************************************************
1954 * *
1955 \subsection{Sequencing on types}
1956 * *
1957 ************************************************************************
1958 -}
1959
1960 seqType :: Type -> ()
1961 seqType (LitTy n) = n `seq` ()
1962 seqType (TyVarTy tv) = tv `seq` ()
1963 seqType (AppTy t1 t2) = seqType t1 `seq` seqType t2
1964 seqType (FunTy t1 t2) = seqType t1 `seq` seqType t2
1965 seqType (TyConApp tc tys) = tc `seq` seqTypes tys
1966 seqType (ForAllTy (TvBndr tv _) ty) = seqType (tyVarKind tv) `seq` seqType ty
1967 seqType (CastTy ty co) = seqType ty `seq` seqCo co
1968 seqType (CoercionTy co) = seqCo co
1969
1970 seqTypes :: [Type] -> ()
1971 seqTypes [] = ()
1972 seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
1973
1974 {-
1975 ************************************************************************
1976 * *
1977 Comparison for types
1978 (We don't use instances so that we know where it happens)
1979 * *
1980 ************************************************************************
1981
1982 Note [Equality on AppTys]
1983 ~~~~~~~~~~~~~~~~~~~~~~~~~
1984 In our cast-ignoring equality, we want to say that the following two
1985 are equal:
1986
1987 (Maybe |> co) (Int |> co') ~? Maybe Int
1988
1989 But the left is an AppTy while the right is a TyConApp. The solution is
1990 to use repSplitAppTy_maybe to break up the TyConApp into its pieces and
1991 then continue. Easy to do, but also easy to forget to do.
1992
1993 -}
1994
1995 eqType :: Type -> Type -> Bool
1996 -- ^ Type equality on source types. Does not look through @newtypes@ or
1997 -- 'PredType's, but it does look through type synonyms.
1998 -- This first checks that the kinds of the types are equal and then
1999 -- checks whether the types are equal, ignoring casts and coercions.
2000 -- (The kind check is a recursive call, but since all kinds have type
2001 -- @Type@, there is no need to check the types of kinds.)
2002 -- See also Note [Non-trivial definitional equality] in TyCoRep.
2003 eqType t1 t2 = isEqual $ nonDetCmpType t1 t2
2004 -- It's OK to use nonDetCmpType here and eqType is deterministic,
2005 -- nonDetCmpType does equality deterministically
2006
2007 -- | Compare types with respect to a (presumably) non-empty 'RnEnv2'.
2008 eqTypeX :: RnEnv2 -> Type -> Type -> Bool
2009 eqTypeX env t1 t2 = isEqual $ nonDetCmpTypeX env t1 t2
2010 -- It's OK to use nonDetCmpType here and eqTypeX is deterministic,
2011 -- nonDetCmpTypeX does equality deterministically
2012
2013 -- | Type equality on lists of types, looking through type synonyms
2014 -- but not newtypes.
2015 eqTypes :: [Type] -> [Type] -> Bool
2016 eqTypes tys1 tys2 = isEqual $ nonDetCmpTypes tys1 tys2
2017 -- It's OK to use nonDetCmpType here and eqTypes is deterministic,
2018 -- nonDetCmpTypes does equality deterministically
2019
2020 eqVarBndrs :: RnEnv2 -> [Var] -> [Var] -> Maybe RnEnv2
2021 -- Check that the var lists are the same length
2022 -- and have matching kinds; if so, extend the RnEnv2
2023 -- Returns Nothing if they don't match
2024 eqVarBndrs env [] []
2025 = Just env
2026 eqVarBndrs env (tv1:tvs1) (tv2:tvs2)
2027 | eqTypeX env (tyVarKind tv1) (tyVarKind tv2)
2028 = eqVarBndrs (rnBndr2 env tv1 tv2) tvs1 tvs2
2029 eqVarBndrs _ _ _= Nothing
2030
2031 -- Now here comes the real worker
2032
2033 {-
2034 Note [nonDetCmpType nondeterminism]
2035 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2036 nonDetCmpType is implemented in terms of nonDetCmpTypeX. nonDetCmpTypeX
2037 uses nonDetCmpTc which compares TyCons by their Unique value. Using Uniques for
2038 ordering leads to nondeterminism. We hit the same problem in the TyVarTy case,
2039 comparing type variables is nondeterministic, note the call to nonDetCmpVar in
2040 nonDetCmpTypeX.
2041 See Note [Unique Determinism] for more details.
2042 -}
2043
2044 nonDetCmpType :: Type -> Type -> Ordering
2045 nonDetCmpType t1 t2
2046 -- we know k1 and k2 have the same kind, because they both have kind *.
2047 = nonDetCmpTypeX rn_env t1 t2
2048 where
2049 rn_env = mkRnEnv2 (mkInScopeSet (tyCoVarsOfTypes [t1, t2]))
2050
2051 nonDetCmpTypes :: [Type] -> [Type] -> Ordering
2052 nonDetCmpTypes ts1 ts2 = nonDetCmpTypesX rn_env ts1 ts2
2053 where
2054 rn_env = mkRnEnv2 (mkInScopeSet (tyCoVarsOfTypes (ts1 ++ ts2)))
2055
2056 -- | An ordering relation between two 'Type's (known below as @t1 :: k1@
2057 -- and @t2 :: k2@)
2058 data TypeOrdering = TLT -- ^ @t1 < t2@
2059 | TEQ -- ^ @t1 ~ t2@ and there are no casts in either,
2060 -- therefore we can conclude @k1 ~ k2@
2061 | TEQX -- ^ @t1 ~ t2@ yet one of the types contains a cast so
2062 -- they may differ in kind.
2063 | TGT -- ^ @t1 > t2@
2064 deriving (Eq, Ord, Enum, Bounded)
2065
2066 nonDetCmpTypeX :: RnEnv2 -> Type -> Type -> Ordering -- Main workhorse
2067 -- See Note [Non-trivial definitional equality] in TyCoRep
2068 nonDetCmpTypeX env orig_t1 orig_t2 =
2069 case go env orig_t1 orig_t2 of
2070 -- If there are casts then we also need to do a comparison of the kinds of
2071 -- the types being compared
2072 TEQX -> toOrdering $ go env k1 k2
2073 ty_ordering -> toOrdering ty_ordering
2074 where
2075 k1 = typeKind orig_t1
2076 k2 = typeKind orig_t2
2077
2078 toOrdering :: TypeOrdering -> Ordering
2079 toOrdering TLT = LT
2080 toOrdering TEQ = EQ
2081 toOrdering TEQX = EQ
2082 toOrdering TGT = GT
2083
2084 liftOrdering :: Ordering -> TypeOrdering
2085 liftOrdering LT = TLT
2086 liftOrdering EQ = TEQ
2087 liftOrdering GT = TGT
2088
2089 thenCmpTy :: TypeOrdering -> TypeOrdering -> TypeOrdering
2090 thenCmpTy TEQ rel = rel
2091 thenCmpTy TEQX rel = hasCast rel
2092 thenCmpTy rel _ = rel
2093
2094 hasCast :: TypeOrdering -> TypeOrdering
2095 hasCast TEQ = TEQX
2096 hasCast rel = rel
2097
2098 -- Returns both the resulting ordering relation between the two types
2099 -- and whether either contains a cast.
2100 go :: RnEnv2 -> Type -> Type -> TypeOrdering
2101 go env t1 t2
2102 | Just t1' <- coreViewOneStarKind t1 = go env t1' t2
2103 | Just t2' <- coreViewOneStarKind t2 = go env t1 t2'
2104
2105 go env (TyVarTy tv1) (TyVarTy tv2)
2106 = liftOrdering $ rnOccL env tv1 `nonDetCmpVar` rnOccR env tv2
2107 go env (ForAllTy (TvBndr tv1 _) t1) (ForAllTy (TvBndr tv2 _) t2)
2108 = go env (tyVarKind tv1) (tyVarKind tv2)
2109 `thenCmpTy` go (rnBndr2 env tv1 tv2) t1 t2
2110 -- See Note [Equality on AppTys]
2111 go env (AppTy s1 t1) ty2
2112 | Just (s2, t2) <- repSplitAppTy_maybe ty2
2113 = go env s1 s2 `thenCmpTy` go env t1 t2
2114 go env ty1 (AppTy s2 t2)
2115 | Just (s1, t1) <- repSplitAppTy_maybe ty1
2116 = go env s1 s2 `thenCmpTy` go env t1 t2
2117 go env (FunTy s1 t1) (FunTy s2 t2)
2118 = go env s1 s2 `thenCmpTy` go env t1 t2
2119 go env (TyConApp tc1 tys1) (TyConApp tc2 tys2)
2120 = liftOrdering (tc1 `nonDetCmpTc` tc2) `thenCmpTy` gos env tys1 tys2
2121 go _ (LitTy l1) (LitTy l2) = liftOrdering (compare l1 l2)
2122 go env (CastTy t1 _) t2 = hasCast $ go env t1 t2
2123 go env t1 (CastTy t2 _) = hasCast $ go env t1 t2
2124 go _ (CoercionTy {}) (CoercionTy {}) = TEQ
2125
2126 -- Deal with the rest: TyVarTy < CoercionTy < AppTy < LitTy < TyConApp < ForAllTy
2127 go _ ty1 ty2
2128 = liftOrdering $ (get_rank ty1) `compare` (get_rank ty2)
2129 where get_rank :: Type -> Int
2130 get_rank (CastTy {})
2131 = pprPanic "nonDetCmpTypeX.get_rank" (ppr [ty1,ty2])
2132 get_rank (TyVarTy {}) = 0
2133 get_rank (CoercionTy {}) = 1
2134 get_rank (AppTy {}) = 3
2135 get_rank (LitTy {}) = 4
2136 get_rank (TyConApp {}) = 5
2137 get_rank (FunTy {}) = 6
2138 get_rank (ForAllTy {}) = 7
2139
2140 gos :: RnEnv2 -> [Type] -> [Type] -> TypeOrdering
2141 gos _ [] [] = TEQ
2142 gos _ [] _ = TLT
2143 gos _ _ [] = TGT
2144 gos env (ty1:tys1) (ty2:tys2) = go env ty1 ty2 `thenCmpTy` gos env tys1 tys2
2145
2146 -------------
2147 nonDetCmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
2148 nonDetCmpTypesX _ [] [] = EQ
2149 nonDetCmpTypesX env (t1:tys1) (t2:tys2) = nonDetCmpTypeX env t1 t2
2150 `thenCmp` nonDetCmpTypesX env tys1 tys2
2151 nonDetCmpTypesX _ [] _ = LT
2152 nonDetCmpTypesX _ _ [] = GT
2153
2154 -------------
2155 -- | Compare two 'TyCon's. NB: This should /never/ see the "star synonyms",
2156 -- as recognized by Kind.isStarKindSynonymTyCon. See Note
2157 -- [Kind Constraint and kind *] in Kind.
2158 -- See Note [nonDetCmpType nondeterminism]
2159 nonDetCmpTc :: TyCon -> TyCon -> Ordering
2160 nonDetCmpTc tc1 tc2
2161 = ASSERT( not (isStarKindSynonymTyCon tc1) && not (isStarKindSynonymTyCon tc2) )
2162 u1 `nonDetCmpUnique` u2
2163 where
2164 u1 = tyConUnique tc1
2165 u2 = tyConUnique tc2
2166
2167 {-
2168 ************************************************************************
2169 * *
2170 The kind of a type
2171 * *
2172 ************************************************************************
2173 -}
2174
2175 typeKind :: Type -> Kind
2176 typeKind (TyConApp tc tys) = piResultTys (tyConKind tc) tys
2177 typeKind (AppTy fun arg) = piResultTy (typeKind fun) arg
2178 typeKind (LitTy l) = typeLiteralKind l
2179 typeKind (FunTy {}) = liftedTypeKind
2180 typeKind (ForAllTy _ ty) = typeKind ty
2181 typeKind (TyVarTy tyvar) = tyVarKind tyvar
2182 typeKind (CastTy _ty co) = pSnd $ coercionKind co
2183 typeKind (CoercionTy co) = coercionType co
2184
2185 typeLiteralKind :: TyLit -> Kind
2186 typeLiteralKind l =
2187 case l of
2188 NumTyLit _ -> typeNatKind
2189 StrTyLit _ -> typeSymbolKind
2190
2191 -- | Returns True if a type is levity polymorphic. Should be the same
2192 -- as (isKindLevPoly . typeKind) but much faster.
2193 -- Precondition: The type has kind (TYPE blah)
2194 isTypeLevPoly :: Type -> Bool
2195 isTypeLevPoly = go
2196 where
2197 go ty@(TyVarTy {}) = check_kind ty
2198 go ty@(AppTy {}) = check_kind ty
2199 go ty@(TyConApp tc _) | not (isTcLevPoly tc) = False
2200 | otherwise = check_kind ty
2201 go (ForAllTy _ ty) = go ty
2202 go (FunTy {}) = False
2203 go (LitTy {}) = False
2204 go ty@(CastTy {}) = check_kind ty
2205 go ty@(CoercionTy {}) = pprPanic "isTypeLevPoly co" (ppr ty)
2206
2207 check_kind = isKindLevPoly . typeKind
2208
2209 -- | Looking past all pi-types, is the end result potentially levity polymorphic?
2210 -- Example: True for (forall r (a :: TYPE r). String -> a)
2211 -- Example: False for (forall r1 r2 (a :: TYPE r1) (b :: TYPE r2). a -> b -> Type)
2212 resultIsLevPoly :: Type -> Bool
2213 resultIsLevPoly = isTypeLevPoly . snd . splitPiTys
2214
2215 {-
2216 %************************************************************************
2217 %* *
2218 Miscellaneous functions
2219 %* *
2220 %************************************************************************
2221
2222 -}
2223 -- | All type constructors occurring in the type; looking through type
2224 -- synonyms, but not newtypes.
2225 -- When it finds a Class, it returns the class TyCon.
2226 tyConsOfType :: Type -> NameEnv TyCon
2227 tyConsOfType ty
2228 = go ty
2229 where
2230 go :: Type -> NameEnv TyCon -- The NameEnv does duplicate elim
2231 go ty | Just ty' <- coreView ty = go ty'
2232 go (TyVarTy {}) = emptyNameEnv
2233 go (LitTy {}) = emptyNameEnv
2234 go (TyConApp tc tys) = go_tc tc `plusNameEnv` go_s tys
2235 go (AppTy a b) = go a `plusNameEnv` go b
2236 go (FunTy a b) = go a `plusNameEnv` go b `plusNameEnv` go_tc funTyCon
2237 go (ForAllTy (TvBndr tv _) ty) = go ty `plusNameEnv` go (tyVarKind tv)
2238 go (CastTy ty co) = go ty `plusNameEnv` go_co co
2239 go (CoercionTy co) = go_co co
2240
2241 go_co (Refl _ ty) = go ty
2242 go_co (TyConAppCo _ tc args) = go_tc tc `plusNameEnv` go_cos args
2243 go_co (AppCo co arg) = go_co co `plusNameEnv` go_co arg
2244 go_co (ForAllCo _ kind_co co) = go_co kind_co `plusNameEnv` go_co co
2245 go_co (CoVarCo {}) = emptyNameEnv
2246 go_co (AxiomInstCo ax _ args) = go_ax ax `plusNameEnv` go_cos args
2247 go_co (UnivCo p _ t1 t2) = go_prov p `plusNameEnv` go t1 `plusNameEnv` go t2
2248 go_co (SymCo co) = go_co co
2249 go_co (TransCo co1 co2) = go_co co1 `plusNameEnv` go_co co2
2250 go_co (NthCo _ co) = go_co co
2251 go_co (LRCo _ co) = go_co co
2252 go_co (InstCo co arg) = go_co co `plusNameEnv` go_co arg
2253 go_co (CoherenceCo co1 co2) = go_co co1 `plusNameEnv` go_co co2
2254 go_co (KindCo co) = go_co co
2255 go_co (SubCo co) = go_co co
2256 go_co (AxiomRuleCo _ cs) = go_cos cs
2257
2258 go_prov UnsafeCoerceProv = emptyNameEnv
2259 go_prov (PhantomProv co) = go_co co
2260 go_prov (ProofIrrelProv co) = go_co co
2261 go_prov (PluginProv _) = emptyNameEnv
2262 go_prov (HoleProv _) = emptyNameEnv
2263 -- this last case can happen from the tyConsOfType used from
2264 -- checkTauTvUpdate
2265
2266 go_s tys = foldr (plusNameEnv . go) emptyNameEnv tys
2267 go_cos cos = foldr (plusNameEnv . go_co) emptyNameEnv cos
2268
2269 go_tc tc = unitNameEnv (tyConName tc) tc
2270 go_ax ax = go_tc $ coAxiomTyCon ax
2271
2272 -- | Find the result 'Kind' of a type synonym,
2273 -- after applying it to its 'arity' number of type variables
2274 -- Actually this function works fine on data types too,
2275 -- but they'd always return '*', so we never need to ask
2276 synTyConResKind :: TyCon -> Kind
2277 synTyConResKind tycon = piResultTys (tyConKind tycon) (mkTyVarTys (tyConTyVars tycon))
2278
2279 -- | Retrieve the free variables in this type, splitting them based
2280 -- on whether they are used visibly or invisibly. Invisible ones come
2281 -- first.
2282 splitVisVarsOfType :: Type -> Pair TyCoVarSet
2283 splitVisVarsOfType orig_ty = Pair invis_vars vis_vars
2284 where
2285 Pair invis_vars1 vis_vars = go orig_ty
2286 invis_vars = invis_vars1 `minusVarSet` vis_vars
2287
2288 go (TyVarTy tv) = Pair (tyCoVarsOfType $ tyVarKind tv) (unitVarSet tv)
2289 go (AppTy t1 t2) = go t1 `mappend` go t2
2290 go (TyConApp tc tys) = go_tc tc tys
2291 go (FunTy t1 t2) = go t1 `mappend` go t2
2292 go (ForAllTy (TvBndr tv _) ty)
2293 = ((`delVarSet` tv) <$> go ty) `mappend`
2294 (invisible (tyCoVarsOfType $ tyVarKind tv))
2295 go (LitTy {}) = mempty
2296 go (CastTy ty co) = go ty `mappend` invisible (tyCoVarsOfCo co)
2297 go (CoercionTy co) = invisible $ tyCoVarsOfCo co
2298
2299 invisible vs = Pair vs emptyVarSet
2300
2301 go_tc tc tys = let (invis, vis) = partitionInvisibles tc id tys in
2302 invisible (tyCoVarsOfTypes invis) `mappend` foldMap go vis
2303
2304 splitVisVarsOfTypes :: [Type] -> Pair TyCoVarSet
2305 splitVisVarsOfTypes = foldMap splitVisVarsOfType