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