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