69d1f7c60c34a68c5f42b153b060196145d8f54b
[ghc.git] / compiler / typecheck / TcType.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5 \section[TcType]{Types used in the typechecker}
6
7 This module provides the Type interface for front-end parts of the
8 compiler. These parts
9
10 * treat "source types" as opaque:
11 newtypes, and predicates are meaningful.
12 * look through usage types
13
14 The "tc" prefix is for "TypeChecker", because the type checker
15 is the principal client.
16 -}
17
18 {-# LANGUAGE CPP, MultiWayIf, FlexibleContexts #-}
19
20 module TcType (
21 --------------------------------
22 -- Types
23 TcType, TcSigmaType, TcRhoType, TcTauType, TcPredType, TcThetaType,
24 TcTyVar, TcTyVarSet, TcDTyVarSet, TcTyCoVarSet, TcDTyCoVarSet,
25 TcKind, TcCoVar, TcTyCoVar, TcTyVarBinder, TcTyCon,
26
27 ExpType(..), InferResult(..), ExpSigmaType, ExpRhoType, mkCheckExpType,
28
29 SyntaxOpType(..), synKnownType, mkSynFunTys,
30
31 -- TcLevel
32 TcLevel(..), topTcLevel, pushTcLevel, isTopTcLevel,
33 strictlyDeeperThan, sameDepthAs, fmvTcLevel,
34 tcTypeLevel, tcTyVarLevel, maxTcLevel,
35
36 --------------------------------
37 -- MetaDetails
38 UserTypeCtxt(..), pprUserTypeCtxt, isSigMaybe,
39 TcTyVarDetails(..), pprTcTyVarDetails, vanillaSkolemTv, superSkolemTv,
40 MetaDetails(Flexi, Indirect), MetaInfo(..),
41 isImmutableTyVar, isSkolemTyVar, isMetaTyVar, isMetaTyVarTy, isTyVarTy,
42 isSigTyVar, isOverlappableTyVar, isTyConableTyVar,
43 isFskTyVar, isFmvTyVar, isFlattenTyVar,
44 isAmbiguousTyVar, metaTyVarRef, metaTyVarInfo,
45 isFlexi, isIndirect, isRuntimeUnkSkol,
46 metaTyVarTcLevel, setMetaTyVarTcLevel, metaTyVarTcLevel_maybe,
47 isTouchableMetaTyVar, isTouchableOrFmv,
48 isFloatedTouchableMetaTyVar,
49
50 --------------------------------
51 -- Builders
52 mkPhiTy, mkInfSigmaTy, mkSpecSigmaTy, mkSigmaTy,
53 mkNakedTyConApp, mkNakedAppTys, mkNakedAppTy,
54 mkNakedCastTy,
55
56 --------------------------------
57 -- Splitters
58 -- These are important because they do not look through newtypes
59 getTyVar,
60 tcSplitForAllTy_maybe,
61 tcSplitForAllTys, tcSplitPiTys, tcSplitForAllTyVarBndrs,
62 tcSplitPhiTy, tcSplitPredFunTy_maybe,
63 tcSplitFunTy_maybe, tcSplitFunTys, tcFunArgTy, tcFunResultTy, tcFunResultTyN,
64 tcSplitFunTysN,
65 tcSplitTyConApp, tcSplitTyConApp_maybe,
66 tcRepSplitTyConApp_maybe, tcRepSplitTyConApp_maybe',
67 tcTyConAppTyCon, tcTyConAppTyCon_maybe, tcTyConAppArgs,
68 tcSplitAppTy_maybe, tcSplitAppTy, tcSplitAppTys, tcRepSplitAppTy_maybe,
69 tcGetTyVar_maybe, tcGetTyVar, nextRole,
70 tcSplitSigmaTy, tcSplitNestedSigmaTys, tcDeepSplitSigmaTy_maybe,
71
72 ---------------------------------
73 -- Predicates.
74 -- Again, newtypes are opaque
75 eqType, eqTypes, nonDetCmpType, nonDetCmpTypes, eqTypeX,
76 pickyEqType, tcEqType, tcEqKind, tcEqTypeNoKindCheck, tcEqTypeVis,
77 isSigmaTy, isRhoTy, isRhoExpTy, isOverloadedTy,
78 isFloatingTy, isDoubleTy, isFloatTy, isIntTy, isWordTy, isStringTy,
79 isIntegerTy, isBoolTy, isUnitTy, isCharTy, isCallStackTy, isCallStackPred,
80 isTauTy, isTauTyCon, tcIsTyVarTy, tcIsForAllTy,
81 isPredTy, isTyVarClassPred, isTyVarExposed, isTyVarUnderDatatype,
82 checkValidClsArgs, hasTyVarHead,
83 isRigidEqPred, isRigidTy,
84
85 ---------------------------------
86 -- Misc type manipulators
87
88 deNoteType,
89 orphNamesOfType, orphNamesOfCo,
90 orphNamesOfTypes, orphNamesOfCoCon,
91 getDFunTyKey,
92 evVarPred_maybe, evVarPred,
93
94 ---------------------------------
95 -- Predicate types
96 mkMinimalBySCs, transSuperClasses,
97 pickQuantifiablePreds, pickCapturedPreds,
98 immSuperClasses,
99 isImprovementPred,
100
101 -- * Finding type instances
102 tcTyFamInsts,
103
104 -- * Finding "exact" (non-dead) type variables
105 exactTyCoVarsOfType, exactTyCoVarsOfTypes,
106 splitDepVarsOfType, splitDepVarsOfTypes, TcDepVars(..), tcDepVarSet,
107 anyRewritableTyVar,
108
109 -- * Extracting bound variables
110 allBoundVariables, allBoundVariabless,
111
112 ---------------------------------
113 -- Foreign import and export
114 isFFIArgumentTy, -- :: DynFlags -> Safety -> Type -> Bool
115 isFFIImportResultTy, -- :: DynFlags -> Type -> Bool
116 isFFIExportResultTy, -- :: Type -> Bool
117 isFFIExternalTy, -- :: Type -> Bool
118 isFFIDynTy, -- :: Type -> Type -> Bool
119 isFFIPrimArgumentTy, -- :: DynFlags -> Type -> Bool
120 isFFIPrimResultTy, -- :: DynFlags -> Type -> Bool
121 isFFILabelTy, -- :: Type -> Bool
122 isFFITy, -- :: Type -> Bool
123 isFunPtrTy, -- :: Type -> Bool
124 tcSplitIOType_maybe, -- :: Type -> Maybe Type
125
126 --------------------------------
127 -- Rexported from Kind
128 Kind, typeKind,
129 liftedTypeKind,
130 constraintKind,
131 isLiftedTypeKind, isUnliftedTypeKind, classifiesTypeWithValues,
132
133 --------------------------------
134 -- Rexported from Type
135 Type, PredType, ThetaType, TyBinder, ArgFlag(..),
136
137 mkForAllTy, mkForAllTys, mkInvForAllTys, mkSpecForAllTys, mkInvForAllTy,
138 mkFunTy, mkFunTys,
139 mkTyConApp, mkAppTy, mkAppTys,
140 mkTyConTy, mkTyVarTy,
141 mkTyVarTys,
142
143 isClassPred, isEqPred, isNomEqPred, isIPPred,
144 mkClassPred,
145 isDictLikeTy,
146 tcSplitDFunTy, tcSplitDFunHead, tcSplitMethodTy,
147 isRuntimeRepVar, isKindLevPoly,
148 isVisibleBinder, isInvisibleBinder,
149
150 -- Type substitutions
151 TCvSubst(..), -- Representation visible to a few friends
152 TvSubstEnv, emptyTCvSubst,
153 zipTvSubst,
154 mkTvSubstPrs, notElemTCvSubst, unionTCvSubst,
155 getTvSubstEnv, setTvSubstEnv, getTCvInScope, extendTCvInScope,
156 extendTCvInScopeList, extendTCvInScopeSet, extendTvSubstAndInScope,
157 Type.lookupTyVar, Type.extendTCvSubst, Type.substTyVarBndr,
158 Type.extendTvSubst,
159 isInScope, mkTCvSubst, mkTvSubst, zipTyEnv, zipCoEnv,
160 Type.substTy, substTys, substTyWith, substTyWithCoVars,
161 substTyAddInScope,
162 substTyUnchecked, substTysUnchecked, substThetaUnchecked,
163 substTyWithUnchecked,
164 substCoUnchecked, substCoWithUnchecked,
165 substTheta,
166
167 isUnliftedType, -- Source types are always lifted
168 isUnboxedTupleType, -- Ditto
169 isPrimitiveType,
170
171 coreView,
172
173 tyCoVarsOfType, tyCoVarsOfTypes, closeOverKinds,
174 tyCoFVsOfType, tyCoFVsOfTypes,
175 tyCoVarsOfTypeDSet, tyCoVarsOfTypesDSet, closeOverKindsDSet,
176 tyCoVarsOfTypeList, tyCoVarsOfTypesList,
177 noFreeVarsOfType,
178
179 --------------------------------
180 -- Transforming Types to TcTypes
181 toTcType, -- :: Type -> TcType
182 toTcTypeBag, -- :: Bag EvVar -> Bag EvVar
183
184 pprKind, pprParendKind, pprSigmaType,
185 pprType, pprParendType, pprTypeApp, pprTyThingCategory, tyThingCategory,
186 pprTheta, pprThetaArrowTy, pprClassPred,
187 pprTvBndr, pprTvBndrs,
188
189 TypeSize, sizeType, sizeTypes, toposortTyVars
190
191 ) where
192
193 #include "HsVersions.h"
194
195 -- friends:
196 import Kind
197 import TyCoRep
198 import Class
199 import Var
200 import ForeignCall
201 import VarSet
202 import Coercion
203 import Type
204 import RepType
205 import TyCon
206
207 -- others:
208 import DynFlags
209 import CoreFVs
210 import Name -- hiding (varName)
211 -- We use this to make dictionaries for type literals.
212 -- Perhaps there's a better way to do this?
213 import NameSet
214 import VarEnv
215 import PrelNames
216 import TysWiredIn( coercibleClass, unitTyCon, unitTyConKey
217 , listTyCon, constraintKind )
218 import BasicTypes
219 import Util
220 import Bag
221 import Maybes
222 import Outputable
223 import FastString
224 import ErrUtils( Validity(..), MsgDoc, isValid )
225 import FV
226 import qualified GHC.LanguageExtensions as LangExt
227
228 import Data.IORef
229 import Data.Functor.Identity
230
231 {-
232 ************************************************************************
233 * *
234 Types
235 * *
236 ************************************************************************
237
238 The type checker divides the generic Type world into the
239 following more structured beasts:
240
241 sigma ::= forall tyvars. phi
242 -- A sigma type is a qualified type
243 --
244 -- Note that even if 'tyvars' is empty, theta
245 -- may not be: e.g. (?x::Int) => Int
246
247 -- Note that 'sigma' is in prenex form:
248 -- all the foralls are at the front.
249 -- A 'phi' type has no foralls to the right of
250 -- an arrow
251
252 phi :: theta => rho
253
254 rho ::= sigma -> rho
255 | tau
256
257 -- A 'tau' type has no quantification anywhere
258 -- Note that the args of a type constructor must be taus
259 tau ::= tyvar
260 | tycon tau_1 .. tau_n
261 | tau_1 tau_2
262 | tau_1 -> tau_2
263
264 -- In all cases, a (saturated) type synonym application is legal,
265 -- provided it expands to the required form.
266
267 Note [TcTyVars in the typechecker]
268 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
269 The typechecker uses a lot of type variables with special properties,
270 notably being a unification variable with a mutable reference. These
271 use the 'TcTyVar' variant of Var.Var.
272
273 However, the type checker and constraint solver can encounter type
274 variables that use the 'TyVar' variant of Var.Var, for a couple of
275 reasons:
276
277 - When unifying or flattening under (forall a. ty)
278
279 - When typechecking a class decl, say
280 class C (a :: k) where
281 foo :: T a -> Int
282 We have first kind-check the header; fix k and (a:k) to be
283 TyVars, bring 'k' and 'a' into scope, and kind check the
284 signature for 'foo'. In doing so we call solveEqualities to
285 solve any kind equalities in foo's signature. So the solver
286 may see free occurrences of 'k'.
287
288 It's convenient to simply treat these TyVars as skolem constants,
289 which of course they are. So
290
291 * Var.tcTyVarDetails succeeds on a TyVar, returning
292 vanillaSkolemTv, as well as on a TcTyVar.
293
294 * tcIsTcTyVar returns True for both TyVar and TcTyVar variants
295 of Var.Var. The "tc" prefix means "a type variable that can be
296 encountered by the typechecker".
297
298 This is a bit of a change from an earlier era when we remoselessly
299 insisted on real TcTyVars in the type checker. But that seems
300 unnecessary (for skolems, TyVars are fine) and it's now very hard
301 to guarantee, with the advent of kind equalities.
302
303 Note [Coercion variables in free variable lists]
304 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
305 There are several places in the GHC codebase where functions like
306 tyCoVarsOfType, tyCoVarsOfCt, et al. are used to compute the free type
307 variables of a type. The "Co" part of these functions' names shouldn't be
308 dismissed, as it is entirely possible that they will include coercion variables
309 in addition to type variables! As a result, there are some places in TcType
310 where we must take care to check that a variable is a _type_ variable (using
311 isTyVar) before calling tcTyVarDetails--a partial function that is not defined
312 for coercion variables--on the variable. Failing to do so led to
313 GHC Trac #12785.
314 -}
315
316 -- See Note [TcTyVars in the typechecker]
317 type TcTyVar = TyVar -- Used only during type inference
318 type TcCoVar = CoVar -- Used only during type inference
319 type TcType = Type -- A TcType can have mutable type variables
320 type TcTyCoVar = Var -- Either a TcTyVar or a CoVar
321 -- Invariant on ForAllTy in TcTypes:
322 -- forall a. T
323 -- a cannot occur inside a MutTyVar in T; that is,
324 -- T is "flattened" before quantifying over a
325
326 type TcTyVarBinder = TyVarBinder
327 type TcTyCon = TyCon -- these can be the TcTyCon constructor
328
329 -- These types do not have boxy type variables in them
330 type TcPredType = PredType
331 type TcThetaType = ThetaType
332 type TcSigmaType = TcType
333 type TcRhoType = TcType -- Note [TcRhoType]
334 type TcTauType = TcType
335 type TcKind = Kind
336 type TcTyVarSet = TyVarSet
337 type TcTyCoVarSet = TyCoVarSet
338 type TcDTyVarSet = DTyVarSet
339 type TcDTyCoVarSet = DTyCoVarSet
340
341
342 {- *********************************************************************
343 * *
344 ExpType: an "expected type" in the type checker
345 * *
346 ********************************************************************* -}
347
348 -- | An expected type to check against during type-checking.
349 -- See Note [ExpType] in TcMType, where you'll also find manipulators.
350 data ExpType = Check TcType
351 | Infer !InferResult
352
353 data InferResult
354 = IR { ir_uniq :: Unique -- For debugging only
355 , ir_lvl :: TcLevel -- See Note [TcLevel of ExpType] in TcMType
356 , ir_inst :: Bool -- True <=> deeply instantiate before returning
357 -- i.e. return a RhoType
358 -- False <=> do not instantiate before returning
359 -- i.e. return a SigmaType
360 , ir_ref :: IORef (Maybe TcType) }
361 -- The type that fills in this hole should be a Type,
362 -- that is, its kind should be (TYPE rr) for some rr
363
364 type ExpSigmaType = ExpType
365 type ExpRhoType = ExpType
366
367 instance Outputable ExpType where
368 ppr (Check ty) = text "Check" <> braces (ppr ty)
369 ppr (Infer ir) = ppr ir
370
371 instance Outputable InferResult where
372 ppr (IR { ir_uniq = u, ir_lvl = lvl
373 , ir_inst = inst })
374 = text "Infer" <> braces (ppr u <> comma <> ppr lvl <+> ppr inst)
375
376 -- | Make an 'ExpType' suitable for checking.
377 mkCheckExpType :: TcType -> ExpType
378 mkCheckExpType = Check
379
380
381 {- *********************************************************************
382 * *
383 SyntaxOpType
384 * *
385 ********************************************************************* -}
386
387 -- | What to expect for an argument to a rebindable-syntax operator.
388 -- Quite like 'Type', but allows for holes to be filled in by tcSyntaxOp.
389 -- The callback called from tcSyntaxOp gets a list of types; the meaning
390 -- of these types is determined by a left-to-right depth-first traversal
391 -- of the 'SyntaxOpType' tree. So if you pass in
392 --
393 -- > SynAny `SynFun` (SynList `SynFun` SynType Int) `SynFun` SynAny
394 --
395 -- you'll get three types back: one for the first 'SynAny', the /element/
396 -- type of the list, and one for the last 'SynAny'. You don't get anything
397 -- for the 'SynType', because you've said positively that it should be an
398 -- Int, and so it shall be.
399 --
400 -- This is defined here to avoid defining it in TcExpr.hs-boot.
401 data SyntaxOpType
402 = SynAny -- ^ Any type
403 | SynRho -- ^ A rho type, deeply skolemised or instantiated as appropriate
404 | SynList -- ^ A list type. You get back the element type of the list
405 | SynFun SyntaxOpType SyntaxOpType
406 -- ^ A function.
407 | SynType ExpType -- ^ A known type.
408 infixr 0 `SynFun`
409
410 -- | Like 'SynType' but accepts a regular TcType
411 synKnownType :: TcType -> SyntaxOpType
412 synKnownType = SynType . mkCheckExpType
413
414 -- | Like 'mkFunTys' but for 'SyntaxOpType'
415 mkSynFunTys :: [SyntaxOpType] -> ExpType -> SyntaxOpType
416 mkSynFunTys arg_tys res_ty = foldr SynFun (SynType res_ty) arg_tys
417
418
419 {-
420 Note [TcRhoType]
421 ~~~~~~~~~~~~~~~~
422 A TcRhoType has no foralls or contexts at the top, or to the right of an arrow
423 YES (forall a. a->a) -> Int
424 NO forall a. a -> Int
425 NO Eq a => a -> a
426 NO Int -> forall a. a -> Int
427
428
429 ************************************************************************
430 * *
431 TyVarDetails, MetaDetails, MetaInfo
432 * *
433 ************************************************************************
434
435 TyVarDetails gives extra info about type variables, used during type
436 checking. It's attached to mutable type variables only.
437 It's knot-tied back to Var.hs. There is no reason in principle
438 why Var.hs shouldn't actually have the definition, but it "belongs" here.
439
440 Note [Signature skolems]
441 ~~~~~~~~~~~~~~~~~~~~~~~~
442 Consider this
443
444 f :: forall a. [a] -> Int
445 f (x::b : xs) = 3
446
447 Here 'b' is a lexically scoped type variable, but it turns out to be
448 the same as the skolem 'a'. So we have a special kind of skolem
449 constant, SigTv, which can unify with other SigTvs. They are used
450 *only* for pattern type signatures.
451
452 Similarly consider
453 data T (a:k1) = MkT (S a)
454 data S (b:k2) = MkS (T b)
455 When doing kind inference on {S,T} we don't want *skolems* for k1,k2,
456 because they end up unifying; we want those SigTvs again.
457
458 Note [TyVars and TcTyVars during type checking]
459 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
460 The Var type has constructors TyVar and TcTyVar. They are used
461 as follows:
462
463 * TcTyVar: used /only/ during type checking. Should never appear
464 afterwards. May contain a mutable field, in the MetaTv case.
465
466 * TyVar: is never seen by the constraint solver, except locally
467 inside a type like (forall a. [a] ->[a]), where 'a' is a TyVar.
468 We instantiate these with TcTyVars before exposing the type
469 to the constraint solver.
470
471 I have swithered about the latter invariant, excluding TyVars from the
472 constraint solver. It's not strictly essential, and indeed
473 (historically but still there) Var.tcTyVarDetails returns
474 vanillaSkolemTv for a TyVar.
475
476 But ultimately I want to seeparate Type from TcType, and in that case
477 we would need to enforce the separation.
478 -}
479
480 -- A TyVarDetails is inside a TyVar
481 -- See Note [TyVars and TcTyVars]
482 data TcTyVarDetails
483 = SkolemTv -- A skolem
484 TcLevel -- Level of the implication that binds it
485 Bool -- True <=> this skolem type variable can be overlapped
486 -- when looking up instances
487 -- See Note [Binding when looking up instances] in InstEnv
488
489 | FlatSkol -- A flatten-skolem. It stands for the TcType, and zonking
490 TcType -- will replace it by that type.
491 -- See Note [The flattening story] in TcFlatten
492
493 | RuntimeUnk -- Stands for an as-yet-unknown type in the GHCi
494 -- interactive context
495
496 | MetaTv { mtv_info :: MetaInfo
497 , mtv_ref :: IORef MetaDetails
498 , mtv_tclvl :: TcLevel } -- See Note [TcLevel and untouchable type variables]
499
500 vanillaSkolemTv, superSkolemTv :: TcTyVarDetails
501 -- See Note [Binding when looking up instances] in InstEnv
502 vanillaSkolemTv = SkolemTv (pushTcLevel topTcLevel) False -- Might be instantiated
503 superSkolemTv = SkolemTv (pushTcLevel topTcLevel) True -- Treat this as a completely distinct type
504
505 -----------------------------
506 data MetaDetails
507 = Flexi -- Flexi type variables unify to become Indirects
508 | Indirect TcType
509
510 data MetaInfo
511 = TauTv -- This MetaTv is an ordinary unification variable
512 -- A TauTv is always filled in with a tau-type, which
513 -- never contains any ForAlls.
514
515 | SigTv -- A variant of TauTv, except that it should not be
516 -- unified with a type, only with a type variable
517 -- SigTvs are only distinguished to improve error messages
518 -- see Note [Signature skolems]
519 -- The MetaDetails, if filled in, will
520 -- always be another SigTv or a SkolemTv
521
522 | FlatMetaTv -- A flatten meta-tyvar
523 -- It is a meta-tyvar, but it is always untouchable, with level 0
524 -- See Note [The flattening story] in TcFlatten
525
526 instance Outputable MetaDetails where
527 ppr Flexi = text "Flexi"
528 ppr (Indirect ty) = text "Indirect" <+> ppr ty
529
530 pprTcTyVarDetails :: TcTyVarDetails -> SDoc
531 -- For debugging
532 pprTcTyVarDetails (RuntimeUnk {}) = text "rt"
533 pprTcTyVarDetails (FlatSkol {}) = text "fsk"
534 pprTcTyVarDetails (SkolemTv lvl True) = text "ssk" <> colon <> ppr lvl
535 pprTcTyVarDetails (SkolemTv lvl False) = text "sk" <> colon <> ppr lvl
536 pprTcTyVarDetails (MetaTv { mtv_info = info, mtv_tclvl = tclvl })
537 = pp_info <> colon <> ppr tclvl
538 where
539 pp_info = case info of
540 TauTv -> text "tau"
541 SigTv -> text "sig"
542 FlatMetaTv -> text "fuv"
543
544
545 {- *********************************************************************
546 * *
547 UserTypeCtxt
548 * *
549 ********************************************************************* -}
550
551 -------------------------------------
552 -- UserTypeCtxt describes the origin of the polymorphic type
553 -- in the places where we need to an expression has that type
554
555 data UserTypeCtxt
556 = FunSigCtxt -- Function type signature, when checking the type
557 -- Also used for types in SPECIALISE pragmas
558 Name -- Name of the function
559 Bool -- True <=> report redundant constraints
560 -- This is usually True, but False for
561 -- * Record selectors (not important here)
562 -- * Class and instance methods. Here
563 -- the code may legitimately be more
564 -- polymorphic than the signature
565 -- generated from the class
566 -- declaration
567
568 | InfSigCtxt Name -- Inferred type for function
569 | ExprSigCtxt -- Expression type signature
570 | TypeAppCtxt -- Visible type application
571 | ConArgCtxt Name -- Data constructor argument
572 | TySynCtxt Name -- RHS of a type synonym decl
573 | PatSynCtxt Name -- Type sig for a pattern synonym
574 | PatSigCtxt -- Type sig in pattern
575 -- eg f (x::t) = ...
576 -- or (x::t, y) = e
577 | RuleSigCtxt Name -- LHS of a RULE forall
578 -- RULE "foo" forall (x :: a -> a). f (Just x) = ...
579 | ResSigCtxt -- Result type sig
580 -- f x :: t = ....
581 | ForSigCtxt Name -- Foreign import or export signature
582 | DefaultDeclCtxt -- Types in a default declaration
583 | InstDeclCtxt -- An instance declaration
584 | SpecInstCtxt -- SPECIALISE instance pragma
585 | ThBrackCtxt -- Template Haskell type brackets [t| ... |]
586 | GenSigCtxt -- Higher-rank or impredicative situations
587 -- e.g. (f e) where f has a higher-rank type
588 -- We might want to elaborate this
589 | GhciCtxt -- GHCi command :kind <type>
590
591 | ClassSCCtxt Name -- Superclasses of a class
592 | SigmaCtxt -- Theta part of a normal for-all type
593 -- f :: <S> => a -> a
594 | DataTyCtxt Name -- The "stupid theta" part of a data decl
595 -- data <S> => T a = MkT a
596
597 {-
598 -- Notes re TySynCtxt
599 -- We allow type synonyms that aren't types; e.g. type List = []
600 --
601 -- If the RHS mentions tyvars that aren't in scope, we'll
602 -- quantify over them:
603 -- e.g. type T = a->a
604 -- will become type T = forall a. a->a
605 --
606 -- With gla-exts that's right, but for H98 we should complain.
607 -}
608
609
610 pprUserTypeCtxt :: UserTypeCtxt -> SDoc
611 pprUserTypeCtxt (FunSigCtxt n _) = text "the type signature for" <+> quotes (ppr n)
612 pprUserTypeCtxt (InfSigCtxt n) = text "the inferred type for" <+> quotes (ppr n)
613 pprUserTypeCtxt (RuleSigCtxt n) = text "a RULE for" <+> quotes (ppr n)
614 pprUserTypeCtxt ExprSigCtxt = text "an expression type signature"
615 pprUserTypeCtxt TypeAppCtxt = text "a type argument"
616 pprUserTypeCtxt (ConArgCtxt c) = text "the type of the constructor" <+> quotes (ppr c)
617 pprUserTypeCtxt (TySynCtxt c) = text "the RHS of the type synonym" <+> quotes (ppr c)
618 pprUserTypeCtxt ThBrackCtxt = text "a Template Haskell quotation [t|...|]"
619 pprUserTypeCtxt PatSigCtxt = text "a pattern type signature"
620 pprUserTypeCtxt ResSigCtxt = text "a result type signature"
621 pprUserTypeCtxt (ForSigCtxt n) = text "the foreign declaration for" <+> quotes (ppr n)
622 pprUserTypeCtxt DefaultDeclCtxt = text "a type in a `default' declaration"
623 pprUserTypeCtxt InstDeclCtxt = text "an instance declaration"
624 pprUserTypeCtxt SpecInstCtxt = text "a SPECIALISE instance pragma"
625 pprUserTypeCtxt GenSigCtxt = text "a type expected by the context"
626 pprUserTypeCtxt GhciCtxt = text "a type in a GHCi command"
627 pprUserTypeCtxt (ClassSCCtxt c) = text "the super-classes of class" <+> quotes (ppr c)
628 pprUserTypeCtxt SigmaCtxt = text "the context of a polymorphic type"
629 pprUserTypeCtxt (DataTyCtxt tc) = text "the context of the data type declaration for" <+> quotes (ppr tc)
630 pprUserTypeCtxt (PatSynCtxt n) = text "the signature for pattern synonym" <+> quotes (ppr n)
631
632 isSigMaybe :: UserTypeCtxt -> Maybe Name
633 isSigMaybe (FunSigCtxt n _) = Just n
634 isSigMaybe (ConArgCtxt n) = Just n
635 isSigMaybe (ForSigCtxt n) = Just n
636 isSigMaybe (PatSynCtxt n) = Just n
637 isSigMaybe _ = Nothing
638
639
640 {- *********************************************************************
641 * *
642 Untoucable type variables
643 * *
644 ********************************************************************* -}
645
646 newtype TcLevel = TcLevel Int deriving( Eq, Ord )
647 -- See Note [TcLevel and untouchable type variables] for what this Int is
648 -- See also Note [TcLevel assignment]
649
650 {-
651 Note [TcLevel and untouchable type variables]
652 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
653 * Each unification variable (MetaTv)
654 and each Implication
655 has a level number (of type TcLevel)
656
657 * INVARIANTS. In a tree of Implications,
658
659 (ImplicInv) The level number of an Implication is
660 STRICTLY GREATER THAN that of its parent
661
662 (MetaTvInv) The level number of a unification variable is
663 LESS THAN OR EQUAL TO that of its parent
664 implication
665
666 * A unification variable is *touchable* if its level number
667 is EQUAL TO that of its immediate parent implication.
668
669 * INVARIANT
670 (GivenInv) The free variables of the ic_given of an
671 implication are all untouchable; ie their level
672 numbers are LESS THAN the ic_tclvl of the implication
673
674 Note [Skolem escape prevention]
675 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
676 We only unify touchable unification variables. Because of
677 (MetaTvInv), there can be no occurrences of the variable further out,
678 so the unification can't cause the skolems to escape. Example:
679 data T = forall a. MkT a (a->Int)
680 f x (MkT v f) = length [v,x]
681 We decide (x::alpha), and generate an implication like
682 [1]forall a. (a ~ alpha[0])
683 But we must not unify alpha:=a, because the skolem would escape.
684
685 For the cases where we DO want to unify, we rely on floating the
686 equality. Example (with same T)
687 g x (MkT v f) = x && True
688 We decide (x::alpha), and generate an implication like
689 [1]forall a. (Bool ~ alpha[0])
690 We do NOT unify directly, bur rather float out (if the constraint
691 does not mention 'a') to get
692 (Bool ~ alpha[0]) /\ [1]forall a.()
693 and NOW we can unify alpha.
694
695 The same idea of only unifying touchables solves another problem.
696 Suppose we had
697 (F Int ~ uf[0]) /\ [1](forall a. C a => F Int ~ beta[1])
698 In this example, beta is touchable inside the implication. The
699 first solveSimpleWanteds step leaves 'uf' un-unified. Then we move inside
700 the implication where a new constraint
701 uf ~ beta
702 emerges. If we (wrongly) spontaneously solved it to get uf := beta,
703 the whole implication disappears but when we pop out again we are left with
704 (F Int ~ uf) which will be unified by our final zonking stage and
705 uf will get unified *once more* to (F Int).
706
707 Note [TcLevel assignment]
708 ~~~~~~~~~~~~~~~~~~~~~~~~~
709 We arrange the TcLevels like this
710
711 0 Level for flatten meta-vars
712 1 Top level
713 2 First-level implication constraints
714 3 Second-level implication constraints
715 ...etc...
716
717 The flatten meta-vars are all at level 0, just to make them untouchable.
718 -}
719
720 maxTcLevel :: TcLevel -> TcLevel -> TcLevel
721 maxTcLevel (TcLevel a) (TcLevel b) = TcLevel (a `max` b)
722
723 fmvTcLevel :: TcLevel -> TcLevel
724 -- See Note [TcLevel assignment]
725 fmvTcLevel _ = TcLevel 0
726
727 topTcLevel :: TcLevel
728 -- See Note [TcLevel assignment]
729 topTcLevel = TcLevel 1 -- 1 = outermost level
730
731 isTopTcLevel :: TcLevel -> Bool
732 isTopTcLevel (TcLevel 1) = True
733 isTopTcLevel _ = False
734
735 pushTcLevel :: TcLevel -> TcLevel
736 -- See Note [TcLevel assignment]
737 pushTcLevel (TcLevel us) = TcLevel (us + 1)
738
739 strictlyDeeperThan :: TcLevel -> TcLevel -> Bool
740 strictlyDeeperThan (TcLevel tv_tclvl) (TcLevel ctxt_tclvl)
741 = tv_tclvl > ctxt_tclvl
742
743 sameDepthAs :: TcLevel -> TcLevel -> Bool
744 sameDepthAs (TcLevel ctxt_tclvl) (TcLevel tv_tclvl)
745 = ctxt_tclvl == tv_tclvl -- NB: invariant ctxt_tclvl >= tv_tclvl
746 -- So <= would be equivalent
747
748 checkTcLevelInvariant :: TcLevel -> TcLevel -> Bool
749 -- Checks (MetaTvInv) from Note [TcLevel and untouchable type variables]
750 checkTcLevelInvariant (TcLevel ctxt_tclvl) (TcLevel tv_tclvl)
751 = ctxt_tclvl >= tv_tclvl
752
753 tcTyVarLevel :: TcTyVar -> TcLevel
754 tcTyVarLevel tv
755 = ASSERT2( tcIsTcTyVar tv, ppr tv )
756 case tcTyVarDetails tv of
757 MetaTv { mtv_tclvl = tv_lvl } -> tv_lvl
758 SkolemTv tv_lvl _ -> tv_lvl
759 FlatSkol ty -> tcTypeLevel ty
760 RuntimeUnk -> topTcLevel
761
762 tcTypeLevel :: TcType -> TcLevel
763 -- Max level of any free var of the type
764 tcTypeLevel ty
765 = foldDVarSet add topTcLevel (tyCoVarsOfTypeDSet ty)
766 where
767 add v lvl
768 | isTcTyVar v = lvl `maxTcLevel` tcTyVarLevel v
769 | otherwise = lvl
770
771 instance Outputable TcLevel where
772 ppr (TcLevel us) = ppr us
773
774 {- *********************************************************************
775 * *
776 Finding type family instances
777 * *
778 ************************************************************************
779 -}
780
781 -- | Finds outermost type-family applications occuring in a type,
782 -- after expanding synonyms. In the list (F, tys) that is returned
783 -- we guarantee that tys matches F's arity. For example, given
784 -- type family F a :: * -> * (arity 1)
785 -- calling tcTyFamInsts on (Maybe (F Int Bool) will return
786 -- (F, [Int]), not (F, [Int,Bool])
787 --
788 -- This is important for its use in deciding termination of type
789 -- instances (see Trac #11581). E.g.
790 -- type instance G [Int] = ...(F Int <big type>)...
791 -- we don't need to take <big type> into account when asking if
792 -- the calls on the RHS are smaller than the LHS
793 tcTyFamInsts :: Type -> [(TyCon, [Type])]
794 tcTyFamInsts ty
795 | Just exp_ty <- coreView ty = tcTyFamInsts exp_ty
796 tcTyFamInsts (TyVarTy _) = []
797 tcTyFamInsts (TyConApp tc tys)
798 | isTypeFamilyTyCon tc = [(tc, take (tyConArity tc) tys)]
799 | otherwise = concat (map tcTyFamInsts tys)
800 tcTyFamInsts (LitTy {}) = []
801 tcTyFamInsts (ForAllTy bndr ty) = tcTyFamInsts (binderKind bndr)
802 ++ tcTyFamInsts ty
803 tcTyFamInsts (FunTy ty1 ty2) = tcTyFamInsts ty1 ++ tcTyFamInsts ty2
804 tcTyFamInsts (AppTy ty1 ty2) = tcTyFamInsts ty1 ++ tcTyFamInsts ty2
805 tcTyFamInsts (CastTy ty _) = tcTyFamInsts ty
806 tcTyFamInsts (CoercionTy _) = [] -- don't count tyfams in coercions,
807 -- as they never get normalized, anyway
808
809 {-
810 ************************************************************************
811 * *
812 The "exact" free variables of a type
813 * *
814 ************************************************************************
815
816 Note [Silly type synonym]
817 ~~~~~~~~~~~~~~~~~~~~~~~~~
818 Consider
819 type T a = Int
820 What are the free tyvars of (T x)? Empty, of course!
821 Here's the example that Ralf Laemmel showed me:
822 foo :: (forall a. C u a -> C u a) -> u
823 mappend :: Monoid u => u -> u -> u
824
825 bar :: Monoid u => u
826 bar = foo (\t -> t `mappend` t)
827 We have to generalise at the arg to f, and we don't
828 want to capture the constraint (Monad (C u a)) because
829 it appears to mention a. Pretty silly, but it was useful to him.
830
831 exactTyCoVarsOfType is used by the type checker to figure out exactly
832 which type variables are mentioned in a type. It's also used in the
833 smart-app checking code --- see TcExpr.tcIdApp
834
835 On the other hand, consider a *top-level* definition
836 f = (\x -> x) :: T a -> T a
837 If we don't abstract over 'a' it'll get fixed to GHC.Prim.Any, and then
838 if we have an application like (f "x") we get a confusing error message
839 involving Any. So the conclusion is this: when generalising
840 - at top level use tyCoVarsOfType
841 - in nested bindings use exactTyCoVarsOfType
842 See Trac #1813 for example.
843 -}
844
845 exactTyCoVarsOfType :: Type -> TyCoVarSet
846 -- Find the free type variables (of any kind)
847 -- but *expand* type synonyms. See Note [Silly type synonym] above.
848 exactTyCoVarsOfType ty
849 = go ty
850 where
851 go ty | Just ty' <- coreView ty = go ty' -- This is the key line
852 go (TyVarTy tv) = unitVarSet tv `unionVarSet` go (tyVarKind tv)
853 go (TyConApp _ tys) = exactTyCoVarsOfTypes tys
854 go (LitTy {}) = emptyVarSet
855 go (AppTy fun arg) = go fun `unionVarSet` go arg
856 go (FunTy arg res) = go arg `unionVarSet` go res
857 go (ForAllTy bndr ty) = delBinderVar (go ty) bndr `unionVarSet` go (binderKind bndr)
858 go (CastTy ty co) = go ty `unionVarSet` goCo co
859 go (CoercionTy co) = goCo co
860
861 goCo (Refl _ ty) = go ty
862 goCo (TyConAppCo _ _ args)= goCos args
863 goCo (AppCo co arg) = goCo co `unionVarSet` goCo arg
864 goCo (ForAllCo tv k_co co)
865 = goCo co `delVarSet` tv `unionVarSet` goCo k_co
866 goCo (FunCo _ co1 co2) = goCo co1 `unionVarSet` goCo co2
867 goCo (CoVarCo v) = unitVarSet v `unionVarSet` go (varType v)
868 goCo (AxiomInstCo _ _ args) = goCos args
869 goCo (UnivCo p _ t1 t2) = goProv p `unionVarSet` go t1 `unionVarSet` go t2
870 goCo (SymCo co) = goCo co
871 goCo (TransCo co1 co2) = goCo co1 `unionVarSet` goCo co2
872 goCo (NthCo _ co) = goCo co
873 goCo (LRCo _ co) = goCo co
874 goCo (InstCo co arg) = goCo co `unionVarSet` goCo arg
875 goCo (CoherenceCo c1 c2) = goCo c1 `unionVarSet` goCo c2
876 goCo (KindCo co) = goCo co
877 goCo (SubCo co) = goCo co
878 goCo (AxiomRuleCo _ c) = goCos c
879
880 goCos cos = foldr (unionVarSet . goCo) emptyVarSet cos
881
882 goProv UnsafeCoerceProv = emptyVarSet
883 goProv (PhantomProv kco) = goCo kco
884 goProv (ProofIrrelProv kco) = goCo kco
885 goProv (PluginProv _) = emptyVarSet
886 goProv (HoleProv _) = emptyVarSet
887
888 exactTyCoVarsOfTypes :: [Type] -> TyVarSet
889 exactTyCoVarsOfTypes tys = mapUnionVarSet exactTyCoVarsOfType tys
890
891 anyRewritableTyVar :: Bool -> (TcTyVar -> Bool)
892 -> TcType -> Bool
893 -- (anyRewritableTyVar ignore_cos pred ty) returns True
894 -- if the 'pred' returns True of free TyVar in 'ty'
895 -- Do not look inside casts and coercions if 'ignore_cos' is True
896 -- See Note [anyRewritableTyVar]
897 anyRewritableTyVar ignore_cos pred ty
898 = go emptyVarSet ty
899 where
900 go_tv bound tv | tv `elemVarSet` bound = False
901 | otherwise = pred tv
902
903 go bound (TyVarTy tv) = go_tv bound tv
904 go _ (LitTy {}) = False
905 go bound (TyConApp _ tys) = any (go bound) tys
906 go bound (AppTy fun arg) = go bound fun || go bound arg
907 go bound (FunTy arg res) = go bound arg || go bound res
908 go bound (ForAllTy tv ty) = go (bound `extendVarSet` binderVar tv) ty
909 go bound (CastTy ty co) = go bound ty || go_co bound co
910 go bound (CoercionTy co) = go_co bound co
911
912 go_co bound co
913 | ignore_cos = False
914 | otherwise = anyVarSet (go_tv bound) (tyCoVarsOfCo co)
915 -- We don't have an equivalent of anyRewritableTyVar for coercions
916 -- (at least not yet) so take the free vars and test them
917
918 {- Note [anyRewritableTyVar]
919 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
920 anyRewritableTyVar is used during kick-out from the inert set,
921 to decide if, given a new equality (a ~ ty), we should kick out
922 a constraint C. Rather than gather free variables and see if 'a'
923 is among them, we instead pass in a predicate; this is just efficiency.
924 -}
925
926 {- *********************************************************************
927 * *
928 Bound variables in a type
929 * *
930 ********************************************************************* -}
931
932 -- | Find all variables bound anywhere in a type.
933 -- See also Note [Scope-check inferred kinds] in TcHsType
934 allBoundVariables :: Type -> TyVarSet
935 allBoundVariables ty = fvVarSet $ go ty
936 where
937 go :: Type -> FV
938 go (TyVarTy tv) = go (tyVarKind tv)
939 go (TyConApp _ tys) = mapUnionFV go tys
940 go (AppTy t1 t2) = go t1 `unionFV` go t2
941 go (FunTy t1 t2) = go t1 `unionFV` go t2
942 go (ForAllTy (TvBndr tv _) t2) = FV.unitFV tv `unionFV`
943 go (tyVarKind tv) `unionFV` go t2
944 go (LitTy {}) = emptyFV
945 go (CastTy ty _) = go ty
946 go (CoercionTy {}) = emptyFV
947 -- any types mentioned in a coercion should also be mentioned in
948 -- a type.
949
950 allBoundVariabless :: [Type] -> TyVarSet
951 allBoundVariabless = mapUnionVarSet allBoundVariables
952
953 {- *********************************************************************
954 * *
955 Type and kind variables in a type
956 * *
957 ********************************************************************* -}
958
959 data TcDepVars -- See Note [Dependent type variables]
960 -- See Note [TcDepVars determinism]
961 = DV { dv_kvs :: DTyCoVarSet -- "kind" variables (dependent)
962 , dv_tvs :: DTyVarSet -- "type" variables (non-dependent)
963 -- A variable may appear in both sets
964 -- E.g. T k (x::k) The first occurrence of k makes it
965 -- show up in dv_tvs, the second in dv_kvs
966 -- See Note [Dependent type variables]
967 }
968
969 tcDepVarSet :: TcDepVars -> TyVarSet
970 -- Actually can contain CoVars, but never mind
971 tcDepVarSet (DV { dv_kvs = kvs, dv_tvs = tvs })
972 = dVarSetToVarSet kvs `unionVarSet` dVarSetToVarSet tvs
973
974 instance Monoid TcDepVars where
975 mempty = DV { dv_kvs = emptyDVarSet, dv_tvs = emptyDVarSet }
976 mappend (DV { dv_kvs = kv1, dv_tvs = tv1 })
977 (DV { dv_kvs = kv2, dv_tvs = tv2 })
978 = DV { dv_kvs = kv1 `unionDVarSet` kv2
979 , dv_tvs = tv1 `unionDVarSet` tv2}
980
981 instance Outputable TcDepVars where
982 ppr (DV {dv_kvs = kvs, dv_tvs = tvs })
983 = text "DV" <+> braces (sep [ text "dv_kvs =" <+> ppr kvs
984 , text "dv_tvs =" <+> ppr tvs ])
985
986 {- Note [Dependent type variables]
987 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
988 In Haskell type inference we quantify over type variables; but we only
989 quantify over /kind/ variables when -XPolyKinds is on. So when
990 collecting the free vars of a type, prior to quantifying, we must keep
991 the type and kind variables separate. But what does that mean in a
992 system where kind variables /are/ type variables? It's a fairly
993 arbitrary distinction based on how the variables appear:
994
995 - "Kind variables" appear in the kind of some other free variable
996 PLUS any free coercion variables
997
998 - "Type variables" are all free vars that are not kind variables
999
1000 E.g. In the type T k (a::k)
1001 'k' is a kind variable, because it occurs in the kind of 'a',
1002 even though it also appears at "top level" of the type
1003 'a' is a type variable, because it doesn't
1004
1005 We gather these variables using a TcDepVars record:
1006 DV { dv_kvs: Variables free in the kind of a free type variable
1007 or of a forall-bound type variable
1008 , dv_tvs: Variables sytactically free in the type }
1009
1010 So: dv_kvs are the kind variables of the type
1011 (dv_tvs - dv_kvs) are the type variable of the type
1012
1013 Note that
1014
1015 * A variable can occur in both.
1016 T k (x::k) The first occurrence of k makes it
1017 show up in dv_tvs, the second in dv_kvs
1018
1019 * We include any coercion variables in the "dependent",
1020 "kind-variable" set because we never quantify over them.
1021
1022 * Both sets are un-ordered, of course.
1023
1024 * The "kind variables" might depend on each other; e.g
1025 (k1 :: k2), (k2 :: *)
1026 The "type variables" do not depend on each other; if
1027 one did, it'd be classified as a kind variable!
1028
1029 Note [TcDepVars determinism]
1030 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1031 When we quantify over type variables we decide the order in which they
1032 appear in the final type. Because the order of type variables in the type
1033 can end up in the interface file and affects some optimizations like
1034 worker-wrapper we want this order to be deterministic.
1035
1036 To achieve that we use deterministic sets of variables that can be converted to
1037 lists in a deterministic order.
1038
1039 For more information about deterministic sets see
1040 Note [Deterministic UniqFM] in UniqDFM.
1041 -}
1042
1043 -- | Like 'splitDepVarsOfType', but over a list of types
1044 splitDepVarsOfTypes :: [Type] -> TcDepVars
1045 splitDepVarsOfTypes = foldMap splitDepVarsOfType
1046
1047 -- | Worker for 'splitDepVarsOfType'. This might output the same var
1048 -- in both sets, if it's used in both a type and a kind.
1049 -- See Note [TcDepVars determinism]
1050 -- See Note [Dependent type variables]
1051 splitDepVarsOfType :: Type -> TcDepVars
1052 splitDepVarsOfType = go
1053 where
1054 go (TyVarTy tv) = DV { dv_kvs =tyCoVarsOfTypeDSet $ tyVarKind tv
1055 , dv_tvs = unitDVarSet tv }
1056 go (AppTy t1 t2) = go t1 `mappend` go t2
1057 go (TyConApp _ tys) = foldMap go tys
1058 go (FunTy arg res) = go arg `mappend` go res
1059 go (LitTy {}) = mempty
1060 go (CastTy ty co) = go ty `mappend` go_co co
1061 go (CoercionTy co) = go_co co
1062 go (ForAllTy (TvBndr tv _) ty)
1063 = let DV { dv_kvs = kvs, dv_tvs = tvs } = go ty in
1064 DV { dv_kvs = (kvs `delDVarSet` tv)
1065 `extendDVarSetList` tyCoVarsOfTypeList (tyVarKind tv)
1066 , dv_tvs = tvs `delDVarSet` tv }
1067
1068 go_co co = DV { dv_kvs = tyCoVarsOfCoDSet co
1069 , dv_tvs = emptyDVarSet }
1070
1071 {-
1072 ************************************************************************
1073 * *
1074 Predicates
1075 * *
1076 ************************************************************************
1077 -}
1078
1079 tcIsTcTyVar :: TcTyVar -> Bool
1080 -- See Note [TcTyVars in the typechecker]
1081 tcIsTcTyVar tv = isTyVar tv
1082
1083 isTouchableOrFmv :: TcLevel -> TcTyVar -> Bool
1084 isTouchableOrFmv ctxt_tclvl tv
1085 = ASSERT2( tcIsTcTyVar tv, ppr tv )
1086 case tcTyVarDetails tv of
1087 MetaTv { mtv_tclvl = tv_tclvl, mtv_info = info }
1088 -> ASSERT2( checkTcLevelInvariant ctxt_tclvl tv_tclvl,
1089 ppr tv $$ ppr tv_tclvl $$ ppr ctxt_tclvl )
1090 case info of
1091 FlatMetaTv -> True
1092 _ -> tv_tclvl `sameDepthAs` ctxt_tclvl
1093 _ -> False
1094
1095 isTouchableMetaTyVar :: TcLevel -> TcTyVar -> Bool
1096 isTouchableMetaTyVar ctxt_tclvl tv
1097 | isTyVar tv -- See Note [Coercion variables in free variable lists]
1098 = ASSERT2( tcIsTcTyVar tv, ppr tv )
1099 case tcTyVarDetails tv of
1100 MetaTv { mtv_tclvl = tv_tclvl }
1101 -> ASSERT2( checkTcLevelInvariant ctxt_tclvl tv_tclvl,
1102 ppr tv $$ ppr tv_tclvl $$ ppr ctxt_tclvl )
1103 tv_tclvl `sameDepthAs` ctxt_tclvl
1104 _ -> False
1105 | otherwise = False
1106
1107 isFloatedTouchableMetaTyVar :: TcLevel -> TcTyVar -> Bool
1108 isFloatedTouchableMetaTyVar ctxt_tclvl tv
1109 | isTyVar tv -- See Note [Coercion variables in free variable lists]
1110 = ASSERT2( tcIsTcTyVar tv, ppr tv )
1111 case tcTyVarDetails tv of
1112 MetaTv { mtv_tclvl = tv_tclvl } -> tv_tclvl `strictlyDeeperThan` ctxt_tclvl
1113 _ -> False
1114 | otherwise = False
1115
1116 isImmutableTyVar :: TyVar -> Bool
1117 isImmutableTyVar tv = isSkolemTyVar tv
1118
1119 isTyConableTyVar, isSkolemTyVar, isOverlappableTyVar,
1120 isMetaTyVar, isAmbiguousTyVar,
1121 isFmvTyVar, isFskTyVar, isFlattenTyVar :: TcTyVar -> Bool
1122
1123 isTyConableTyVar tv
1124 -- True of a meta-type variable that can be filled in
1125 -- with a type constructor application; in particular,
1126 -- not a SigTv
1127 | isTyVar tv -- See Note [Coercion variables in free variable lists]
1128 = ASSERT2( tcIsTcTyVar tv, ppr tv )
1129 case tcTyVarDetails tv of
1130 MetaTv { mtv_info = SigTv } -> False
1131 _ -> True
1132 | otherwise = True
1133
1134 isFmvTyVar tv
1135 = ASSERT2( tcIsTcTyVar tv, ppr tv )
1136 case tcTyVarDetails tv of
1137 MetaTv { mtv_info = FlatMetaTv } -> True
1138 _ -> False
1139
1140 -- | True of both given and wanted flatten-skolems (fak and usk)
1141 isFlattenTyVar tv
1142 = ASSERT2( tcIsTcTyVar tv, ppr tv )
1143 case tcTyVarDetails tv of
1144 FlatSkol {} -> True
1145 MetaTv { mtv_info = FlatMetaTv } -> True
1146 _ -> False
1147
1148 -- | True of FlatSkol skolems only
1149 isFskTyVar tv
1150 = ASSERT2( tcIsTcTyVar tv, ppr tv )
1151 case tcTyVarDetails tv of
1152 FlatSkol {} -> True
1153 _ -> False
1154
1155 isSkolemTyVar tv
1156 = ASSERT2( tcIsTcTyVar tv, ppr tv )
1157 case tcTyVarDetails tv of
1158 MetaTv {} -> False
1159 _other -> True
1160
1161 isOverlappableTyVar tv
1162 | isTyVar tv -- See Note [Coercion variables in free variable lists]
1163 = ASSERT2( tcIsTcTyVar tv, ppr tv )
1164 case tcTyVarDetails tv of
1165 SkolemTv _ overlappable -> overlappable
1166 _ -> False
1167 | otherwise = False
1168
1169 isMetaTyVar tv
1170 | isTyVar tv -- See Note [Coercion variables in free variable lists]
1171 = ASSERT2( tcIsTcTyVar tv, ppr tv )
1172 case tcTyVarDetails tv of
1173 MetaTv {} -> True
1174 _ -> False
1175 | otherwise = False
1176
1177 -- isAmbiguousTyVar is used only when reporting type errors
1178 -- It picks out variables that are unbound, namely meta
1179 -- type variables and the RuntimUnk variables created by
1180 -- RtClosureInspect.zonkRTTIType. These are "ambiguous" in
1181 -- the sense that they stand for an as-yet-unknown type
1182 isAmbiguousTyVar tv
1183 | isTyVar tv -- See Note [Coercion variables in free variable lists]
1184 = case tcTyVarDetails tv of
1185 MetaTv {} -> True
1186 RuntimeUnk {} -> True
1187 _ -> False
1188 | otherwise = False
1189
1190 isMetaTyVarTy :: TcType -> Bool
1191 isMetaTyVarTy (TyVarTy tv) = isMetaTyVar tv
1192 isMetaTyVarTy _ = False
1193
1194 metaTyVarInfo :: TcTyVar -> MetaInfo
1195 metaTyVarInfo tv
1196 = case tcTyVarDetails tv of
1197 MetaTv { mtv_info = info } -> info
1198 _ -> pprPanic "metaTyVarInfo" (ppr tv)
1199
1200 metaTyVarTcLevel :: TcTyVar -> TcLevel
1201 metaTyVarTcLevel tv
1202 = case tcTyVarDetails tv of
1203 MetaTv { mtv_tclvl = tclvl } -> tclvl
1204 _ -> pprPanic "metaTyVarTcLevel" (ppr tv)
1205
1206 metaTyVarTcLevel_maybe :: TcTyVar -> Maybe TcLevel
1207 metaTyVarTcLevel_maybe tv
1208 = case tcTyVarDetails tv of
1209 MetaTv { mtv_tclvl = tclvl } -> Just tclvl
1210 _ -> Nothing
1211
1212 metaTyVarRef :: TyVar -> IORef MetaDetails
1213 metaTyVarRef tv
1214 = case tcTyVarDetails tv of
1215 MetaTv { mtv_ref = ref } -> ref
1216 _ -> pprPanic "metaTyVarRef" (ppr tv)
1217
1218 setMetaTyVarTcLevel :: TcTyVar -> TcLevel -> TcTyVar
1219 setMetaTyVarTcLevel tv tclvl
1220 = case tcTyVarDetails tv of
1221 details@(MetaTv {}) -> setTcTyVarDetails tv (details { mtv_tclvl = tclvl })
1222 _ -> pprPanic "metaTyVarTcLevel" (ppr tv)
1223
1224 isSigTyVar :: Var -> Bool
1225 isSigTyVar tv
1226 = case tcTyVarDetails tv of
1227 MetaTv { mtv_info = SigTv } -> True
1228 _ -> False
1229
1230 isFlexi, isIndirect :: MetaDetails -> Bool
1231 isFlexi Flexi = True
1232 isFlexi _ = False
1233
1234 isIndirect (Indirect _) = True
1235 isIndirect _ = False
1236
1237 isRuntimeUnkSkol :: TyVar -> Bool
1238 -- Called only in TcErrors; see Note [Runtime skolems] there
1239 isRuntimeUnkSkol x
1240 | RuntimeUnk <- tcTyVarDetails x = True
1241 | otherwise = False
1242
1243 {-
1244 ************************************************************************
1245 * *
1246 \subsection{Tau, sigma and rho}
1247 * *
1248 ************************************************************************
1249 -}
1250
1251 mkSigmaTy :: [TyVarBinder] -> [PredType] -> Type -> Type
1252 mkSigmaTy bndrs theta tau = mkForAllTys bndrs (mkPhiTy theta tau)
1253
1254 -- | Make a sigma ty where all type variables are 'Inferred'. That is,
1255 -- they cannot be used with visible type application.
1256 mkInfSigmaTy :: [TyVar] -> [PredType] -> Type -> Type
1257 mkInfSigmaTy tyvars ty = mkSigmaTy (mkTyVarBinders Inferred tyvars) ty
1258
1259 -- | Make a sigma ty where all type variables are "specified". That is,
1260 -- they can be used with visible type application
1261 mkSpecSigmaTy :: [TyVar] -> [PredType] -> Type -> Type
1262 mkSpecSigmaTy tyvars ty = mkSigmaTy (mkTyVarBinders Specified tyvars) ty
1263
1264 mkPhiTy :: [PredType] -> Type -> Type
1265 mkPhiTy = mkFunTys
1266
1267 ---------------
1268 getDFunTyKey :: Type -> OccName -- Get some string from a type, to be used to
1269 -- construct a dictionary function name
1270 getDFunTyKey ty | Just ty' <- coreView ty = getDFunTyKey ty'
1271 getDFunTyKey (TyVarTy tv) = getOccName tv
1272 getDFunTyKey (TyConApp tc _) = getOccName tc
1273 getDFunTyKey (LitTy x) = getDFunTyLitKey x
1274 getDFunTyKey (AppTy fun _) = getDFunTyKey fun
1275 getDFunTyKey (FunTy _ _) = getOccName funTyCon
1276 getDFunTyKey (ForAllTy _ t) = getDFunTyKey t
1277 getDFunTyKey (CastTy ty _) = getDFunTyKey ty
1278 getDFunTyKey t@(CoercionTy _) = pprPanic "getDFunTyKey" (ppr t)
1279
1280 getDFunTyLitKey :: TyLit -> OccName
1281 getDFunTyLitKey (NumTyLit n) = mkOccName Name.varName (show n)
1282 getDFunTyLitKey (StrTyLit n) = mkOccName Name.varName (show n) -- hm
1283
1284 ---------------
1285 mkNakedTyConApp :: TyCon -> [Type] -> Type
1286 -- Builds a TyConApp
1287 -- * without being strict in TyCon,
1288 -- * without satisfying the invariants of TyConApp
1289 -- A subsequent zonking will establish the invariants
1290 -- See Note [Type-checking inside the knot] in TcHsType
1291 mkNakedTyConApp tc tys = TyConApp tc tys
1292
1293 mkNakedAppTys :: Type -> [Type] -> Type
1294 -- See Note [Type-checking inside the knot] in TcHsType
1295 mkNakedAppTys ty1 [] = ty1
1296 mkNakedAppTys (TyConApp tc tys1) tys2 = mkNakedTyConApp tc (tys1 ++ tys2)
1297 mkNakedAppTys ty1 tys2 = foldl AppTy ty1 tys2
1298
1299 mkNakedAppTy :: Type -> Type -> Type
1300 -- See Note [Type-checking inside the knot] in TcHsType
1301 mkNakedAppTy ty1 ty2 = mkNakedAppTys ty1 [ty2]
1302
1303 mkNakedCastTy :: Type -> Coercion -> Type
1304 -- Do simple, fast compaction; especially dealing with Refl
1305 -- for which it's plain stupid to create a cast
1306 -- This simple function killed off a huge number of Refl casts
1307 -- in types, at birth.
1308 -- Note that it's fine to do this even for a "mkNaked" function,
1309 -- because we don't look at TyCons. isReflCo checks if the coercion
1310 -- is structurally Refl; it does not check for shape k ~ k.
1311 mkNakedCastTy ty co | isReflCo co = ty
1312 mkNakedCastTy (CastTy ty co1) co2 = CastTy ty (co1 `mkTransCo` co2)
1313 mkNakedCastTy ty co = CastTy ty co
1314
1315 {-
1316 ************************************************************************
1317 * *
1318 \subsection{Expanding and splitting}
1319 * *
1320 ************************************************************************
1321
1322 These tcSplit functions are like their non-Tc analogues, but
1323 *) they do not look through newtypes
1324
1325 However, they are non-monadic and do not follow through mutable type
1326 variables. It's up to you to make sure this doesn't matter.
1327 -}
1328
1329 -- | Splits a forall type into a list of 'TyBinder's and the inner type.
1330 -- Always succeeds, even if it returns an empty list.
1331 tcSplitPiTys :: Type -> ([TyBinder], Type)
1332 tcSplitPiTys = splitPiTys
1333
1334 tcSplitForAllTy_maybe :: Type -> Maybe (TyVarBinder, Type)
1335 tcSplitForAllTy_maybe ty | Just ty' <- coreView ty = tcSplitForAllTy_maybe ty'
1336 tcSplitForAllTy_maybe (ForAllTy tv ty) = Just (tv, ty)
1337 tcSplitForAllTy_maybe _ = Nothing
1338
1339 -- | Like 'tcSplitPiTys', but splits off only named binders, returning
1340 -- just the tycovars.
1341 tcSplitForAllTys :: Type -> ([TyVar], Type)
1342 tcSplitForAllTys = splitForAllTys
1343
1344 -- | Like 'tcSplitForAllTys', but splits off only named binders.
1345 tcSplitForAllTyVarBndrs :: Type -> ([TyVarBinder], Type)
1346 tcSplitForAllTyVarBndrs = splitForAllTyVarBndrs
1347
1348 -- | Is this a ForAllTy with a named binder?
1349 tcIsForAllTy :: Type -> Bool
1350 tcIsForAllTy ty | Just ty' <- coreView ty = tcIsForAllTy ty'
1351 tcIsForAllTy (ForAllTy {}) = True
1352 tcIsForAllTy _ = False
1353
1354 tcSplitPredFunTy_maybe :: Type -> Maybe (PredType, Type)
1355 -- Split off the first predicate argument from a type
1356 tcSplitPredFunTy_maybe ty
1357 | Just ty' <- coreView ty = tcSplitPredFunTy_maybe ty'
1358 tcSplitPredFunTy_maybe (FunTy arg res)
1359 | isPredTy arg = Just (arg, res)
1360 tcSplitPredFunTy_maybe _
1361 = Nothing
1362
1363 tcSplitPhiTy :: Type -> (ThetaType, Type)
1364 tcSplitPhiTy ty
1365 = split ty []
1366 where
1367 split ty ts
1368 = case tcSplitPredFunTy_maybe ty of
1369 Just (pred, ty) -> split ty (pred:ts)
1370 Nothing -> (reverse ts, ty)
1371
1372 -- | Split a sigma type into its parts.
1373 tcSplitSigmaTy :: Type -> ([TyVar], ThetaType, Type)
1374 tcSplitSigmaTy ty = case tcSplitForAllTys ty of
1375 (tvs, rho) -> case tcSplitPhiTy rho of
1376 (theta, tau) -> (tvs, theta, tau)
1377
1378 -- | Split a sigma type into its parts, going underneath as many @ForAllTy@s
1379 -- as possible. For example, given this type synonym:
1380 --
1381 -- @
1382 -- type Traversal s t a b = forall f. Applicative f => (a -> f b) -> s -> f t
1383 -- @
1384 --
1385 -- if you called @tcSplitSigmaTy@ on this type:
1386 --
1387 -- @
1388 -- forall s t a b. Each s t a b => Traversal s t a b
1389 -- @
1390 --
1391 -- then it would return @([s,t,a,b], [Each s t a b], Traversal s t a b)@. But
1392 -- if you instead called @tcSplitNestedSigmaTys@ on the type, it would return
1393 -- @([s,t,a,b,f], [Each s t a b, Applicative f], (a -> f b) -> s -> f t)@.
1394 tcSplitNestedSigmaTys :: Type -> ([TyVar], ThetaType, Type)
1395 -- NB: This is basically a pure version of deeplyInstantiate (from Inst) that
1396 -- doesn't compute an HsWrapper.
1397 tcSplitNestedSigmaTys ty
1398 -- If there's a forall, split it apart and try splitting the rho type
1399 -- underneath it.
1400 | Just (arg_tys, tvs1, theta1, rho1) <- tcDeepSplitSigmaTy_maybe ty
1401 = let (tvs2, theta2, rho2) = tcSplitNestedSigmaTys rho1
1402 in (tvs1 ++ tvs2, theta1 ++ theta2, mkFunTys arg_tys rho2)
1403 -- If there's no forall, we're done.
1404 | otherwise = ([], [], ty)
1405
1406 -----------------------
1407 tcDeepSplitSigmaTy_maybe
1408 :: TcSigmaType -> Maybe ([TcType], [TyVar], ThetaType, TcSigmaType)
1409 -- Looks for a *non-trivial* quantified type, under zero or more function arrows
1410 -- By "non-trivial" we mean either tyvars or constraints are non-empty
1411
1412 tcDeepSplitSigmaTy_maybe ty
1413 | Just (arg_ty, res_ty) <- tcSplitFunTy_maybe ty
1414 , Just (arg_tys, tvs, theta, rho) <- tcDeepSplitSigmaTy_maybe res_ty
1415 = Just (arg_ty:arg_tys, tvs, theta, rho)
1416
1417 | (tvs, theta, rho) <- tcSplitSigmaTy ty
1418 , not (null tvs && null theta)
1419 = Just ([], tvs, theta, rho)
1420
1421 | otherwise = Nothing
1422
1423 -----------------------
1424 tcTyConAppTyCon :: Type -> TyCon
1425 tcTyConAppTyCon ty
1426 = case tcTyConAppTyCon_maybe ty of
1427 Just tc -> tc
1428 Nothing -> pprPanic "tcTyConAppTyCon" (pprType ty)
1429
1430 -- | Like 'tcRepSplitTyConApp_maybe', but only returns the 'TyCon'.
1431 tcTyConAppTyCon_maybe :: Type -> Maybe TyCon
1432 tcTyConAppTyCon_maybe ty
1433 | Just ty' <- coreView ty = tcTyConAppTyCon_maybe ty'
1434 tcTyConAppTyCon_maybe (TyConApp tc _)
1435 = Just tc
1436 tcTyConAppTyCon_maybe (FunTy _ _)
1437 = Just funTyCon
1438 tcTyConAppTyCon_maybe _
1439 = Nothing
1440
1441 tcTyConAppArgs :: Type -> [Type]
1442 tcTyConAppArgs ty = case tcSplitTyConApp_maybe ty of
1443 Just (_, args) -> args
1444 Nothing -> pprPanic "tcTyConAppArgs" (pprType ty)
1445
1446 tcSplitTyConApp :: Type -> (TyCon, [Type])
1447 tcSplitTyConApp ty = case tcSplitTyConApp_maybe ty of
1448 Just stuff -> stuff
1449 Nothing -> pprPanic "tcSplitTyConApp" (pprType ty)
1450
1451 -- | Split a type constructor application into its type constructor and
1452 -- applied types. Note that this may fail in the case of a 'FunTy' with an
1453 -- argument of unknown kind 'FunTy' (e.g. @FunTy (a :: k) Int@. since the kind
1454 -- of @a@ isn't of the form @TYPE rep@). Consequently, you may need to zonk your
1455 -- type before using this function.
1456 --
1457 -- If you only need the 'TyCon', consider using 'tcTyConAppTyCon_maybe'.
1458 tcSplitTyConApp_maybe :: HasCallStack => Type -> Maybe (TyCon, [Type])
1459 tcSplitTyConApp_maybe ty | Just ty' <- coreView ty = tcSplitTyConApp_maybe ty'
1460 tcSplitTyConApp_maybe ty = tcRepSplitTyConApp_maybe ty
1461
1462 -- | Like 'tcSplitTyConApp_maybe' but doesn't look through type synonyms.
1463 tcRepSplitTyConApp_maybe :: HasCallStack => Type -> Maybe (TyCon, [Type])
1464 tcRepSplitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
1465 tcRepSplitTyConApp_maybe (FunTy arg res)
1466 | Just arg_rep <- getRuntimeRep_maybe arg
1467 , Just res_rep <- getRuntimeRep_maybe res
1468 = Just (funTyCon, [arg_rep, res_rep, arg, res])
1469
1470 | otherwise
1471 = pprPanic "tcRepSplitTyConApp_maybe" (ppr arg $$ ppr res)
1472 tcRepSplitTyConApp_maybe _ = Nothing
1473
1474 -- | Like 'tcRepSplitTyConApp_maybe', but returns 'Nothing' if,
1475 --
1476 -- 1. the type is structurally not a type constructor application, or
1477 --
1478 -- 2. the type is a function type (e.g. application of 'funTyCon'), but we
1479 -- currently don't even enough information to fully determine its RuntimeRep
1480 -- variables. For instance, @FunTy (a :: k) Int@.
1481 --
1482 -- By contrast 'tcRepSplitTyConApp_maybe' panics in the second case.
1483 --
1484 -- The behavior here is needed during canonicalization; see Note [FunTy and
1485 -- decomposing tycon applications] in TcCanonical for details.
1486 tcRepSplitTyConApp_maybe' :: HasCallStack => Type -> Maybe (TyCon, [Type])
1487 tcRepSplitTyConApp_maybe' (TyConApp tc tys) = Just (tc, tys)
1488 tcRepSplitTyConApp_maybe' (FunTy arg res)
1489 | Just arg_rep <- getRuntimeRep_maybe arg
1490 , Just res_rep <- getRuntimeRep_maybe res
1491 = Just (funTyCon, [arg_rep, res_rep, arg, res])
1492 tcRepSplitTyConApp_maybe' _ = Nothing
1493
1494
1495 -----------------------
1496 tcSplitFunTys :: Type -> ([Type], Type)
1497 tcSplitFunTys ty = case tcSplitFunTy_maybe ty of
1498 Nothing -> ([], ty)
1499 Just (arg,res) -> (arg:args, res')
1500 where
1501 (args,res') = tcSplitFunTys res
1502
1503 tcSplitFunTy_maybe :: Type -> Maybe (Type, Type)
1504 tcSplitFunTy_maybe ty | Just ty' <- coreView ty = tcSplitFunTy_maybe ty'
1505 tcSplitFunTy_maybe (FunTy arg res) | not (isPredTy arg) = Just (arg, res)
1506 tcSplitFunTy_maybe _ = Nothing
1507 -- Note the typeKind guard
1508 -- Consider (?x::Int) => Bool
1509 -- We don't want to treat this as a function type!
1510 -- A concrete example is test tc230:
1511 -- f :: () -> (?p :: ()) => () -> ()
1512 --
1513 -- g = f () ()
1514
1515 tcSplitFunTysN :: Arity -- N: Number of desired args
1516 -> TcRhoType
1517 -> Either Arity -- Number of missing arrows
1518 ([TcSigmaType], -- Arg types (always N types)
1519 TcSigmaType) -- The rest of the type
1520 -- ^ Split off exactly the specified number argument types
1521 -- Returns
1522 -- (Left m) if there are 'm' missing arrows in the type
1523 -- (Right (tys,res)) if the type looks like t1 -> ... -> tn -> res
1524 tcSplitFunTysN n ty
1525 | n == 0
1526 = Right ([], ty)
1527 | Just (arg,res) <- tcSplitFunTy_maybe ty
1528 = case tcSplitFunTysN (n-1) res of
1529 Left m -> Left m
1530 Right (args,body) -> Right (arg:args, body)
1531 | otherwise
1532 = Left n
1533
1534 tcSplitFunTy :: Type -> (Type, Type)
1535 tcSplitFunTy ty = expectJust "tcSplitFunTy" (tcSplitFunTy_maybe ty)
1536
1537 tcFunArgTy :: Type -> Type
1538 tcFunArgTy ty = fst (tcSplitFunTy ty)
1539
1540 tcFunResultTy :: Type -> Type
1541 tcFunResultTy ty = snd (tcSplitFunTy ty)
1542
1543 -- | Strips off n *visible* arguments and returns the resulting type
1544 tcFunResultTyN :: HasDebugCallStack => Arity -> Type -> Type
1545 tcFunResultTyN n ty
1546 | Right (_, res_ty) <- tcSplitFunTysN n ty
1547 = res_ty
1548 | otherwise
1549 = pprPanic "tcFunResultTyN" (ppr n <+> ppr ty)
1550
1551 -----------------------
1552 tcSplitAppTy_maybe :: Type -> Maybe (Type, Type)
1553 tcSplitAppTy_maybe ty | Just ty' <- coreView ty = tcSplitAppTy_maybe ty'
1554 tcSplitAppTy_maybe ty = tcRepSplitAppTy_maybe ty
1555
1556 tcSplitAppTy :: Type -> (Type, Type)
1557 tcSplitAppTy ty = case tcSplitAppTy_maybe ty of
1558 Just stuff -> stuff
1559 Nothing -> pprPanic "tcSplitAppTy" (pprType ty)
1560
1561 tcSplitAppTys :: Type -> (Type, [Type])
1562 tcSplitAppTys ty
1563 = go ty []
1564 where
1565 go ty args = case tcSplitAppTy_maybe ty of
1566 Just (ty', arg) -> go ty' (arg:args)
1567 Nothing -> (ty,args)
1568
1569 -----------------------
1570 tcGetTyVar_maybe :: Type -> Maybe TyVar
1571 tcGetTyVar_maybe ty | Just ty' <- coreView ty = tcGetTyVar_maybe ty'
1572 tcGetTyVar_maybe (TyVarTy tv) = Just tv
1573 tcGetTyVar_maybe _ = Nothing
1574
1575 tcGetTyVar :: String -> Type -> TyVar
1576 tcGetTyVar msg ty = expectJust msg (tcGetTyVar_maybe ty)
1577
1578 tcIsTyVarTy :: Type -> Bool
1579 tcIsTyVarTy ty | Just ty' <- coreView ty = tcIsTyVarTy ty'
1580 tcIsTyVarTy (CastTy ty _) = tcIsTyVarTy ty -- look through casts, as
1581 -- this is only used for
1582 -- e.g., FlexibleContexts
1583 tcIsTyVarTy (TyVarTy _) = True
1584 tcIsTyVarTy _ = False
1585
1586 -----------------------
1587 tcSplitDFunTy :: Type -> ([TyVar], [Type], Class, [Type])
1588 -- Split the type of a dictionary function
1589 -- We don't use tcSplitSigmaTy, because a DFun may (with NDP)
1590 -- have non-Pred arguments, such as
1591 -- df :: forall m. (forall b. Eq b => Eq (m b)) -> C m
1592 --
1593 -- Also NB splitFunTys, not tcSplitFunTys;
1594 -- the latter specifically stops at PredTy arguments,
1595 -- and we don't want to do that here
1596 tcSplitDFunTy ty
1597 = case tcSplitForAllTys ty of { (tvs, rho) ->
1598 case splitFunTys rho of { (theta, tau) ->
1599 case tcSplitDFunHead tau of { (clas, tys) ->
1600 (tvs, theta, clas, tys) }}}
1601
1602 tcSplitDFunHead :: Type -> (Class, [Type])
1603 tcSplitDFunHead = getClassPredTys
1604
1605 tcSplitMethodTy :: Type -> ([TyVar], PredType, Type)
1606 -- A class method (selector) always has a type like
1607 -- forall as. C as => blah
1608 -- So if the class looks like
1609 -- class C a where
1610 -- op :: forall b. (Eq a, Ix b) => a -> b
1611 -- the class method type looks like
1612 -- op :: forall a. C a => forall b. (Eq a, Ix b) => a -> b
1613 --
1614 -- tcSplitMethodTy just peels off the outer forall and
1615 -- that first predicate
1616 tcSplitMethodTy ty
1617 | (sel_tyvars,sel_rho) <- tcSplitForAllTys ty
1618 , Just (first_pred, local_meth_ty) <- tcSplitPredFunTy_maybe sel_rho
1619 = (sel_tyvars, first_pred, local_meth_ty)
1620 | otherwise
1621 = pprPanic "tcSplitMethodTy" (ppr ty)
1622
1623
1624 {- *********************************************************************
1625 * *
1626 Type equalities
1627 * *
1628 ********************************************************************* -}
1629
1630 tcEqKind :: TcKind -> TcKind -> Bool
1631 tcEqKind = tcEqType
1632
1633 tcEqType :: TcType -> TcType -> Bool
1634 -- tcEqType is a proper implements the same Note [Non-trivial definitional
1635 -- equality] (in TyCoRep) as `eqType`, but Type.eqType believes (* ==
1636 -- Constraint), and that is NOT what we want in the type checker!
1637 tcEqType ty1 ty2
1638 = isNothing (tc_eq_type coreView ki1 ki2) &&
1639 isNothing (tc_eq_type coreView ty1 ty2)
1640 where
1641 ki1 = typeKind ty1
1642 ki2 = typeKind ty2
1643
1644 -- | Just like 'tcEqType', but will return True for types of different kinds
1645 -- as long as their non-coercion structure is identical.
1646 tcEqTypeNoKindCheck :: TcType -> TcType -> Bool
1647 tcEqTypeNoKindCheck ty1 ty2
1648 = isNothing $ tc_eq_type coreView ty1 ty2
1649
1650 -- | Like 'tcEqType', but returns information about whether the difference
1651 -- is visible in the case of a mismatch.
1652 -- @Nothing@ : the types are equal
1653 -- @Just True@ : the types differ, and the point of difference is visible
1654 -- @Just False@ : the types differ, and the point of difference is invisible
1655 tcEqTypeVis :: TcType -> TcType -> Maybe Bool
1656 tcEqTypeVis ty1 ty2
1657 = tc_eq_type coreView ty1 ty2 <!> invis (tc_eq_type coreView ki1 ki2)
1658 where
1659 ki1 = typeKind ty1
1660 ki2 = typeKind ty2
1661
1662 -- convert Just True to Just False
1663 invis :: Maybe Bool -> Maybe Bool
1664 invis = fmap (const False)
1665
1666 (<!>) :: Maybe Bool -> Maybe Bool -> Maybe Bool
1667 Nothing <!> x = x
1668 Just True <!> _ = Just True
1669 Just _vis <!> Just True = Just True
1670 Just vis <!> _ = Just vis
1671 infixr 3 <!>
1672
1673 -- | Real worker for 'tcEqType'. No kind check!
1674 tc_eq_type :: (TcType -> Maybe TcType) -- ^ @coreView@, if you want unwrapping
1675 -> Type -> Type -> Maybe Bool
1676 tc_eq_type view_fun orig_ty1 orig_ty2 = go True orig_env orig_ty1 orig_ty2
1677 where
1678 go :: Bool -> RnEnv2 -> Type -> Type -> Maybe Bool
1679 go vis env t1 t2 | Just t1' <- view_fun t1 = go vis env t1' t2
1680 go vis env t1 t2 | Just t2' <- view_fun t2 = go vis env t1 t2'
1681
1682 go vis env (TyVarTy tv1) (TyVarTy tv2)
1683 = check vis $ rnOccL env tv1 == rnOccR env tv2
1684
1685 go vis _ (LitTy lit1) (LitTy lit2)
1686 = check vis $ lit1 == lit2
1687
1688 go vis env (ForAllTy (TvBndr tv1 vis1) ty1)
1689 (ForAllTy (TvBndr tv2 vis2) ty2)
1690 = go (isVisibleArgFlag vis1) env (tyVarKind tv1) (tyVarKind tv2)
1691 <!> go vis (rnBndr2 env tv1 tv2) ty1 ty2
1692 <!> check vis (vis1 == vis2)
1693 -- Make sure we handle all FunTy cases since falling through to the
1694 -- AppTy case means that tcRepSplitAppTy_maybe may see an unzonked
1695 -- kind variable, which causes things to blow up.
1696 go vis env (FunTy arg1 res1) (FunTy arg2 res2)
1697 = go vis env arg1 arg2 <!> go vis env res1 res2
1698 go vis env ty (FunTy arg res)
1699 = eqFunTy vis env arg res ty
1700 go vis env (FunTy arg res) ty
1701 = eqFunTy vis env arg res ty
1702
1703 -- See Note [Equality on AppTys] in Type
1704 go vis env (AppTy s1 t1) ty2
1705 | Just (s2, t2) <- tcRepSplitAppTy_maybe ty2
1706 = go vis env s1 s2 <!> go vis env t1 t2
1707 go vis env ty1 (AppTy s2 t2)
1708 | Just (s1, t1) <- tcRepSplitAppTy_maybe ty1
1709 = go vis env s1 s2 <!> go vis env t1 t2
1710 go vis env (TyConApp tc1 ts1) (TyConApp tc2 ts2)
1711 = check vis (tc1 == tc2) <!> gos (tc_vis vis tc1) env ts1 ts2
1712 go vis env (CastTy t1 _) t2 = go vis env t1 t2
1713 go vis env t1 (CastTy t2 _) = go vis env t1 t2
1714 go _ _ (CoercionTy {}) (CoercionTy {}) = Nothing
1715 go vis _ _ _ = Just vis
1716
1717 gos _ _ [] [] = Nothing
1718 gos (v:vs) env (t1:ts1) (t2:ts2) = go v env t1 t2 <!> gos vs env ts1 ts2
1719 gos (v:_) _ _ _ = Just v
1720 gos _ _ _ _ = panic "tc_eq_type"
1721
1722 tc_vis :: Bool -> TyCon -> [Bool]
1723 tc_vis True tc = viss ++ repeat True
1724 -- the repeat True is necessary because tycons can legitimately
1725 -- be oversaturated
1726 where
1727 bndrs = tyConBinders tc
1728 viss = map (isVisibleArgFlag . tyConBinderArgFlag) bndrs
1729 tc_vis False _ = repeat False -- if we're not in a visible context, our args
1730 -- aren't either
1731
1732 check :: Bool -> Bool -> Maybe Bool
1733 check _ True = Nothing
1734 check vis False = Just vis
1735
1736 orig_env = mkRnEnv2 $ mkInScopeSet $ tyCoVarsOfTypes [orig_ty1, orig_ty2]
1737
1738 -- @eqFunTy arg res ty@ is True when @ty@ equals @FunTy arg res@. This is
1739 -- sometimes hard to know directly because @ty@ might have some casts
1740 -- obscuring the FunTy. And 'splitAppTy' is difficult because we can't
1741 -- always extract a RuntimeRep (see Note [xyz]) if the kind of the arg or
1742 -- res is unzonked/unflattened. Thus this function, which handles this
1743 -- corner case.
1744 eqFunTy :: Bool -> RnEnv2 -> Type -> Type -> Type -> Maybe Bool
1745 eqFunTy vis env arg res (FunTy arg' res')
1746 = go vis env arg arg' <!> go vis env res res'
1747 eqFunTy vis env arg res ty@(AppTy{})
1748 | Just (tc, [_, _, arg', res']) <- get_args ty []
1749 , tc == funTyCon
1750 = go vis env arg arg' <!> go vis env res res'
1751 where
1752 get_args :: Type -> [Type] -> Maybe (TyCon, [Type])
1753 get_args (AppTy f x) args = get_args f (x:args)
1754 get_args (CastTy t _) args = get_args t args
1755 get_args (TyConApp tc tys) args = Just (tc, tys ++ args)
1756 get_args _ _ = Nothing
1757 eqFunTy vis _ _ _ _
1758 = Just vis
1759
1760 -- | Like 'pickyEqTypeVis', but returns a Bool for convenience
1761 pickyEqType :: TcType -> TcType -> Bool
1762 -- Check when two types _look_ the same, _including_ synonyms.
1763 -- So (pickyEqType String [Char]) returns False
1764 -- This ignores kinds and coercions, because this is used only for printing.
1765 pickyEqType ty1 ty2
1766 = isNothing $
1767 tc_eq_type (const Nothing) ty1 ty2
1768
1769 {- *********************************************************************
1770 * *
1771 Predicate types
1772 * *
1773 ************************************************************************
1774
1775 Deconstructors and tests on predicate types
1776
1777 Note [Kind polymorphic type classes]
1778 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1779 class C f where... -- C :: forall k. k -> Constraint
1780 g :: forall (f::*). C f => f -> f
1781
1782 Here the (C f) in the signature is really (C * f), and we
1783 don't want to complain that the * isn't a type variable!
1784 -}
1785
1786 isTyVarClassPred :: PredType -> Bool
1787 isTyVarClassPred ty = case getClassPredTys_maybe ty of
1788 Just (_, tys) -> all isTyVarTy tys
1789 _ -> False
1790
1791 -------------------------
1792 checkValidClsArgs :: Bool -> Class -> [KindOrType] -> Bool
1793 -- If the Bool is True (flexible contexts), return True (i.e. ok)
1794 -- Otherwise, check that the type (not kind) args are all headed by a tyvar
1795 -- E.g. (Eq a) accepted, (Eq (f a)) accepted, but (Eq Int) rejected
1796 -- This function is here rather than in TcValidity because it is
1797 -- called from TcSimplify, which itself is imported by TcValidity
1798 checkValidClsArgs flexible_contexts cls kts
1799 | flexible_contexts = True
1800 | otherwise = all hasTyVarHead tys
1801 where
1802 tys = filterOutInvisibleTypes (classTyCon cls) kts
1803
1804 hasTyVarHead :: Type -> Bool
1805 -- Returns true of (a t1 .. tn), where 'a' is a type variable
1806 hasTyVarHead ty -- Haskell 98 allows predicates of form
1807 | tcIsTyVarTy ty = True -- C (a ty1 .. tyn)
1808 | otherwise -- where a is a type variable
1809 = case tcSplitAppTy_maybe ty of
1810 Just (ty, _) -> hasTyVarHead ty
1811 Nothing -> False
1812
1813 evVarPred_maybe :: EvVar -> Maybe PredType
1814 evVarPred_maybe v = if isPredTy ty then Just ty else Nothing
1815 where ty = varType v
1816
1817 evVarPred :: EvVar -> PredType
1818 evVarPred var
1819 | debugIsOn
1820 = case evVarPred_maybe var of
1821 Just pred -> pred
1822 Nothing -> pprPanic "tcEvVarPred" (ppr var <+> ppr (varType var))
1823 | otherwise
1824 = varType var
1825
1826 ------------------
1827 -- | When inferring types, should we quantify over a given predicate?
1828 -- Generally true of classes; generally false of equality constraints.
1829 -- Equality constraints that mention quantified type variables and
1830 -- implicit variables complicate the story. See Notes
1831 -- [Inheriting implicit parameters] and [Quantifying over equality constraints]
1832 pickQuantifiablePreds
1833 :: TyVarSet -- Quantifying over these
1834 -> TcThetaType -- Proposed constraints to quantify
1835 -> TcThetaType -- A subset that we can actually quantify
1836 -- This function decides whether a particular constraint should be
1837 -- quantified over, given the type variables that are being quantified
1838 pickQuantifiablePreds qtvs theta
1839 = let flex_ctxt = True in -- Quantify over non-tyvar constraints, even without
1840 -- -XFlexibleContexts: see Trac #10608, #10351
1841 -- flex_ctxt <- xoptM Opt_FlexibleContexts
1842 filter (pick_me flex_ctxt) theta
1843 where
1844 pick_me flex_ctxt pred
1845 = case classifyPredType pred of
1846
1847 ClassPred cls tys
1848 | Just {} <- isCallStackPred pred
1849 -- NEVER infer a CallStack constraint
1850 -- Otherwise, we let the constraints bubble up to be
1851 -- solved from the outer context, or be defaulted when we
1852 -- reach the top-level.
1853 -- see Note [Overview of implicit CallStacks]
1854 -> False
1855
1856 | isIPClass cls -> True -- See note [Inheriting implicit parameters]
1857
1858 | otherwise
1859 -> pick_cls_pred flex_ctxt cls tys
1860
1861 EqPred ReprEq ty1 ty2 -> pick_cls_pred flex_ctxt coercibleClass [ty1, ty2]
1862 -- representational equality is like a class constraint
1863
1864 EqPred NomEq ty1 ty2 -> quant_fun ty1 || quant_fun ty2
1865 IrredPred ty -> tyCoVarsOfType ty `intersectsVarSet` qtvs
1866
1867 pick_cls_pred flex_ctxt cls tys
1868 = tyCoVarsOfTypes tys `intersectsVarSet` qtvs
1869 && (checkValidClsArgs flex_ctxt cls tys)
1870 -- Only quantify over predicates that checkValidType
1871 -- will pass! See Trac #10351.
1872
1873 -- See Note [Quantifying over equality constraints]
1874 quant_fun ty
1875 = case tcSplitTyConApp_maybe ty of
1876 Just (tc, tys) | isTypeFamilyTyCon tc
1877 -> tyCoVarsOfTypes tys `intersectsVarSet` qtvs
1878 _ -> False
1879
1880 pickCapturedPreds
1881 :: TyVarSet -- Quantifying over these
1882 -> TcThetaType -- Proposed constraints to quantify
1883 -> TcThetaType -- A subset that we can actually quantify
1884 -- A simpler version of pickQuantifiablePreds, used to winnow down
1885 -- the inferred constrains of a group of bindings, into those for
1886 -- one particular identifier
1887 pickCapturedPreds qtvs theta
1888 = filter captured theta
1889 where
1890 captured pred = isIPPred pred || (tyCoVarsOfType pred `intersectsVarSet` qtvs)
1891
1892
1893 -- Superclasses
1894
1895 type PredWithSCs = (PredType, [PredType])
1896
1897 mkMinimalBySCs :: [PredType] -> [PredType]
1898 -- Remove predicates that can be deduced from others by superclasses,
1899 -- including duplicate predicates. The result is a subset of the input.
1900 mkMinimalBySCs ptys = go preds_with_scs []
1901 where
1902 preds_with_scs :: [PredWithSCs]
1903 preds_with_scs = [ (pred, pred : transSuperClasses pred)
1904 | pred <- ptys ]
1905
1906 go :: [PredWithSCs] -- Work list
1907 -> [PredWithSCs] -- Accumulating result
1908 -> [PredType]
1909 go [] min_preds = map fst min_preds
1910 go (work_item@(p,_) : work_list) min_preds
1911 | p `in_cloud` work_list || p `in_cloud` min_preds
1912 = go work_list min_preds
1913 | otherwise
1914 = go work_list (work_item : min_preds)
1915
1916 in_cloud :: PredType -> [PredWithSCs] -> Bool
1917 in_cloud p ps = or [ p `eqType` p' | (_, scs) <- ps, p' <- scs ]
1918
1919 transSuperClasses :: PredType -> [PredType]
1920 -- (transSuperClasses p) returns (p's superclasses) not including p
1921 -- Stop if you encounter the same class again
1922 -- See Note [Expanding superclasses]
1923 transSuperClasses p
1924 = go emptyNameSet p
1925 where
1926 go :: NameSet -> PredType -> [PredType]
1927 go rec_clss p
1928 | ClassPred cls tys <- classifyPredType p
1929 , let cls_nm = className cls
1930 , not (cls_nm `elemNameSet` rec_clss)
1931 , let rec_clss' | isCTupleClass cls = rec_clss
1932 | otherwise = rec_clss `extendNameSet` cls_nm
1933 = [ p' | sc <- immSuperClasses cls tys
1934 , p' <- sc : go rec_clss' sc ]
1935 | otherwise
1936 = []
1937
1938 immSuperClasses :: Class -> [Type] -> [PredType]
1939 immSuperClasses cls tys
1940 = substTheta (zipTvSubst tyvars tys) sc_theta
1941 where
1942 (tyvars,sc_theta,_,_) = classBigSig cls
1943
1944 isImprovementPred :: PredType -> Bool
1945 -- Either it's an equality, or has some functional dependency
1946 isImprovementPred ty
1947 = case classifyPredType ty of
1948 EqPred NomEq t1 t2 -> not (t1 `tcEqType` t2)
1949 EqPred ReprEq _ _ -> False
1950 ClassPred cls _ -> classHasFds cls
1951 IrredPred {} -> True -- Might have equalities after reduction?
1952
1953 {- Note [Expanding superclasses]
1954 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1955 When we expand superclasses, we use the following algorithm:
1956
1957 expand( so_far, pred ) returns the transitive superclasses of pred,
1958 not including pred itself
1959 1. If pred is not a class constraint, return empty set
1960 Otherwise pred = C ts
1961 2. If C is in so_far, return empty set (breaks loops)
1962 3. Find the immediate superclasses constraints of (C ts)
1963 4. For each such sc_pred, return (sc_pred : expand( so_far+C, D ss )
1964
1965 Notice that
1966
1967 * With normal Haskell-98 classes, the loop-detector will never bite,
1968 so we'll get all the superclasses.
1969
1970 * Since there is only a finite number of distinct classes, expansion
1971 must terminate.
1972
1973 * The loop breaking is a bit conservative. Notably, a tuple class
1974 could contain many times without threatening termination:
1975 (Eq a, (Ord a, Ix a))
1976 And this is try of any class that we can statically guarantee
1977 as non-recursive (in some sense). For now, we just make a special
1978 case for tuples. Something better would be cool.
1979
1980 See also TcTyDecls.checkClassCycles.
1981
1982 Note [Inheriting implicit parameters]
1983 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1984 Consider this:
1985
1986 f x = (x::Int) + ?y
1987
1988 where f is *not* a top-level binding.
1989 From the RHS of f we'll get the constraint (?y::Int).
1990 There are two types we might infer for f:
1991
1992 f :: Int -> Int
1993
1994 (so we get ?y from the context of f's definition), or
1995
1996 f :: (?y::Int) => Int -> Int
1997
1998 At first you might think the first was better, because then
1999 ?y behaves like a free variable of the definition, rather than
2000 having to be passed at each call site. But of course, the WHOLE
2001 IDEA is that ?y should be passed at each call site (that's what
2002 dynamic binding means) so we'd better infer the second.
2003
2004 BOTTOM LINE: when *inferring types* you must quantify over implicit
2005 parameters, *even if* they don't mention the bound type variables.
2006 Reason: because implicit parameters, uniquely, have local instance
2007 declarations. See pickQuantifiablePreds.
2008
2009 Note [Quantifying over equality constraints]
2010 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2011 Should we quantify over an equality constraint (s ~ t)? In general, we don't.
2012 Doing so may simply postpone a type error from the function definition site to
2013 its call site. (At worst, imagine (Int ~ Bool)).
2014
2015 However, consider this
2016 forall a. (F [a] ~ Int) => blah
2017 Should we quantify over the (F [a] ~ Int). Perhaps yes, because at the call
2018 site we will know 'a', and perhaps we have instance F [Bool] = Int.
2019 So we *do* quantify over a type-family equality where the arguments mention
2020 the quantified variables.
2021
2022 ************************************************************************
2023 * *
2024 \subsection{Predicates}
2025 * *
2026 ************************************************************************
2027 -}
2028
2029 isSigmaTy :: TcType -> Bool
2030 -- isSigmaTy returns true of any qualified type. It doesn't
2031 -- *necessarily* have any foralls. E.g
2032 -- f :: (?x::Int) => Int -> Int
2033 isSigmaTy ty | Just ty' <- coreView ty = isSigmaTy ty'
2034 isSigmaTy (ForAllTy {}) = True
2035 isSigmaTy (FunTy a _) = isPredTy a
2036 isSigmaTy _ = False
2037
2038 isRhoTy :: TcType -> Bool -- True of TcRhoTypes; see Note [TcRhoType]
2039 isRhoTy ty | Just ty' <- coreView ty = isRhoTy ty'
2040 isRhoTy (ForAllTy {}) = False
2041 isRhoTy (FunTy a r) = not (isPredTy a) && isRhoTy r
2042 isRhoTy _ = True
2043
2044 -- | Like 'isRhoTy', but also says 'True' for 'Infer' types
2045 isRhoExpTy :: ExpType -> Bool
2046 isRhoExpTy (Check ty) = isRhoTy ty
2047 isRhoExpTy (Infer {}) = True
2048
2049 isOverloadedTy :: Type -> Bool
2050 -- Yes for a type of a function that might require evidence-passing
2051 -- Used only by bindLocalMethods
2052 isOverloadedTy ty | Just ty' <- coreView ty = isOverloadedTy ty'
2053 isOverloadedTy (ForAllTy _ ty) = isOverloadedTy ty
2054 isOverloadedTy (FunTy a _) = isPredTy a
2055 isOverloadedTy _ = False
2056
2057 isFloatTy, isDoubleTy, isIntegerTy, isIntTy, isWordTy, isBoolTy,
2058 isUnitTy, isCharTy, isAnyTy :: Type -> Bool
2059 isFloatTy = is_tc floatTyConKey
2060 isDoubleTy = is_tc doubleTyConKey
2061 isIntegerTy = is_tc integerTyConKey
2062 isIntTy = is_tc intTyConKey
2063 isWordTy = is_tc wordTyConKey
2064 isBoolTy = is_tc boolTyConKey
2065 isUnitTy = is_tc unitTyConKey
2066 isCharTy = is_tc charTyConKey
2067 isAnyTy = is_tc anyTyConKey
2068
2069 -- | Does a type represent a floating-point number?
2070 isFloatingTy :: Type -> Bool
2071 isFloatingTy ty = isFloatTy ty || isDoubleTy ty
2072
2073 -- | Is a type 'String'?
2074 isStringTy :: Type -> Bool
2075 isStringTy ty
2076 = case tcSplitTyConApp_maybe ty of
2077 Just (tc, [arg_ty]) -> tc == listTyCon && isCharTy arg_ty
2078 _ -> False
2079
2080 -- | Is a type a 'CallStack'?
2081 isCallStackTy :: Type -> Bool
2082 isCallStackTy ty
2083 | Just tc <- tyConAppTyCon_maybe ty
2084 = tc `hasKey` callStackTyConKey
2085 | otherwise
2086 = False
2087
2088 -- | Is a 'PredType' a 'CallStack' implicit parameter?
2089 --
2090 -- If so, return the name of the parameter.
2091 isCallStackPred :: PredType -> Maybe FastString
2092 isCallStackPred pred
2093 | Just (str, ty) <- isIPPred_maybe pred
2094 , isCallStackTy ty
2095 = Just str
2096 | otherwise
2097 = Nothing
2098
2099 is_tc :: Unique -> Type -> Bool
2100 -- Newtypes are opaque to this
2101 is_tc uniq ty = case tcSplitTyConApp_maybe ty of
2102 Just (tc, _) -> uniq == getUnique tc
2103 Nothing -> False
2104
2105 -- | Does the given tyvar appear in the given type outside of any
2106 -- non-newtypes? Assume we're looking for @a@. Says "yes" for
2107 -- @a@, @N a@, @b a@, @a b@, @b (N a)@. Says "no" for
2108 -- @[a]@, @Maybe a@, @T a@, where @N@ is a newtype and @T@ is a datatype.
2109 isTyVarExposed :: TcTyVar -> TcType -> Bool
2110 isTyVarExposed tv (TyVarTy tv') = tv == tv'
2111 isTyVarExposed tv (TyConApp tc tys)
2112 | isNewTyCon tc = any (isTyVarExposed tv) tys
2113 | otherwise = False
2114 isTyVarExposed _ (LitTy {}) = False
2115 isTyVarExposed tv (AppTy fun arg) = isTyVarExposed tv fun
2116 || isTyVarExposed tv arg
2117 isTyVarExposed _ (ForAllTy {}) = False
2118 isTyVarExposed _ (FunTy {}) = False
2119 isTyVarExposed tv (CastTy ty _) = isTyVarExposed tv ty
2120 isTyVarExposed _ (CoercionTy {}) = False
2121
2122 -- | Does the given tyvar appear under a type generative w.r.t.
2123 -- representational equality? See Note [Occurs check error] in
2124 -- TcCanonical for the motivation for this function.
2125 isTyVarUnderDatatype :: TcTyVar -> TcType -> Bool
2126 isTyVarUnderDatatype tv = go False
2127 where
2128 go under_dt ty | Just ty' <- coreView ty = go under_dt ty'
2129 go under_dt (TyVarTy tv') = under_dt && (tv == tv')
2130 go under_dt (TyConApp tc tys) = let under_dt' = under_dt ||
2131 isGenerativeTyCon tc
2132 Representational
2133 in any (go under_dt') tys
2134 go _ (LitTy {}) = False
2135 go _ (FunTy arg res) = go True arg || go True res
2136 go under_dt (AppTy fun arg) = go under_dt fun || go under_dt arg
2137 go under_dt (ForAllTy (TvBndr tv' _) inner_ty)
2138 | tv' == tv = False
2139 | otherwise = go under_dt inner_ty
2140 go under_dt (CastTy ty _) = go under_dt ty
2141 go _ (CoercionTy {}) = False
2142
2143 isRigidTy :: TcType -> Bool
2144 isRigidTy ty
2145 | Just (tc,_) <- tcSplitTyConApp_maybe ty = isGenerativeTyCon tc Nominal
2146 | Just {} <- tcSplitAppTy_maybe ty = True
2147 | isForAllTy ty = True
2148 | otherwise = False
2149
2150 isRigidEqPred :: TcLevel -> PredTree -> Bool
2151 -- ^ True of all Nominal equalities that are solidly insoluble
2152 -- This means all equalities *except*
2153 -- * Meta-tv non-SigTv on LHS
2154 -- * Meta-tv SigTv on LHS, tyvar on right
2155 isRigidEqPred tc_lvl (EqPred NomEq ty1 _)
2156 | Just tv1 <- tcGetTyVar_maybe ty1
2157 = ASSERT2( tcIsTcTyVar tv1, ppr tv1 )
2158 not (isMetaTyVar tv1) || isTouchableMetaTyVar tc_lvl tv1
2159
2160 | otherwise -- LHS is not a tyvar
2161 = True
2162
2163 isRigidEqPred _ _ = False -- Not an equality
2164
2165 {-
2166 ************************************************************************
2167 * *
2168 \subsection{Transformation of Types to TcTypes}
2169 * *
2170 ************************************************************************
2171 -}
2172
2173 toTcType :: Type -> TcType
2174 -- The constraint solver expects EvVars to have TcType, in which the
2175 -- free type variables are TcTyVars. So we convert from Type to TcType here
2176 -- A bit tiresome; but one day I expect the two types to be entirely separate
2177 -- in which case we'll definitely need to do this
2178 toTcType = runIdentity . to_tc_type emptyVarSet
2179
2180 toTcTypeBag :: Bag EvVar -> Bag EvVar -- All TyVars are transformed to TcTyVars
2181 toTcTypeBag evvars = mapBag (\tv -> setTyVarKind tv (toTcType (tyVarKind tv))) evvars
2182
2183 to_tc_mapper :: TyCoMapper VarSet Identity
2184 to_tc_mapper
2185 = TyCoMapper { tcm_smart = False -- more efficient not to use smart ctors
2186 , tcm_tyvar = tyvar
2187 , tcm_covar = covar
2188 , tcm_hole = hole
2189 , tcm_tybinder = tybinder }
2190 where
2191 tyvar :: VarSet -> TyVar -> Identity Type
2192 tyvar ftvs tv
2193 | Just var <- lookupVarSet ftvs tv = return $ TyVarTy var
2194 | isTcTyVar tv = TyVarTy <$> updateTyVarKindM (to_tc_type ftvs) tv
2195 | otherwise
2196 = do { kind' <- to_tc_type ftvs (tyVarKind tv)
2197 ; return $ TyVarTy $ mkTcTyVar (tyVarName tv) kind' vanillaSkolemTv }
2198
2199 covar :: VarSet -> CoVar -> Identity Coercion
2200 covar ftvs cv
2201 | Just var <- lookupVarSet ftvs cv = return $ CoVarCo var
2202 | otherwise = CoVarCo <$> updateVarTypeM (to_tc_type ftvs) cv
2203
2204 hole :: VarSet -> CoercionHole -> Role -> Type -> Type
2205 -> Identity Coercion
2206 hole ftvs h r t1 t2 = mkHoleCo h r <$> to_tc_type ftvs t1
2207 <*> to_tc_type ftvs t2
2208
2209 tybinder :: VarSet -> TyVar -> ArgFlag -> Identity (VarSet, TyVar)
2210 tybinder ftvs tv _vis = do { kind' <- to_tc_type ftvs (tyVarKind tv)
2211 ; let tv' = mkTcTyVar (tyVarName tv) kind'
2212 vanillaSkolemTv
2213 ; return (ftvs `extendVarSet` tv', tv') }
2214
2215 to_tc_type :: VarSet -> Type -> Identity TcType
2216 to_tc_type = mapType to_tc_mapper
2217
2218 {-
2219 ************************************************************************
2220 * *
2221 \subsection{Misc}
2222 * *
2223 ************************************************************************
2224
2225 Note [Visible type application]
2226 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2227 GHC implements a generalisation of the algorithm described in the
2228 "Visible Type Application" paper (available from
2229 http://www.cis.upenn.edu/~sweirich/publications.html). A key part
2230 of that algorithm is to distinguish user-specified variables from inferred
2231 variables. For example, the following should typecheck:
2232
2233 f :: forall a b. a -> b -> b
2234 f = const id
2235
2236 g = const id
2237
2238 x = f @Int @Bool 5 False
2239 y = g 5 @Bool False
2240
2241 The idea is that we wish to allow visible type application when we are
2242 instantiating a specified, fixed variable. In practice, specified, fixed
2243 variables are either written in a type signature (or
2244 annotation), OR are imported from another module. (We could do better here,
2245 for example by doing SCC analysis on parts of a module and considering any
2246 type from outside one's SCC to be fully specified, but this is very confusing to
2247 users. The simple rule above is much more straightforward and predictable.)
2248
2249 So, both of f's quantified variables are specified and may be instantiated.
2250 But g has no type signature, so only id's variable is specified (because id
2251 is imported). We write the type of g as forall {a}. a -> forall b. b -> b.
2252 Note that the a is in braces, meaning it cannot be instantiated with
2253 visible type application.
2254
2255 Tracking specified vs. inferred variables is done conveniently by a field
2256 in TyBinder.
2257
2258 -}
2259
2260 deNoteType :: Type -> Type
2261 -- Remove all *outermost* type synonyms and other notes
2262 deNoteType ty | Just ty' <- coreView ty = deNoteType ty'
2263 deNoteType ty = ty
2264
2265 {-
2266 Find the free tycons and classes of a type. This is used in the front
2267 end of the compiler.
2268 -}
2269
2270 {-
2271 ************************************************************************
2272 * *
2273 \subsection[TysWiredIn-ext-type]{External types}
2274 * *
2275 ************************************************************************
2276
2277 The compiler's foreign function interface supports the passing of a
2278 restricted set of types as arguments and results (the restricting factor
2279 being the )
2280 -}
2281
2282 tcSplitIOType_maybe :: Type -> Maybe (TyCon, Type)
2283 -- (tcSplitIOType_maybe t) returns Just (IO,t',co)
2284 -- if co : t ~ IO t'
2285 -- returns Nothing otherwise
2286 tcSplitIOType_maybe ty
2287 = case tcSplitTyConApp_maybe ty of
2288 Just (io_tycon, [io_res_ty])
2289 | io_tycon `hasKey` ioTyConKey ->
2290 Just (io_tycon, io_res_ty)
2291 _ ->
2292 Nothing
2293
2294 isFFITy :: Type -> Bool
2295 -- True for any TyCon that can possibly be an arg or result of an FFI call
2296 isFFITy ty = isValid (checkRepTyCon legalFFITyCon ty)
2297
2298 isFFIArgumentTy :: DynFlags -> Safety -> Type -> Validity
2299 -- Checks for valid argument type for a 'foreign import'
2300 isFFIArgumentTy dflags safety ty
2301 = checkRepTyCon (legalOutgoingTyCon dflags safety) ty
2302
2303 isFFIExternalTy :: Type -> Validity
2304 -- Types that are allowed as arguments of a 'foreign export'
2305 isFFIExternalTy ty = checkRepTyCon legalFEArgTyCon ty
2306
2307 isFFIImportResultTy :: DynFlags -> Type -> Validity
2308 isFFIImportResultTy dflags ty
2309 = checkRepTyCon (legalFIResultTyCon dflags) ty
2310
2311 isFFIExportResultTy :: Type -> Validity
2312 isFFIExportResultTy ty = checkRepTyCon legalFEResultTyCon ty
2313
2314 isFFIDynTy :: Type -> Type -> Validity
2315 -- The type in a foreign import dynamic must be Ptr, FunPtr, or a newtype of
2316 -- either, and the wrapped function type must be equal to the given type.
2317 -- We assume that all types have been run through normaliseFfiType, so we don't
2318 -- need to worry about expanding newtypes here.
2319 isFFIDynTy expected ty
2320 -- Note [Foreign import dynamic]
2321 -- In the example below, expected would be 'CInt -> IO ()', while ty would
2322 -- be 'FunPtr (CDouble -> IO ())'.
2323 | Just (tc, [ty']) <- splitTyConApp_maybe ty
2324 , tyConUnique tc `elem` [ptrTyConKey, funPtrTyConKey]
2325 , eqType ty' expected
2326 = IsValid
2327 | otherwise
2328 = NotValid (vcat [ text "Expected: Ptr/FunPtr" <+> pprParendType expected <> comma
2329 , text " Actual:" <+> ppr ty ])
2330
2331 isFFILabelTy :: Type -> Validity
2332 -- The type of a foreign label must be Ptr, FunPtr, or a newtype of either.
2333 isFFILabelTy ty = checkRepTyCon ok ty
2334 where
2335 ok tc | tc `hasKey` funPtrTyConKey || tc `hasKey` ptrTyConKey
2336 = IsValid
2337 | otherwise
2338 = NotValid (text "A foreign-imported address (via &foo) must have type (Ptr a) or (FunPtr a)")
2339
2340 isFFIPrimArgumentTy :: DynFlags -> Type -> Validity
2341 -- Checks for valid argument type for a 'foreign import prim'
2342 -- Currently they must all be simple unlifted types, or the well-known type
2343 -- Any, which can be used to pass the address to a Haskell object on the heap to
2344 -- the foreign function.
2345 isFFIPrimArgumentTy dflags ty
2346 | isAnyTy ty = IsValid
2347 | otherwise = checkRepTyCon (legalFIPrimArgTyCon dflags) ty
2348
2349 isFFIPrimResultTy :: DynFlags -> Type -> Validity
2350 -- Checks for valid result type for a 'foreign import prim' Currently
2351 -- it must be an unlifted type, including unboxed tuples, unboxed
2352 -- sums, or the well-known type Any.
2353 isFFIPrimResultTy dflags ty
2354 | isAnyTy ty = IsValid
2355 | otherwise = checkRepTyCon (legalFIPrimResultTyCon dflags) ty
2356
2357 isFunPtrTy :: Type -> Bool
2358 isFunPtrTy ty
2359 | Just (tc, [_]) <- splitTyConApp_maybe ty
2360 = tc `hasKey` funPtrTyConKey
2361 | otherwise
2362 = False
2363
2364 -- normaliseFfiType gets run before checkRepTyCon, so we don't
2365 -- need to worry about looking through newtypes or type functions
2366 -- here; that's already been taken care of.
2367 checkRepTyCon :: (TyCon -> Validity) -> Type -> Validity
2368 checkRepTyCon check_tc ty
2369 = case splitTyConApp_maybe ty of
2370 Just (tc, tys)
2371 | isNewTyCon tc -> NotValid (hang msg 2 (mk_nt_reason tc tys $$ nt_fix))
2372 | otherwise -> case check_tc tc of
2373 IsValid -> IsValid
2374 NotValid extra -> NotValid (msg $$ extra)
2375 Nothing -> NotValid (quotes (ppr ty) <+> text "is not a data type")
2376 where
2377 msg = quotes (ppr ty) <+> text "cannot be marshalled in a foreign call"
2378 mk_nt_reason tc tys
2379 | null tys = text "because its data constructor is not in scope"
2380 | otherwise = text "because the data constructor for"
2381 <+> quotes (ppr tc) <+> text "is not in scope"
2382 nt_fix = text "Possible fix: import the data constructor to bring it into scope"
2383
2384 {-
2385 Note [Foreign import dynamic]
2386 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2387 A dynamic stub must be of the form 'FunPtr ft -> ft' where ft is any foreign
2388 type. Similarly, a wrapper stub must be of the form 'ft -> IO (FunPtr ft)'.
2389
2390 We use isFFIDynTy to check whether a signature is well-formed. For example,
2391 given a (illegal) declaration like:
2392
2393 foreign import ccall "dynamic"
2394 foo :: FunPtr (CDouble -> IO ()) -> CInt -> IO ()
2395
2396 isFFIDynTy will compare the 'FunPtr' type 'CDouble -> IO ()' with the curried
2397 result type 'CInt -> IO ()', and return False, as they are not equal.
2398
2399
2400 ----------------------------------------------
2401 These chaps do the work; they are not exported
2402 ----------------------------------------------
2403 -}
2404
2405 legalFEArgTyCon :: TyCon -> Validity
2406 legalFEArgTyCon tc
2407 -- It's illegal to make foreign exports that take unboxed
2408 -- arguments. The RTS API currently can't invoke such things. --SDM 7/2000
2409 = boxedMarshalableTyCon tc
2410
2411 legalFIResultTyCon :: DynFlags -> TyCon -> Validity
2412 legalFIResultTyCon dflags tc
2413 | tc == unitTyCon = IsValid
2414 | otherwise = marshalableTyCon dflags tc
2415
2416 legalFEResultTyCon :: TyCon -> Validity
2417 legalFEResultTyCon tc
2418 | tc == unitTyCon = IsValid
2419 | otherwise = boxedMarshalableTyCon tc
2420
2421 legalOutgoingTyCon :: DynFlags -> Safety -> TyCon -> Validity
2422 -- Checks validity of types going from Haskell -> external world
2423 legalOutgoingTyCon dflags _ tc
2424 = marshalableTyCon dflags tc
2425
2426 legalFFITyCon :: TyCon -> Validity
2427 -- True for any TyCon that can possibly be an arg or result of an FFI call
2428 legalFFITyCon tc
2429 | isUnliftedTyCon tc = IsValid
2430 | tc == unitTyCon = IsValid
2431 | otherwise = boxedMarshalableTyCon tc
2432
2433 marshalableTyCon :: DynFlags -> TyCon -> Validity
2434 marshalableTyCon dflags tc
2435 | isUnliftedTyCon tc
2436 , not (isUnboxedTupleTyCon tc || isUnboxedSumTyCon tc)
2437 , not (null (tyConPrimRep tc)) -- Note [Marshalling void]
2438 = validIfUnliftedFFITypes dflags
2439 | otherwise
2440 = boxedMarshalableTyCon tc
2441
2442 boxedMarshalableTyCon :: TyCon -> Validity
2443 boxedMarshalableTyCon tc
2444 | getUnique tc `elem` [ intTyConKey, int8TyConKey, int16TyConKey
2445 , int32TyConKey, int64TyConKey
2446 , wordTyConKey, word8TyConKey, word16TyConKey
2447 , word32TyConKey, word64TyConKey
2448 , floatTyConKey, doubleTyConKey
2449 , ptrTyConKey, funPtrTyConKey
2450 , charTyConKey
2451 , stablePtrTyConKey
2452 , boolTyConKey
2453 ]
2454 = IsValid
2455
2456 | otherwise = NotValid empty
2457
2458 legalFIPrimArgTyCon :: DynFlags -> TyCon -> Validity
2459 -- Check args of 'foreign import prim', only allow simple unlifted types.
2460 -- Strictly speaking it is unnecessary to ban unboxed tuples and sums here since
2461 -- currently they're of the wrong kind to use in function args anyway.
2462 legalFIPrimArgTyCon dflags tc
2463 | isUnliftedTyCon tc
2464 , not (isUnboxedTupleTyCon tc || isUnboxedSumTyCon tc)
2465 = validIfUnliftedFFITypes dflags
2466 | otherwise
2467 = NotValid unlifted_only
2468
2469 legalFIPrimResultTyCon :: DynFlags -> TyCon -> Validity
2470 -- Check result type of 'foreign import prim'. Allow simple unlifted
2471 -- types and also unboxed tuple and sum result types.
2472 legalFIPrimResultTyCon dflags tc
2473 | isUnliftedTyCon tc
2474 , isUnboxedTupleTyCon tc || isUnboxedSumTyCon tc
2475 || not (null (tyConPrimRep tc)) -- Note [Marshalling void]
2476 = validIfUnliftedFFITypes dflags
2477
2478 | otherwise
2479 = NotValid unlifted_only
2480
2481 unlifted_only :: MsgDoc
2482 unlifted_only = text "foreign import prim only accepts simple unlifted types"
2483
2484 validIfUnliftedFFITypes :: DynFlags -> Validity
2485 validIfUnliftedFFITypes dflags
2486 | xopt LangExt.UnliftedFFITypes dflags = IsValid
2487 | otherwise = NotValid (text "To marshal unlifted types, use UnliftedFFITypes")
2488
2489 {-
2490 Note [Marshalling void]
2491 ~~~~~~~~~~~~~~~~~~~~~~~
2492 We don't treat State# (whose PrimRep is VoidRep) as marshalable.
2493 In turn that means you can't write
2494 foreign import foo :: Int -> State# RealWorld
2495
2496 Reason: the back end falls over with panic "primRepHint:VoidRep";
2497 and there is no compelling reason to permit it
2498 -}
2499
2500 {-
2501 ************************************************************************
2502 * *
2503 The "Paterson size" of a type
2504 * *
2505 ************************************************************************
2506 -}
2507
2508 {-
2509 Note [Paterson conditions on PredTypes]
2510 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2511 We are considering whether *class* constraints terminate
2512 (see Note [Paterson conditions]). Precisely, the Paterson conditions
2513 would have us check that "the constraint has fewer constructors and variables
2514 (taken together and counting repetitions) than the head.".
2515
2516 However, we can be a bit more refined by looking at which kind of constraint
2517 this actually is. There are two main tricks:
2518
2519 1. It seems like it should be OK not to count the tuple type constructor
2520 for a PredType like (Show a, Eq a) :: Constraint, since we don't
2521 count the "implicit" tuple in the ThetaType itself.
2522
2523 In fact, the Paterson test just checks *each component* of the top level
2524 ThetaType against the size bound, one at a time. By analogy, it should be
2525 OK to return the size of the *largest* tuple component as the size of the
2526 whole tuple.
2527
2528 2. Once we get into an implicit parameter or equality we
2529 can't get back to a class constraint, so it's safe
2530 to say "size 0". See Trac #4200.
2531
2532 NB: we don't want to detect PredTypes in sizeType (and then call
2533 sizePred on them), or we might get an infinite loop if that PredType
2534 is irreducible. See Trac #5581.
2535 -}
2536
2537 type TypeSize = IntWithInf
2538
2539 sizeType :: Type -> TypeSize
2540 -- Size of a type: the number of variables and constructors
2541 -- Ignore kinds altogether
2542 sizeType = go
2543 where
2544 go ty | Just exp_ty <- coreView ty = go exp_ty
2545 go (TyVarTy {}) = 1
2546 go (TyConApp tc tys)
2547 | isTypeFamilyTyCon tc = infinity -- Type-family applications can
2548 -- expand to any arbitrary size
2549 | otherwise = sizeTypes (filterOutInvisibleTypes tc tys) + 1
2550 go (LitTy {}) = 1
2551 go (FunTy arg res) = go arg + go res + 1
2552 go (AppTy fun arg) = go fun + go arg
2553 go (ForAllTy (TvBndr tv vis) ty)
2554 | isVisibleArgFlag vis = go (tyVarKind tv) + go ty + 1
2555 | otherwise = go ty + 1
2556 go (CastTy ty _) = go ty
2557 go (CoercionTy {}) = 0
2558
2559 sizeTypes :: [Type] -> TypeSize
2560 sizeTypes tys = sum (map sizeType tys)