Remove decideKindGeneralisationPlan
[ghc.git] / compiler / typecheck / TcMType.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5
6 Monadic type operations
7
8 This module contains monadic operations over types that contain
9 mutable type variables
10 -}
11
12 {-# LANGUAGE CPP, TupleSections, MultiWayIf #-}
13
14 module TcMType (
15 TcTyVar, TcKind, TcType, TcTauType, TcThetaType, TcTyVarSet,
16
17 --------------------------------
18 -- Creating new mutable type variables
19 newFlexiTyVar,
20 newFlexiTyVarTy, -- Kind -> TcM TcType
21 newFlexiTyVarTys, -- Int -> Kind -> TcM [TcType]
22 newOpenFlexiTyVarTy, newOpenTypeKind,
23 newMetaKindVar, newMetaKindVars, newMetaTyVarTyAtLevel,
24 cloneMetaTyVar,
25 newFmvTyVar, newFskTyVar,
26
27 readMetaTyVar, writeMetaTyVar,
28 newMetaDetails, isFilledMetaTyVar, isUnfilledMetaTyVar,
29
30 --------------------------------
31 -- Expected types
32 ExpType(..), ExpSigmaType, ExpRhoType,
33 mkCheckExpType,
34 newInferExpType, newInferExpTypeInst, newInferExpTypeNoInst,
35 readExpType, readExpType_maybe,
36 expTypeToType, checkingExpType_maybe, checkingExpType,
37 tauifyExpType, inferResultToType,
38
39 --------------------------------
40 -- Creating new evidence variables
41 newEvVar, newEvVars, newDict,
42 newWanted, newWanteds, cloneWanted, cloneWC,
43 emitWanted, emitWantedEq, emitWantedEvVar, emitWantedEvVars,
44 newTcEvBinds, newNoTcEvBinds, addTcEvBind,
45
46 newCoercionHole, fillCoercionHole, isFilledCoercionHole,
47 unpackCoercionHole, unpackCoercionHole_maybe,
48 checkCoercionHole,
49
50 --------------------------------
51 -- Instantiation
52 newMetaTyVars, newMetaTyVarX, newMetaTyVarsX,
53 newMetaSigTyVars, newMetaSigTyVarX,
54 newSigTyVar, newSkolemTyVar, newWildCardX,
55 tcInstType,
56 tcInstSkolTyVars,tcInstSkolTyVarsX,
57 tcInstSuperSkolTyVarsX,
58 tcSkolDFunType, tcSuperSkolTyVars,
59
60 instSkolTyCoVarsX, freshenTyVarBndrs, freshenCoVarBndrsX,
61
62 --------------------------------
63 -- Zonking and tidying
64 zonkTidyTcType, zonkTidyTcTypes, zonkTidyOrigin,
65 tidyEvVar, tidyCt, tidySkolemInfo,
66 skolemiseRuntimeUnk,
67 zonkTcTyVar, zonkTcTyVars,
68 zonkTcTyVarToTyVar, zonkSigTyVarPairs,
69 zonkTyCoVarsAndFV, zonkTcTypeAndFV,
70 zonkTyCoVarsAndFVList,
71 zonkTcTypeAndSplitDepVars, zonkTcTypesAndSplitDepVars,
72 zonkQuantifiedTyVar, defaultTyVar,
73 quantifyTyVars,
74 zonkTcTyCoVarBndr, zonkTcTyVarBinder,
75 zonkTcType, zonkTcTypes, zonkCo,
76 zonkTyCoVarKind, zonkTcTypeMapper,
77
78 zonkEvVar, zonkWC, zonkSimples,
79 zonkId, zonkCoVar,
80 zonkCt, zonkSkolemInfo,
81
82 tcGetGlobalTyCoVars,
83
84 ------------------------------
85 -- Levity polymorphism
86 ensureNotLevPoly, checkForLevPoly, checkForLevPolyX, formatLevPolyErr
87 ) where
88
89 #include "HsVersions.h"
90
91 -- friends:
92 import GhcPrelude
93
94 import TyCoRep
95 import TcType
96 import Type
97 import Coercion
98 import Class
99 import Var
100
101 -- others:
102 import TcRnMonad -- TcType, amongst others
103 import TcEvidence
104 import Id
105 import Name
106 import VarSet
107 import TysWiredIn
108 import TysPrim
109 import VarEnv
110 import NameEnv
111 import PrelNames
112 import Util
113 import Outputable
114 import FastString
115 import SrcLoc
116 import Bag
117 import Pair
118 import UniqSet
119 import qualified GHC.LanguageExtensions as LangExt
120
121 import Control.Monad
122 import Maybes
123 import Data.List ( mapAccumL )
124 import Control.Arrow ( second )
125
126 {-
127 ************************************************************************
128 * *
129 Kind variables
130 * *
131 ************************************************************************
132 -}
133
134 mkKindName :: Unique -> Name
135 mkKindName unique = mkSystemName unique kind_var_occ
136
137 kind_var_occ :: OccName -- Just one for all MetaKindVars
138 -- They may be jiggled by tidying
139 kind_var_occ = mkOccName tvName "k"
140
141 newMetaKindVar :: TcM TcKind
142 newMetaKindVar = do { uniq <- newUnique
143 ; details <- newMetaDetails TauTv
144 ; let kv = mkTcTyVar (mkKindName uniq) liftedTypeKind details
145 ; traceTc "newMetaKindVar" (ppr kv)
146 ; return (mkTyVarTy kv) }
147
148 newMetaKindVars :: Int -> TcM [TcKind]
149 newMetaKindVars n = mapM (\ _ -> newMetaKindVar) (nOfThem n ())
150
151 {-
152 ************************************************************************
153 * *
154 Evidence variables; range over constraints we can abstract over
155 * *
156 ************************************************************************
157 -}
158
159 newEvVars :: TcThetaType -> TcM [EvVar]
160 newEvVars theta = mapM newEvVar theta
161
162 --------------
163
164 newEvVar :: TcPredType -> TcRnIf gbl lcl EvVar
165 -- Creates new *rigid* variables for predicates
166 newEvVar ty = do { name <- newSysName (predTypeOccName ty)
167 ; return (mkLocalIdOrCoVar name ty) }
168
169 newWanted :: CtOrigin -> Maybe TypeOrKind -> PredType -> TcM CtEvidence
170 -- Deals with both equality and non-equality predicates
171 newWanted orig t_or_k pty
172 = do loc <- getCtLocM orig t_or_k
173 d <- if isEqPred pty then HoleDest <$> newCoercionHole pty
174 else EvVarDest <$> newEvVar pty
175 return $ CtWanted { ctev_dest = d
176 , ctev_pred = pty
177 , ctev_nosh = WDeriv
178 , ctev_loc = loc }
179
180 newWanteds :: CtOrigin -> ThetaType -> TcM [CtEvidence]
181 newWanteds orig = mapM (newWanted orig Nothing)
182
183 ----------------------------------------------
184 -- Cloning constraints
185 ----------------------------------------------
186
187 cloneWanted :: Ct -> TcM Ct
188 cloneWanted ct
189 | ev@(CtWanted { ctev_dest = HoleDest {}, ctev_pred = pty }) <- ctEvidence ct
190 = do { co_hole <- newCoercionHole pty
191 ; return (mkNonCanonical (ev { ctev_dest = HoleDest co_hole })) }
192 | otherwise
193 = return ct
194
195 cloneWC :: WantedConstraints -> TcM WantedConstraints
196 -- Clone all the evidence bindings in
197 -- a) the ic_bind field of any implications
198 -- b) the CoercionHoles of any wanted constraints
199 -- so that solving the WantedConstraints will not have any visible side
200 -- effect, /except/ from causing unifications
201 cloneWC wc@(WC { wc_simple = simples, wc_impl = implics })
202 = do { simples' <- mapBagM cloneWanted simples
203 ; implics' <- mapBagM cloneImplication implics
204 ; return (wc { wc_simple = simples', wc_impl = implics' }) }
205
206 cloneImplication :: Implication -> TcM Implication
207 cloneImplication implic@(Implic { ic_binds = binds, ic_wanted = inner_wanted })
208 = do { binds' <- cloneEvBindsVar binds
209 ; inner_wanted' <- cloneWC inner_wanted
210 ; return (implic { ic_binds = binds', ic_wanted = inner_wanted' }) }
211
212 ----------------------------------------------
213 -- Emitting constraints
214 ----------------------------------------------
215
216 -- | Emits a new Wanted. Deals with both equalities and non-equalities.
217 emitWanted :: CtOrigin -> TcPredType -> TcM EvTerm
218 emitWanted origin pty
219 = do { ev <- newWanted origin Nothing pty
220 ; emitSimple $ mkNonCanonical ev
221 ; return $ ctEvTerm ev }
222
223 -- | Emits a new equality constraint
224 emitWantedEq :: CtOrigin -> TypeOrKind -> Role -> TcType -> TcType -> TcM Coercion
225 emitWantedEq origin t_or_k role ty1 ty2
226 = do { hole <- newCoercionHole pty
227 ; loc <- getCtLocM origin (Just t_or_k)
228 ; emitSimple $ mkNonCanonical $
229 CtWanted { ctev_pred = pty, ctev_dest = HoleDest hole
230 , ctev_nosh = WDeriv, ctev_loc = loc }
231 ; return (HoleCo hole) }
232 where
233 pty = mkPrimEqPredRole role ty1 ty2
234
235 -- | Creates a new EvVar and immediately emits it as a Wanted.
236 -- No equality predicates here.
237 emitWantedEvVar :: CtOrigin -> TcPredType -> TcM EvVar
238 emitWantedEvVar origin ty
239 = do { new_cv <- newEvVar ty
240 ; loc <- getCtLocM origin Nothing
241 ; let ctev = CtWanted { ctev_dest = EvVarDest new_cv
242 , ctev_pred = ty
243 , ctev_nosh = WDeriv
244 , ctev_loc = loc }
245 ; emitSimple $ mkNonCanonical ctev
246 ; return new_cv }
247
248 emitWantedEvVars :: CtOrigin -> [TcPredType] -> TcM [EvVar]
249 emitWantedEvVars orig = mapM (emitWantedEvVar orig)
250
251 newDict :: Class -> [TcType] -> TcM DictId
252 newDict cls tys
253 = do { name <- newSysName (mkDictOcc (getOccName cls))
254 ; return (mkLocalId name (mkClassPred cls tys)) }
255
256 predTypeOccName :: PredType -> OccName
257 predTypeOccName ty = case classifyPredType ty of
258 ClassPred cls _ -> mkDictOcc (getOccName cls)
259 EqPred {} -> mkVarOccFS (fsLit "co")
260 IrredPred {} -> mkVarOccFS (fsLit "irred")
261 ForAllPred {} -> mkVarOccFS (fsLit "df")
262
263 {-
264 ************************************************************************
265 * *
266 Coercion holes
267 * *
268 ************************************************************************
269 -}
270
271 newCoercionHole :: TcPredType -> TcM CoercionHole
272 newCoercionHole pred_ty
273 = do { co_var <- newEvVar pred_ty
274 ; traceTc "New coercion hole:" (ppr co_var)
275 ; ref <- newMutVar Nothing
276 ; return $ CoercionHole { ch_co_var = co_var, ch_ref = ref } }
277
278 -- | Put a value in a coercion hole
279 fillCoercionHole :: CoercionHole -> Coercion -> TcM ()
280 fillCoercionHole (CoercionHole { ch_ref = ref, ch_co_var = cv }) co
281 = do {
282 #if defined(DEBUG)
283 ; cts <- readTcRef ref
284 ; whenIsJust cts $ \old_co ->
285 pprPanic "Filling a filled coercion hole" (ppr cv $$ ppr co $$ ppr old_co)
286 #endif
287 ; traceTc "Filling coercion hole" (ppr cv <+> text ":=" <+> ppr co)
288 ; writeTcRef ref (Just co) }
289
290 -- | Is a coercion hole filled in?
291 isFilledCoercionHole :: CoercionHole -> TcM Bool
292 isFilledCoercionHole (CoercionHole { ch_ref = ref }) = isJust <$> readTcRef ref
293
294 -- | Retrieve the contents of a coercion hole. Panics if the hole
295 -- is unfilled
296 unpackCoercionHole :: CoercionHole -> TcM Coercion
297 unpackCoercionHole hole
298 = do { contents <- unpackCoercionHole_maybe hole
299 ; case contents of
300 Just co -> return co
301 Nothing -> pprPanic "Unfilled coercion hole" (ppr hole) }
302
303 -- | Retrieve the contents of a coercion hole, if it is filled
304 unpackCoercionHole_maybe :: CoercionHole -> TcM (Maybe Coercion)
305 unpackCoercionHole_maybe (CoercionHole { ch_ref = ref }) = readTcRef ref
306
307 -- | Check that a coercion is appropriate for filling a hole. (The hole
308 -- itself is needed only for printing.
309 -- Always returns the checked coercion, but this return value is necessary
310 -- so that the input coercion is forced only when the output is forced.
311 checkCoercionHole :: CoVar -> Coercion -> TcM Coercion
312 checkCoercionHole cv co
313 | debugIsOn
314 = do { cv_ty <- zonkTcType (varType cv)
315 -- co is already zonked, but cv might not be
316 ; return $
317 ASSERT2( ok cv_ty
318 , (text "Bad coercion hole" <+>
319 ppr cv <> colon <+> vcat [ ppr t1, ppr t2, ppr role
320 , ppr cv_ty ]) )
321 co }
322 | otherwise
323 = return co
324
325 where
326 (Pair t1 t2, role) = coercionKindRole co
327 ok cv_ty | EqPred cv_rel cv_t1 cv_t2 <- classifyPredType cv_ty
328 = t1 `eqType` cv_t1
329 && t2 `eqType` cv_t2
330 && role == eqRelRole cv_rel
331 | otherwise
332 = False
333
334 {-
335 ************************************************************************
336 *
337 Expected types
338 *
339 ************************************************************************
340
341 Note [ExpType]
342 ~~~~~~~~~~~~~~
343
344 An ExpType is used as the "expected type" when type-checking an expression.
345 An ExpType can hold a "hole" that can be filled in by the type-checker.
346 This allows us to have one tcExpr that works in both checking mode and
347 synthesis mode (that is, bidirectional type-checking). Previously, this
348 was achieved by using ordinary unification variables, but we don't need
349 or want that generality. (For example, #11397 was caused by doing the
350 wrong thing with unification variables.) Instead, we observe that these
351 holes should
352
353 1. never be nested
354 2. never appear as the type of a variable
355 3. be used linearly (never be duplicated)
356
357 By defining ExpType, separately from Type, we can achieve goals 1 and 2
358 statically.
359
360 See also [wiki:Typechecking]
361
362 Note [TcLevel of ExpType]
363 ~~~~~~~~~~~~~~~~~~~~~~~~~
364 Consider
365
366 data G a where
367 MkG :: G Bool
368
369 foo MkG = True
370
371 This is a classic untouchable-variable / ambiguous GADT return type
372 scenario. But, with ExpTypes, we'll be inferring the type of the RHS.
373 And, because there is only one branch of the case, we won't trigger
374 Note [Case branches must never infer a non-tau type] of TcMatches.
375 We thus must track a TcLevel in an Inferring ExpType. If we try to
376 fill the ExpType and find that the TcLevels don't work out, we
377 fill the ExpType with a tau-tv at the low TcLevel, hopefully to
378 be worked out later by some means. This is triggered in
379 test gadt/gadt-escape1.
380
381 -}
382
383 -- actual data definition is in TcType
384
385 -- | Make an 'ExpType' suitable for inferring a type of kind * or #.
386 newInferExpTypeNoInst :: TcM ExpSigmaType
387 newInferExpTypeNoInst = newInferExpType False
388
389 newInferExpTypeInst :: TcM ExpRhoType
390 newInferExpTypeInst = newInferExpType True
391
392 newInferExpType :: Bool -> TcM ExpType
393 newInferExpType inst
394 = do { u <- newUnique
395 ; tclvl <- getTcLevel
396 ; traceTc "newOpenInferExpType" (ppr u <+> ppr inst <+> ppr tclvl)
397 ; ref <- newMutVar Nothing
398 ; return (Infer (IR { ir_uniq = u, ir_lvl = tclvl
399 , ir_ref = ref, ir_inst = inst })) }
400
401 -- | Extract a type out of an ExpType, if one exists. But one should always
402 -- exist. Unless you're quite sure you know what you're doing.
403 readExpType_maybe :: ExpType -> TcM (Maybe TcType)
404 readExpType_maybe (Check ty) = return (Just ty)
405 readExpType_maybe (Infer (IR { ir_ref = ref})) = readMutVar ref
406
407 -- | Extract a type out of an ExpType. Otherwise, panics.
408 readExpType :: ExpType -> TcM TcType
409 readExpType exp_ty
410 = do { mb_ty <- readExpType_maybe exp_ty
411 ; case mb_ty of
412 Just ty -> return ty
413 Nothing -> pprPanic "Unknown expected type" (ppr exp_ty) }
414
415 -- | Returns the expected type when in checking mode.
416 checkingExpType_maybe :: ExpType -> Maybe TcType
417 checkingExpType_maybe (Check ty) = Just ty
418 checkingExpType_maybe _ = Nothing
419
420 -- | Returns the expected type when in checking mode. Panics if in inference
421 -- mode.
422 checkingExpType :: String -> ExpType -> TcType
423 checkingExpType _ (Check ty) = ty
424 checkingExpType err et = pprPanic "checkingExpType" (text err $$ ppr et)
425
426 tauifyExpType :: ExpType -> TcM ExpType
427 -- ^ Turn a (Infer hole) type into a (Check alpha),
428 -- where alpha is a fresh unification variable
429 tauifyExpType (Check ty) = return (Check ty) -- No-op for (Check ty)
430 tauifyExpType (Infer inf_res) = do { ty <- inferResultToType inf_res
431 ; return (Check ty) }
432
433 -- | Extracts the expected type if there is one, or generates a new
434 -- TauTv if there isn't.
435 expTypeToType :: ExpType -> TcM TcType
436 expTypeToType (Check ty) = return ty
437 expTypeToType (Infer inf_res) = inferResultToType inf_res
438
439 inferResultToType :: InferResult -> TcM Type
440 inferResultToType (IR { ir_uniq = u, ir_lvl = tc_lvl
441 , ir_ref = ref })
442 = do { rr <- newMetaTyVarTyAtLevel tc_lvl runtimeRepTy
443 ; tau <- newMetaTyVarTyAtLevel tc_lvl (tYPE rr)
444 -- See Note [TcLevel of ExpType]
445 ; writeMutVar ref (Just tau)
446 ; traceTc "Forcing ExpType to be monomorphic:"
447 (ppr u <+> text ":=" <+> ppr tau)
448 ; return tau }
449
450
451 {- *********************************************************************
452 * *
453 SkolemTvs (immutable)
454 * *
455 ********************************************************************* -}
456
457 tcInstType :: ([TyVar] -> TcM (TCvSubst, [TcTyVar]))
458 -- ^ How to instantiate the type variables
459 -> Id -- ^ Type to instantiate
460 -> TcM ([(Name, TcTyVar)], TcThetaType, TcType) -- ^ Result
461 -- (type vars, preds (incl equalities), rho)
462 tcInstType inst_tyvars id
463 = case tcSplitForAllTys (idType id) of
464 ([], rho) -> let -- There may be overloading despite no type variables;
465 -- (?x :: Int) => Int -> Int
466 (theta, tau) = tcSplitPhiTy rho
467 in
468 return ([], theta, tau)
469
470 (tyvars, rho) -> do { (subst, tyvars') <- inst_tyvars tyvars
471 ; let (theta, tau) = tcSplitPhiTy (substTyAddInScope subst rho)
472 tv_prs = map tyVarName tyvars `zip` tyvars'
473 ; return (tv_prs, theta, tau) }
474
475 tcSkolDFunType :: DFunId -> TcM ([TcTyVar], TcThetaType, TcType)
476 -- Instantiate a type signature with skolem constants.
477 -- We could give them fresh names, but no need to do so
478 tcSkolDFunType dfun
479 = do { (tv_prs, theta, tau) <- tcInstType tcInstSuperSkolTyVars dfun
480 ; return (map snd tv_prs, theta, tau) }
481
482 tcSuperSkolTyVars :: [TyVar] -> (TCvSubst, [TcTyVar])
483 -- Make skolem constants, but do *not* give them new names, as above
484 -- Moreover, make them "super skolems"; see comments with superSkolemTv
485 -- see Note [Kind substitution when instantiating]
486 -- Precondition: tyvars should be ordered by scoping
487 tcSuperSkolTyVars = mapAccumL tcSuperSkolTyVar emptyTCvSubst
488
489 tcSuperSkolTyVar :: TCvSubst -> TyVar -> (TCvSubst, TcTyVar)
490 tcSuperSkolTyVar subst tv
491 = (extendTvSubstWithClone subst tv new_tv, new_tv)
492 where
493 kind = substTyUnchecked subst (tyVarKind tv)
494 new_tv = mkTcTyVar (tyVarName tv) kind superSkolemTv
495
496 -- | Given a list of @['TyVar']@, skolemize the type variables,
497 -- returning a substitution mapping the original tyvars to the
498 -- skolems, and the list of newly bound skolems. See also
499 -- tcInstSkolTyVars' for a precondition. The resulting
500 -- skolems are non-overlappable; see Note [Overlap and deriving]
501 -- for an example where this matters.
502 tcInstSkolTyVars :: [TyVar] -> TcM (TCvSubst, [TcTyVar])
503 tcInstSkolTyVars = tcInstSkolTyVarsX emptyTCvSubst
504
505 tcInstSkolTyVarsX :: TCvSubst -> [TyVar] -> TcM (TCvSubst, [TcTyVar])
506 tcInstSkolTyVarsX = tcInstSkolTyVars' False
507
508 tcInstSuperSkolTyVars :: [TyVar] -> TcM (TCvSubst, [TcTyVar])
509 tcInstSuperSkolTyVars = tcInstSuperSkolTyVarsX emptyTCvSubst
510
511 tcInstSuperSkolTyVarsX :: TCvSubst -> [TyVar] -> TcM (TCvSubst, [TcTyVar])
512 tcInstSuperSkolTyVarsX subst = tcInstSkolTyVars' True subst
513
514 tcInstSkolTyVars' :: Bool -> TCvSubst -> [TyVar] -> TcM (TCvSubst, [TcTyVar])
515 -- Precondition: tyvars should be ordered (kind vars first)
516 -- see Note [Kind substitution when instantiating]
517 -- Get the location from the monad; this is a complete freshening operation
518 tcInstSkolTyVars' overlappable subst tvs
519 = do { loc <- getSrcSpanM
520 ; lvl <- getTcLevel
521 ; instSkolTyCoVarsX (mkTcSkolTyVar lvl loc overlappable) subst tvs }
522
523 mkTcSkolTyVar :: TcLevel -> SrcSpan -> Bool -> TcTyCoVarMaker gbl lcl
524 -- Allocates skolems whose level is ONE GREATER THAN the passed-in tc_lvl
525 -- See Note [Skolem level allocation]
526 mkTcSkolTyVar tc_lvl loc overlappable old_name kind
527 = do { uniq <- newUnique
528 ; let name = mkInternalName uniq (getOccName old_name) loc
529 ; return (mkTcTyVar name kind details) }
530 where
531 details = SkolemTv (pushTcLevel tc_lvl) overlappable
532 -- pushTcLevel: see Note [Skolem level allocation]
533
534 {- Note [Skolem level allocation]
535 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
536 We generally allocate skolems /before/ calling pushLevelAndCaptureConstraints.
537 So we want their level to the level of the soon-to-be-created implication,
538 which has a level one higher than the current level. Hence the pushTcLevel.
539 It feels like a slight hack. Applies also to vanillaSkolemTv.
540
541 -}
542
543 ------------------
544 freshenTyVarBndrs :: [TyVar] -> TcRnIf gbl lcl (TCvSubst, [TyVar])
545 -- ^ Give fresh uniques to a bunch of TyVars, but they stay
546 -- as TyVars, rather than becoming TcTyVars
547 -- Used in FamInst.newFamInst, and Inst.newClsInst
548 freshenTyVarBndrs = instSkolTyCoVars mk_tv
549 where
550 mk_tv old_name kind
551 = do { uniq <- newUnique
552 ; return (mkTyVar (setNameUnique old_name uniq) kind) }
553
554 freshenCoVarBndrsX :: TCvSubst -> [CoVar] -> TcRnIf gbl lcl (TCvSubst, [CoVar])
555 -- ^ Give fresh uniques to a bunch of CoVars
556 -- Used in FamInst.newFamInst
557 freshenCoVarBndrsX subst = instSkolTyCoVarsX mk_cv subst
558 where
559 mk_cv old_name kind
560 = do { uniq <- newUnique
561 ; return (mkCoVar (setNameUnique old_name uniq) kind) }
562
563 ------------------
564 type TcTyCoVarMaker gbl lcl = Name -> Kind -> TcRnIf gbl lcl TyCoVar
565 -- The TcTyCoVarMaker should make a fresh Name, based on the old one
566 -- Freshness is critical. See Note [Skolems in zonkSyntaxExpr] in TcHsSyn
567
568 instSkolTyCoVars :: TcTyCoVarMaker gbl lcl -> [TyVar] -> TcRnIf gbl lcl (TCvSubst, [TyCoVar])
569 instSkolTyCoVars mk_tcv = instSkolTyCoVarsX mk_tcv emptyTCvSubst
570
571 instSkolTyCoVarsX :: TcTyCoVarMaker gbl lcl
572 -> TCvSubst -> [TyCoVar] -> TcRnIf gbl lcl (TCvSubst, [TyCoVar])
573 instSkolTyCoVarsX mk_tcv = mapAccumLM (instSkolTyCoVarX mk_tcv)
574
575 instSkolTyCoVarX :: TcTyCoVarMaker gbl lcl
576 -> TCvSubst -> TyCoVar -> TcRnIf gbl lcl (TCvSubst, TyCoVar)
577 instSkolTyCoVarX mk_tcv subst tycovar
578 = do { new_tcv <- mk_tcv old_name kind
579 ; let subst1 | isTyVar new_tcv
580 = extendTvSubstWithClone subst tycovar new_tcv
581 | otherwise
582 = extendCvSubstWithClone subst tycovar new_tcv
583 ; return (subst1, new_tcv) }
584 where
585 old_name = tyVarName tycovar
586 kind = substTyUnchecked subst (tyVarKind tycovar)
587
588 newFskTyVar :: TcType -> TcM TcTyVar
589 newFskTyVar fam_ty
590 = do { uniq <- newUnique
591 ; ref <- newMutVar Flexi
592 ; tclvl <- getTcLevel
593 ; let details = MetaTv { mtv_info = FlatSkolTv
594 , mtv_ref = ref
595 , mtv_tclvl = tclvl }
596 name = mkMetaTyVarName uniq (fsLit "fsk")
597 ; return (mkTcTyVar name (typeKind fam_ty) details) }
598
599 {-
600 Note [Kind substitution when instantiating]
601 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
602 When we instantiate a bunch of kind and type variables, first we
603 expect them to be topologically sorted.
604 Then we have to instantiate the kind variables, build a substitution
605 from old variables to the new variables, then instantiate the type
606 variables substituting the original kind.
607
608 Exemple: If we want to instantiate
609 [(k1 :: *), (k2 :: *), (a :: k1 -> k2), (b :: k1)]
610 we want
611 [(?k1 :: *), (?k2 :: *), (?a :: ?k1 -> ?k2), (?b :: ?k1)]
612 instead of the buggous
613 [(?k1 :: *), (?k2 :: *), (?a :: k1 -> k2), (?b :: k1)]
614
615
616 ************************************************************************
617 * *
618 MetaTvs (meta type variables; mutable)
619 * *
620 ************************************************************************
621 -}
622
623 -- a SigTv can unify with type *variables* only, including other SigTvs
624 -- and skolems. Sometimes, they can unify with type variables that the
625 -- user would rather keep distinct; see #11203 for an example.
626 -- So, any client of this
627 -- function needs to either allow the SigTvs to unify with each other
628 -- (say, for pattern-bound scoped type variables), or check that they
629 -- don't (say, with a call to findDubSigTvs).
630 newSigTyVar :: Name -> Kind -> TcM TcTyVar
631 newSigTyVar name kind
632 = do { details <- newMetaDetails SigTv
633 ; let tyvar = mkTcTyVar name kind details
634 ; traceTc "newSigTyVar" (ppr tyvar)
635 ; return tyvar }
636
637 -- makes a new skolem tv
638 newSkolemTyVar :: Name -> Kind -> TcM TcTyVar
639 newSkolemTyVar name kind = do { lvl <- getTcLevel
640 ; return (mkTcTyVar name kind (SkolemTv lvl False)) }
641
642 newFmvTyVar :: TcType -> TcM TcTyVar
643 -- Very like newMetaTyVar, except sets mtv_tclvl to one less
644 -- so that the fmv is untouchable.
645 newFmvTyVar fam_ty
646 = do { uniq <- newUnique
647 ; ref <- newMutVar Flexi
648 ; tclvl <- getTcLevel
649 ; let details = MetaTv { mtv_info = FlatMetaTv
650 , mtv_ref = ref
651 , mtv_tclvl = tclvl }
652 name = mkMetaTyVarName uniq (fsLit "s")
653 ; return (mkTcTyVar name (typeKind fam_ty) details) }
654
655 newMetaDetails :: MetaInfo -> TcM TcTyVarDetails
656 newMetaDetails info
657 = do { ref <- newMutVar Flexi
658 ; tclvl <- getTcLevel
659 ; return (MetaTv { mtv_info = info
660 , mtv_ref = ref
661 , mtv_tclvl = tclvl }) }
662
663 cloneMetaTyVar :: TcTyVar -> TcM TcTyVar
664 cloneMetaTyVar tv
665 = ASSERT( isTcTyVar tv )
666 do { uniq <- newUnique
667 ; ref <- newMutVar Flexi
668 ; let name' = setNameUnique (tyVarName tv) uniq
669 details' = case tcTyVarDetails tv of
670 details@(MetaTv {}) -> details { mtv_ref = ref }
671 _ -> pprPanic "cloneMetaTyVar" (ppr tv)
672 tyvar = mkTcTyVar name' (tyVarKind tv) details'
673 ; traceTc "cloneMetaTyVar" (ppr tyvar)
674 ; return tyvar }
675
676 -- Works for both type and kind variables
677 readMetaTyVar :: TyVar -> TcM MetaDetails
678 readMetaTyVar tyvar = ASSERT2( isMetaTyVar tyvar, ppr tyvar )
679 readMutVar (metaTyVarRef tyvar)
680
681 isFilledMetaTyVar :: TyVar -> TcM Bool
682 -- True of a filled-in (Indirect) meta type variable
683 isFilledMetaTyVar tv
684 | MetaTv { mtv_ref = ref } <- tcTyVarDetails tv
685 = do { details <- readMutVar ref
686 ; return (isIndirect details) }
687 | otherwise = return False
688
689 isUnfilledMetaTyVar :: TyVar -> TcM Bool
690 -- True of a un-filled-in (Flexi) meta type variable
691 isUnfilledMetaTyVar tv
692 | MetaTv { mtv_ref = ref } <- tcTyVarDetails tv
693 = do { details <- readMutVar ref
694 ; return (isFlexi details) }
695 | otherwise = return False
696
697 --------------------
698 -- Works with both type and kind variables
699 writeMetaTyVar :: TcTyVar -> TcType -> TcM ()
700 -- Write into a currently-empty MetaTyVar
701
702 writeMetaTyVar tyvar ty
703 | not debugIsOn
704 = writeMetaTyVarRef tyvar (metaTyVarRef tyvar) ty
705
706 -- Everything from here on only happens if DEBUG is on
707 | not (isTcTyVar tyvar)
708 = WARN( True, text "Writing to non-tc tyvar" <+> ppr tyvar )
709 return ()
710
711 | MetaTv { mtv_ref = ref } <- tcTyVarDetails tyvar
712 = writeMetaTyVarRef tyvar ref ty
713
714 | otherwise
715 = WARN( True, text "Writing to non-meta tyvar" <+> ppr tyvar )
716 return ()
717
718 --------------------
719 writeMetaTyVarRef :: TcTyVar -> TcRef MetaDetails -> TcType -> TcM ()
720 -- Here the tyvar is for error checking only;
721 -- the ref cell must be for the same tyvar
722 writeMetaTyVarRef tyvar ref ty
723 | not debugIsOn
724 = do { traceTc "writeMetaTyVar" (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)
725 <+> text ":=" <+> ppr ty)
726 ; writeTcRef ref (Indirect ty) }
727
728 -- Everything from here on only happens if DEBUG is on
729 | otherwise
730 = do { meta_details <- readMutVar ref;
731 -- Zonk kinds to allow the error check to work
732 ; zonked_tv_kind <- zonkTcType tv_kind
733 ; zonked_ty <- zonkTcType ty
734 ; let zonked_ty_kind = typeKind zonked_ty -- need to zonk even before typeKind;
735 -- otherwise, we can panic in piResultTy
736 kind_check_ok = tcIsConstraintKind zonked_tv_kind
737 || tcEqKind zonked_ty_kind zonked_tv_kind
738 -- Hack alert! tcIsConstraintKind: see TcHsType
739 -- Note [Extra-constraint holes in partial type signatures]
740
741 kind_msg = hang (text "Ill-kinded update to meta tyvar")
742 2 ( ppr tyvar <+> text "::" <+> (ppr tv_kind $$ ppr zonked_tv_kind)
743 <+> text ":="
744 <+> ppr ty <+> text "::" <+> (ppr zonked_ty_kind) )
745
746 ; traceTc "writeMetaTyVar" (ppr tyvar <+> text ":=" <+> ppr ty)
747
748 -- Check for double updates
749 ; MASSERT2( isFlexi meta_details, double_upd_msg meta_details )
750
751 -- Check for level OK
752 -- See Note [Level check when unifying]
753 ; MASSERT2( level_check_ok, level_check_msg )
754
755 -- Check Kinds ok
756 ; MASSERT2( kind_check_ok, kind_msg )
757
758 -- Do the write
759 ; writeMutVar ref (Indirect ty) }
760 where
761 tv_kind = tyVarKind tyvar
762
763 tv_lvl = tcTyVarLevel tyvar
764 ty_lvl = tcTypeLevel ty
765
766 level_check_ok = not (ty_lvl `strictlyDeeperThan` tv_lvl)
767 level_check_msg = ppr ty_lvl $$ ppr tv_lvl $$ ppr tyvar $$ ppr ty
768
769 double_upd_msg details = hang (text "Double update of meta tyvar")
770 2 (ppr tyvar $$ ppr details)
771
772
773 {- Note [Level check when unifying]
774 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
775 When unifying
776 alpha:lvl := ty
777 we expect that the TcLevel of 'ty' will be <= lvl.
778 However, during unflatting we do
779 fuv:l := ty:(l+1)
780 which is usually wrong; hence the check isFmmvTyVar in level_check_ok.
781 See Note [TcLevel assignment] in TcType.
782 -}
783
784 {-
785 % Generating fresh variables for pattern match check
786 -}
787
788
789 {-
790 ************************************************************************
791 * *
792 MetaTvs: TauTvs
793 * *
794 ************************************************************************
795
796 Note [Never need to instantiate coercion variables]
797 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
798 With coercion variables sloshing around in types, it might seem that we
799 sometimes need to instantiate coercion variables. This would be problematic,
800 because coercion variables inhabit unboxed equality (~#), and the constraint
801 solver thinks in terms only of boxed equality (~). The solution is that
802 we never need to instantiate coercion variables in the first place.
803
804 The tyvars that we need to instantiate come from the types of functions,
805 data constructors, and patterns. These will never be quantified over
806 coercion variables, except for the special case of the promoted Eq#. But,
807 that can't ever appear in user code, so we're safe!
808 -}
809
810 mkMetaTyVarName :: Unique -> FastString -> Name
811 -- Makes a /System/ Name, which is eagerly eliminated by
812 -- the unifier; see TcUnify.nicer_to_update_tv1, and
813 -- TcCanonical.canEqTyVarTyVar (nicer_to_update_tv2)
814 mkMetaTyVarName uniq str = mkSystemName uniq (mkTyVarOccFS str)
815
816 newAnonMetaTyVar :: MetaInfo -> Kind -> TcM TcTyVar
817 -- Make a new meta tyvar out of thin air
818 newAnonMetaTyVar meta_info kind
819 = do { uniq <- newUnique
820 ; let name = mkMetaTyVarName uniq s
821 s = case meta_info of
822 TauTv -> fsLit "t"
823 FlatMetaTv -> fsLit "fmv"
824 FlatSkolTv -> fsLit "fsk"
825 SigTv -> fsLit "a"
826 ; details <- newMetaDetails meta_info
827 ; let tyvar = mkTcTyVar name kind details
828 ; traceTc "newAnonMetaTyVar" (ppr tyvar)
829 ; return tyvar }
830
831 cloneAnonMetaTyVar :: MetaInfo -> TyVar -> TcKind -> TcM TcTyVar
832 -- Same as newAnonMetaTyVar, but use a supplied TyVar as the source of the print-name
833 cloneAnonMetaTyVar info tv kind
834 = do { uniq <- newUnique
835 ; details <- newMetaDetails info
836 ; let name = mkSystemName uniq (getOccName tv)
837 -- See Note [Name of an instantiated type variable]
838 tyvar = mkTcTyVar name kind details
839 ; traceTc "cloneAnonMetaTyVar" (ppr tyvar)
840 ; return tyvar }
841
842 {- Note [Name of an instantiated type variable]
843 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
844 At the moment we give a unification variable a System Name, which
845 influences the way it is tidied; see TypeRep.tidyTyVarBndr.
846 -}
847
848 newFlexiTyVar :: Kind -> TcM TcTyVar
849 newFlexiTyVar kind = newAnonMetaTyVar TauTv kind
850
851 newFlexiTyVarTy :: Kind -> TcM TcType
852 newFlexiTyVarTy kind = do
853 tc_tyvar <- newFlexiTyVar kind
854 return (mkTyVarTy tc_tyvar)
855
856 newFlexiTyVarTys :: Int -> Kind -> TcM [TcType]
857 newFlexiTyVarTys n kind = mapM newFlexiTyVarTy (nOfThem n kind)
858
859 newOpenTypeKind :: TcM TcKind
860 newOpenTypeKind
861 = do { rr <- newFlexiTyVarTy runtimeRepTy
862 ; return (tYPE rr) }
863
864 -- | Create a tyvar that can be a lifted or unlifted type.
865 -- Returns alpha :: TYPE kappa, where both alpha and kappa are fresh
866 newOpenFlexiTyVarTy :: TcM TcType
867 newOpenFlexiTyVarTy
868 = do { kind <- newOpenTypeKind
869 ; newFlexiTyVarTy kind }
870
871 newMetaSigTyVars :: [TyVar] -> TcM (TCvSubst, [TcTyVar])
872 newMetaSigTyVars = mapAccumLM newMetaSigTyVarX emptyTCvSubst
873
874 newMetaTyVars :: [TyVar] -> TcM (TCvSubst, [TcTyVar])
875 -- Instantiate with META type variables
876 -- Note that this works for a sequence of kind, type, and coercion variables
877 -- variables. Eg [ (k:*), (a:k->k) ]
878 -- Gives [ (k7:*), (a8:k7->k7) ]
879 newMetaTyVars = mapAccumLM newMetaTyVarX emptyTCvSubst
880 -- emptyTCvSubst has an empty in-scope set, but that's fine here
881 -- Since the tyvars are freshly made, they cannot possibly be
882 -- captured by any existing for-alls.
883
884 newMetaTyVarX :: TCvSubst -> TyVar -> TcM (TCvSubst, TcTyVar)
885 -- Make a new unification variable tyvar whose Name and Kind come from
886 -- an existing TyVar. We substitute kind variables in the kind.
887 newMetaTyVarX subst tyvar = new_meta_tv_x TauTv subst tyvar
888
889 newMetaTyVarsX :: TCvSubst -> [TyVar] -> TcM (TCvSubst, [TcTyVar])
890 -- Just like newMetaTyVars, but start with an existing substitution.
891 newMetaTyVarsX subst = mapAccumLM newMetaTyVarX subst
892
893 newMetaSigTyVarX :: TCvSubst -> TyVar -> TcM (TCvSubst, TcTyVar)
894 -- Just like newMetaTyVarX, but make a SigTv
895 newMetaSigTyVarX subst tyvar = new_meta_tv_x SigTv subst tyvar
896
897 newWildCardX :: TCvSubst -> TyVar -> TcM (TCvSubst, TcTyVar)
898 newWildCardX subst tv
899 = do { new_tv <- newAnonMetaTyVar TauTv (substTy subst (tyVarKind tv))
900 ; return (extendTvSubstWithClone subst tv new_tv, new_tv) }
901
902 new_meta_tv_x :: MetaInfo -> TCvSubst -> TyVar -> TcM (TCvSubst, TcTyVar)
903 new_meta_tv_x info subst tv
904 = do { new_tv <- cloneAnonMetaTyVar info tv substd_kind
905 ; let subst1 = extendTvSubstWithClone subst tv new_tv
906 ; return (subst1, new_tv) }
907 where
908 substd_kind = substTyUnchecked subst (tyVarKind tv)
909 -- NOTE: Trac #12549 is fixed so we could use
910 -- substTy here, but the tc_infer_args problem
911 -- is not yet fixed so leaving as unchecked for now.
912 -- OLD NOTE:
913 -- Unchecked because we call newMetaTyVarX from
914 -- tcInstTyBinder, which is called from tcInferApps
915 -- which does not yet take enough trouble to ensure
916 -- the in-scope set is right; e.g. Trac #12785 trips
917 -- if we use substTy here
918
919 newMetaTyVarTyAtLevel :: TcLevel -> TcKind -> TcM TcType
920 newMetaTyVarTyAtLevel tc_lvl kind
921 = do { uniq <- newUnique
922 ; ref <- newMutVar Flexi
923 ; let name = mkMetaTyVarName uniq (fsLit "p")
924 details = MetaTv { mtv_info = TauTv
925 , mtv_ref = ref
926 , mtv_tclvl = tc_lvl }
927 ; return (mkTyVarTy (mkTcTyVar name kind details)) }
928
929 {- *********************************************************************
930 * *
931 Quantification
932 * *
933 ************************************************************************
934
935 Note [quantifyTyVars]
936 ~~~~~~~~~~~~~~~~~~~~~
937 quantifyTyVars is given the free vars of a type that we
938 are about to wrap in a forall.
939
940 It takes these free type/kind variables (partitioned into dependent and
941 non-dependent variables) and
942 1. Zonks them and remove globals and covars
943 2. Extends kvs1 with free kind vars in the kinds of tvs (removing globals)
944 3. Calls zonkQuantifiedTyVar on each
945
946 Step (2) is often unimportant, because the kind variable is often
947 also free in the type. Eg
948 Typeable k (a::k)
949 has free vars {k,a}. But the type (see Trac #7916)
950 (f::k->*) (a::k)
951 has free vars {f,a}, but we must add 'k' as well! Hence step (2).
952
953 * This function distinguishes between dependent and non-dependent
954 variables only to keep correct defaulting behavior with -XNoPolyKinds.
955 With -XPolyKinds, it treats both classes of variables identically.
956
957 * quantifyTyVars never quantifies over
958 - a coercion variable
959 - a runtime-rep variable
960
961 Note [quantifyTyVars determinism]
962 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
963 The results of quantifyTyVars are wrapped in a forall and can end up in the
964 interface file. One such example is inferred type signatures. They also affect
965 the results of optimizations, for example worker-wrapper. This means that to
966 get deterministic builds quantifyTyVars needs to be deterministic.
967
968 To achieve this CandidatesQTvs is backed by deterministic sets which allows them
969 to be later converted to a list in a deterministic order.
970
971 For more information about deterministic sets see
972 Note [Deterministic UniqFM] in UniqDFM.
973 -}
974
975 quantifyTyVars
976 :: TcTyCoVarSet -- Global tvs; already zonked
977 -> CandidatesQTvs -- See Note [Dependent type variables] in TcType
978 -- Already zonked
979 -> TcM [TcTyVar]
980 -- See Note [quantifyTyVars]
981 -- Can be given a mixture of TcTyVars and TyVars, in the case of
982 -- associated type declarations. Also accepts covars, but *never* returns any.
983
984 quantifyTyVars gbl_tvs dvs@(DV{ dv_kvs = dep_tkvs, dv_tvs = nondep_tkvs })
985 = do { traceTc "quantifyTyVars" (vcat [ppr dvs, ppr gbl_tvs])
986 ; let dep_kvs = dVarSetElemsWellScoped $
987 dep_tkvs `dVarSetMinusVarSet` gbl_tvs
988 -- dVarSetElemsWellScoped: put the kind variables into
989 -- well-scoped order.
990 -- E.g. [k, (a::k)] not the other way roud
991
992 nondep_tvs = dVarSetElems $
993 (nondep_tkvs `minusDVarSet` dep_tkvs)
994 `dVarSetMinusVarSet` gbl_tvs
995 -- See Note [Dependent type variables] in TcType
996 -- The `minus` dep_tkvs removes any kind-level vars
997 -- e.g. T k (a::k) Since k appear in a kind it'll
998 -- be in dv_kvs, and is dependent. So remove it from
999 -- dv_tvs which will also contain k
1000 -- No worry about dependent covars here;
1001 -- they are all in dep_tkvs
1002 -- No worry about scoping, because these are all
1003 -- type variables
1004 -- NB kinds of tvs are zonked by zonkTyCoVarsAndFV
1005
1006 -- In the non-PolyKinds case, default the kind variables
1007 -- to *, and zonk the tyvars as usual. Notice that this
1008 -- may make quantifyTyVars return a shorter list
1009 -- than it was passed, but that's ok
1010 ; poly_kinds <- xoptM LangExt.PolyKinds
1011 ; dep_kvs' <- mapMaybeM (zonk_quant (not poly_kinds)) dep_kvs
1012 ; nondep_tvs' <- mapMaybeM (zonk_quant False) nondep_tvs
1013 ; let final_qtvs = dep_kvs' ++ nondep_tvs'
1014 -- Because of the order, any kind variables
1015 -- mentioned in the kinds of the nondep_tvs'
1016 -- now refer to the dep_kvs'
1017
1018 ; traceTc "quantifyTyVars"
1019 (vcat [ text "globals:" <+> ppr gbl_tvs
1020 , text "nondep:" <+> pprTyVars nondep_tvs
1021 , text "dep:" <+> pprTyVars dep_kvs
1022 , text "dep_kvs'" <+> pprTyVars dep_kvs'
1023 , text "nondep_tvs'" <+> pprTyVars nondep_tvs' ])
1024
1025 -- We should never quantify over coercion variables; check this
1026 ; let co_vars = filter isCoVar final_qtvs
1027 ; MASSERT2( null co_vars, ppr co_vars )
1028
1029 ; return final_qtvs }
1030 where
1031 -- zonk_quant returns a tyvar if it should be quantified over;
1032 -- otherwise, it returns Nothing. The latter case happens for
1033 -- * Kind variables, with -XNoPolyKinds: don't quantify over these
1034 -- * RuntimeRep variables: we never quantify over these
1035 zonk_quant default_kind tkv
1036 | not (isTyVar tkv)
1037 = return Nothing -- this can happen for a covar that's associated with
1038 -- a coercion hole. Test case: typecheck/should_compile/T2494
1039
1040 | not (isTcTyVar tkv)
1041 = return (Just tkv) -- For associated types, we have the class variables
1042 -- in scope, and they are TyVars not TcTyVars
1043 | otherwise
1044 = do { deflt_done <- defaultTyVar default_kind tkv
1045 ; case deflt_done of
1046 True -> return Nothing
1047 False -> do { tv <- zonkQuantifiedTyVar tkv
1048 ; return (Just tv) } }
1049
1050 zonkQuantifiedTyVar :: TcTyVar -> TcM TcTyVar
1051 -- The quantified type variables often include meta type variables
1052 -- we want to freeze them into ordinary type variables
1053 -- The meta tyvar is updated to point to the new skolem TyVar. Now any
1054 -- bound occurrences of the original type variable will get zonked to
1055 -- the immutable version.
1056 --
1057 -- We leave skolem TyVars alone; they are immutable.
1058 --
1059 -- This function is called on both kind and type variables,
1060 -- but kind variables *only* if PolyKinds is on.
1061
1062 zonkQuantifiedTyVar tv
1063 = case tcTyVarDetails tv of
1064 SkolemTv {} -> do { kind <- zonkTcType (tyVarKind tv)
1065 ; return (setTyVarKind tv kind) }
1066 -- It might be a skolem type variable,
1067 -- for example from a user type signature
1068
1069 MetaTv {} -> skolemiseUnboundMetaTyVar tv
1070
1071 _other -> pprPanic "zonkQuantifiedTyVar" (ppr tv) -- RuntimeUnk
1072
1073 defaultTyVar :: Bool -- True <=> please default this kind variable to *
1074 -> TcTyVar -- If it's a MetaTyVar then it is unbound
1075 -> TcM Bool -- True <=> defaulted away altogether
1076
1077 defaultTyVar default_kind tv
1078 | not (isMetaTyVar tv)
1079 = return False
1080
1081 | isSigTyVar tv
1082 -- Do not default SigTvs. Doing so would violate the invariants
1083 -- on SigTvs; see Note [Signature skolems] in TcType.
1084 -- Trac #13343 is an example; #14555 is another
1085 -- See Note [Kind generalisation and SigTvs]
1086 = return False
1087
1088
1089 | isRuntimeRepVar tv -- Do not quantify over a RuntimeRep var
1090 -- unless it is a SigTv, handled earlier
1091 = do { traceTc "Defaulting a RuntimeRep var to LiftedRep" (ppr tv)
1092 ; writeMetaTyVar tv liftedRepTy
1093 ; return True }
1094
1095 | default_kind -- -XNoPolyKinds and this is a kind var
1096 = do { default_kind_var tv -- so default it to * if possible
1097 ; return True }
1098
1099 | otherwise
1100 = return False
1101
1102 where
1103 default_kind_var :: TyVar -> TcM ()
1104 -- defaultKindVar is used exclusively with -XNoPolyKinds
1105 -- See Note [Defaulting with -XNoPolyKinds]
1106 -- It takes an (unconstrained) meta tyvar and defaults it.
1107 -- Works only on vars of type *; for other kinds, it issues an error.
1108 default_kind_var kv
1109 | isLiftedTypeKind (tyVarKind kv)
1110 = do { traceTc "Defaulting a kind var to *" (ppr kv)
1111 ; writeMetaTyVar kv liftedTypeKind }
1112 | otherwise
1113 = addErr (vcat [ text "Cannot default kind variable" <+> quotes (ppr kv')
1114 , text "of kind:" <+> ppr (tyVarKind kv')
1115 , text "Perhaps enable PolyKinds or add a kind signature" ])
1116 where
1117 (_, kv') = tidyOpenTyCoVar emptyTidyEnv kv
1118
1119 skolemiseRuntimeUnk :: TcTyVar -> TcM TyVar
1120 skolemiseRuntimeUnk tv
1121 = skolemise_tv tv RuntimeUnk
1122
1123 skolemiseUnboundMetaTyVar :: TcTyVar -> TcM TyVar
1124 skolemiseUnboundMetaTyVar tv
1125 = skolemise_tv tv (SkolemTv (metaTyVarTcLevel tv) False)
1126
1127 skolemise_tv :: TcTyVar -> TcTyVarDetails -> TcM TyVar
1128 -- We have a Meta tyvar with a ref-cell inside it
1129 -- Skolemise it, so that
1130 -- we are totally out of Meta-tyvar-land
1131 -- We create a skolem TyVar, not a regular TyVar
1132 -- See Note [Zonking to Skolem]
1133 skolemise_tv tv details
1134 = ASSERT2( isMetaTyVar tv, ppr tv )
1135 do { when debugIsOn (check_empty tv)
1136 ; span <- getSrcSpanM -- Get the location from "here"
1137 -- ie where we are generalising
1138 ; kind <- zonkTcType (tyVarKind tv)
1139 ; let uniq = getUnique tv
1140 -- NB: Use same Unique as original tyvar. This is
1141 -- important for TcHsType.splitTelescopeTvs to work properly
1142
1143 tv_name = getOccName tv
1144 final_name = mkInternalName uniq tv_name span
1145 final_tv = mkTcTyVar final_name kind details
1146
1147 ; traceTc "Skolemising" (ppr tv <+> text ":=" <+> ppr final_tv)
1148 ; writeMetaTyVar tv (mkTyVarTy final_tv)
1149 ; return final_tv }
1150
1151 where
1152 check_empty tv -- [Sept 04] Check for non-empty.
1153 = when debugIsOn $ -- See note [Silly Type Synonym]
1154 do { cts <- readMetaTyVar tv
1155 ; case cts of
1156 Flexi -> return ()
1157 Indirect ty -> WARN( True, ppr tv $$ ppr ty )
1158 return () }
1159
1160 {- Note [Defaulting with -XNoPolyKinds]
1161 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1162 Consider
1163
1164 data Compose f g a = Mk (f (g a))
1165
1166 We infer
1167
1168 Compose :: forall k1 k2. (k2 -> *) -> (k1 -> k2) -> k1 -> *
1169 Mk :: forall k1 k2 (f :: k2 -> *) (g :: k1 -> k2) (a :: k1).
1170 f (g a) -> Compose k1 k2 f g a
1171
1172 Now, in another module, we have -XNoPolyKinds -XDataKinds in effect.
1173 What does 'Mk mean? Pre GHC-8.0 with -XNoPolyKinds,
1174 we just defaulted all kind variables to *. But that's no good here,
1175 because the kind variables in 'Mk aren't of kind *, so defaulting to *
1176 is ill-kinded.
1177
1178 After some debate on #11334, we decided to issue an error in this case.
1179 The code is in defaultKindVar.
1180
1181 Note [What is a meta variable?]
1182 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1183 A "meta type-variable", also know as a "unification variable" is a placeholder
1184 introduced by the typechecker for an as-yet-unknown monotype.
1185
1186 For example, when we see a call `reverse (f xs)`, we know that we calling
1187 reverse :: forall a. [a] -> [a]
1188 So we know that the argument `f xs` must be a "list of something". But what is
1189 the "something"? We don't know until we explore the `f xs` a bit more. So we set
1190 out what we do know at the call of `reverse` by instantiate its type with a fresh
1191 meta tyvar, `alpha` say. So now the type of the argument `f xs`, and of the
1192 result, is `[alpha]`. The unification variable `alpha` stands for the
1193 as-yet-unknown type of the elements of the list.
1194
1195 As type inference progresses we may learn more about `alpha`. For example, suppose
1196 `f` has the type
1197 f :: forall b. b -> [Maybe b]
1198 Then we instantiate `f`'s type with another fresh unification variable, say
1199 `beta`; and equate `f`'s result type with reverse's argument type, thus
1200 `[alpha] ~ [Maybe beta]`.
1201
1202 Now we can solve this equality to learn that `alpha ~ Maybe beta`, so we've
1203 refined our knowledge about `alpha`. And so on.
1204
1205 If you found this Note useful, you may also want to have a look at
1206 Section 5 of "Practical type inference for higher rank types" (Peyton Jones,
1207 Vytiniotis, Weirich and Shields. J. Functional Programming. 2011).
1208
1209 Note [What is zonking?]
1210 ~~~~~~~~~~~~~~~~~~~~~~~
1211 GHC relies heavily on mutability in the typechecker for efficient operation.
1212 For this reason, throughout much of the type checking process meta type
1213 variables (the MetaTv constructor of TcTyVarDetails) are represented by mutable
1214 variables (known as TcRefs).
1215
1216 Zonking is the process of ripping out these mutable variables and replacing them
1217 with a real Type. This involves traversing the entire type expression, but the
1218 interesting part of replacing the mutable variables occurs in zonkTyVarOcc.
1219
1220 There are two ways to zonk a Type:
1221
1222 * zonkTcTypeToType, which is intended to be used at the end of type-checking
1223 for the final zonk. It has to deal with unfilled metavars, either by filling
1224 it with a value like Any or failing (determined by the UnboundTyVarZonker
1225 used).
1226
1227 * zonkTcType, which will happily ignore unfilled metavars. This is the
1228 appropriate function to use while in the middle of type-checking.
1229
1230 Note [Zonking to Skolem]
1231 ~~~~~~~~~~~~~~~~~~~~~~~~
1232 We used to zonk quantified type variables to regular TyVars. However, this
1233 leads to problems. Consider this program from the regression test suite:
1234
1235 eval :: Int -> String -> String -> String
1236 eval 0 root actual = evalRHS 0 root actual
1237
1238 evalRHS :: Int -> a
1239 evalRHS 0 root actual = eval 0 root actual
1240
1241 It leads to the deferral of an equality (wrapped in an implication constraint)
1242
1243 forall a. () => ((String -> String -> String) ~ a)
1244
1245 which is propagated up to the toplevel (see TcSimplify.tcSimplifyInferCheck).
1246 In the meantime `a' is zonked and quantified to form `evalRHS's signature.
1247 This has the *side effect* of also zonking the `a' in the deferred equality
1248 (which at this point is being handed around wrapped in an implication
1249 constraint).
1250
1251 Finally, the equality (with the zonked `a') will be handed back to the
1252 simplifier by TcRnDriver.tcRnSrcDecls calling TcSimplify.tcSimplifyTop.
1253 If we zonk `a' with a regular type variable, we will have this regular type
1254 variable now floating around in the simplifier, which in many places assumes to
1255 only see proper TcTyVars.
1256
1257 We can avoid this problem by zonking with a skolem. The skolem is rigid
1258 (which we require for a quantified variable), but is still a TcTyVar that the
1259 simplifier knows how to deal with.
1260
1261 Note [Silly Type Synonyms]
1262 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1263 Consider this:
1264 type C u a = u -- Note 'a' unused
1265
1266 foo :: (forall a. C u a -> C u a) -> u
1267 foo x = ...
1268
1269 bar :: Num u => u
1270 bar = foo (\t -> t + t)
1271
1272 * From the (\t -> t+t) we get type {Num d} => d -> d
1273 where d is fresh.
1274
1275 * Now unify with type of foo's arg, and we get:
1276 {Num (C d a)} => C d a -> C d a
1277 where a is fresh.
1278
1279 * Now abstract over the 'a', but float out the Num (C d a) constraint
1280 because it does not 'really' mention a. (see exactTyVarsOfType)
1281 The arg to foo becomes
1282 \/\a -> \t -> t+t
1283
1284 * So we get a dict binding for Num (C d a), which is zonked to give
1285 a = ()
1286 [Note Sept 04: now that we are zonking quantified type variables
1287 on construction, the 'a' will be frozen as a regular tyvar on
1288 quantification, so the floated dict will still have type (C d a).
1289 Which renders this whole note moot; happily!]
1290
1291 * Then the \/\a abstraction has a zonked 'a' in it.
1292
1293 All very silly. I think its harmless to ignore the problem. We'll end up with
1294 a \/\a in the final result but all the occurrences of a will be zonked to ()
1295
1296 ************************************************************************
1297 * *
1298 Zonking types
1299 * *
1300 ************************************************************************
1301
1302 -}
1303
1304 -- | @tcGetGlobalTyCoVars@ returns a fully-zonked set of *scoped* tyvars free in
1305 -- the environment. To improve subsequent calls to the same function it writes
1306 -- the zonked set back into the environment. Note that this returns all
1307 -- variables free in anything (term-level or type-level) in scope. We thus
1308 -- don't have to worry about clashes with things that are not in scope, because
1309 -- if they are reachable, then they'll be returned here.
1310 -- NB: This is closed over kinds, so it can return unification variables mentioned
1311 -- in the kinds of in-scope tyvars.
1312 tcGetGlobalTyCoVars :: TcM TcTyVarSet
1313 tcGetGlobalTyCoVars
1314 = do { (TcLclEnv {tcl_tyvars = gtv_var}) <- getLclEnv
1315 ; gbl_tvs <- readMutVar gtv_var
1316 ; gbl_tvs' <- zonkTyCoVarsAndFV gbl_tvs
1317 ; writeMutVar gtv_var gbl_tvs'
1318 ; return gbl_tvs' }
1319
1320 zonkTcTypeAndFV :: TcType -> TcM DTyCoVarSet
1321 -- Zonk a type and take its free variables
1322 -- With kind polymorphism it can be essential to zonk *first*
1323 -- so that we find the right set of free variables. Eg
1324 -- forall k1. forall (a:k2). a
1325 -- where k2:=k1 is in the substitution. We don't want
1326 -- k2 to look free in this type!
1327 zonkTcTypeAndFV ty
1328 = tyCoVarsOfTypeDSet <$> zonkTcType ty
1329
1330 -- | Zonk a type and call 'candidateQTyVarsOfType' on it.
1331 zonkTcTypeAndSplitDepVars :: TcType -> TcM CandidatesQTvs
1332 zonkTcTypeAndSplitDepVars ty
1333 = candidateQTyVarsOfType <$> zonkTcType ty
1334
1335 zonkTcTypesAndSplitDepVars :: [TcType] -> TcM CandidatesQTvs
1336 zonkTcTypesAndSplitDepVars tys
1337 = candidateQTyVarsOfTypes <$> mapM zonkTcType tys
1338
1339 zonkTyCoVar :: TyCoVar -> TcM TcType
1340 -- Works on TyVars and TcTyVars
1341 zonkTyCoVar tv | isTcTyVar tv = zonkTcTyVar tv
1342 | isTyVar tv = mkTyVarTy <$> zonkTyCoVarKind tv
1343 | otherwise = ASSERT2( isCoVar tv, ppr tv )
1344 mkCoercionTy . mkCoVarCo <$> zonkTyCoVarKind tv
1345 -- Hackily, when typechecking type and class decls
1346 -- we have TyVars in scopeadded (only) in
1347 -- TcHsType.tcTyClTyVars, but it seems
1348 -- painful to make them into TcTyVars there
1349
1350 zonkTyCoVarsAndFV :: TyCoVarSet -> TcM TyCoVarSet
1351 zonkTyCoVarsAndFV tycovars =
1352 tyCoVarsOfTypes <$> mapM zonkTyCoVar (nonDetEltsUniqSet tycovars)
1353 -- It's OK to use nonDetEltsUniqSet here because we immediately forget about
1354 -- the ordering by turning it into a nondeterministic set and the order
1355 -- of zonking doesn't matter for determinism.
1356
1357 -- Takes a list of TyCoVars, zonks them and returns a
1358 -- deterministically ordered list of their free variables.
1359 zonkTyCoVarsAndFVList :: [TyCoVar] -> TcM [TyCoVar]
1360 zonkTyCoVarsAndFVList tycovars =
1361 tyCoVarsOfTypesList <$> mapM zonkTyCoVar tycovars
1362
1363 zonkTcTyVars :: [TcTyVar] -> TcM [TcType]
1364 zonkTcTyVars tyvars = mapM zonkTcTyVar tyvars
1365
1366 ----------------- Types
1367 zonkTyCoVarKind :: TyCoVar -> TcM TyCoVar
1368 zonkTyCoVarKind tv = do { kind' <- zonkTcType (tyVarKind tv)
1369 ; return (setTyVarKind tv kind') }
1370
1371 zonkTcTypes :: [TcType] -> TcM [TcType]
1372 zonkTcTypes tys = mapM zonkTcType tys
1373
1374 {-
1375 ************************************************************************
1376 * *
1377 Zonking constraints
1378 * *
1379 ************************************************************************
1380 -}
1381
1382 zonkImplication :: Implication -> TcM Implication
1383 zonkImplication implic@(Implic { ic_skols = skols
1384 , ic_given = given
1385 , ic_wanted = wanted
1386 , ic_info = info })
1387 = do { skols' <- mapM zonkTcTyCoVarBndr skols -- Need to zonk their kinds!
1388 -- as Trac #7230 showed
1389 ; given' <- mapM zonkEvVar given
1390 ; info' <- zonkSkolemInfo info
1391 ; wanted' <- zonkWCRec wanted
1392 ; return (implic { ic_skols = skols'
1393 , ic_given = given'
1394 , ic_wanted = wanted'
1395 , ic_info = info' }) }
1396
1397 zonkEvVar :: EvVar -> TcM EvVar
1398 zonkEvVar var = do { ty' <- zonkTcType (varType var)
1399 ; return (setVarType var ty') }
1400
1401
1402 zonkWC :: WantedConstraints -> TcM WantedConstraints
1403 zonkWC wc = zonkWCRec wc
1404
1405 zonkWCRec :: WantedConstraints -> TcM WantedConstraints
1406 zonkWCRec (WC { wc_simple = simple, wc_impl = implic })
1407 = do { simple' <- zonkSimples simple
1408 ; implic' <- mapBagM zonkImplication implic
1409 ; return (WC { wc_simple = simple', wc_impl = implic' }) }
1410
1411 zonkSimples :: Cts -> TcM Cts
1412 zonkSimples cts = do { cts' <- mapBagM zonkCt' cts
1413 ; traceTc "zonkSimples done:" (ppr cts')
1414 ; return cts' }
1415
1416 zonkCt' :: Ct -> TcM Ct
1417 zonkCt' ct = zonkCt ct
1418
1419 {- Note [zonkCt behaviour]
1420 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1421 zonkCt tries to maintain the canonical form of a Ct. For example,
1422 - a CDictCan should stay a CDictCan;
1423 - a CTyEqCan should stay a CTyEqCan (if the LHS stays as a variable.).
1424 - a CHoleCan should stay a CHoleCan
1425 - a CIrredCan should stay a CIrredCan with its cc_insol flag intact
1426
1427 Why?, for example:
1428 - For CDictCan, the @TcSimplify.expandSuperClasses@ step, which runs after the
1429 simple wanted and plugin loop, looks for @CDictCan@s. If a plugin is in use,
1430 constraints are zonked before being passed to the plugin. This means if we
1431 don't preserve a canonical form, @expandSuperClasses@ fails to expand
1432 superclasses. This is what happened in Trac #11525.
1433
1434 - For CHoleCan, once we forget that it's a hole, we can never recover that info.
1435
1436 - For CIrredCan we want to see if a constraint is insoluble with insolubleWC
1437
1438 NB: we do not expect to see any CFunEqCans, because zonkCt is only
1439 called on unflattened constraints.
1440
1441 NB: Constraints are always re-flattened etc by the canonicaliser in
1442 @TcCanonical@ even if they come in as CDictCan. Only canonical constraints that
1443 are actually in the inert set carry all the guarantees. So it is okay if zonkCt
1444 creates e.g. a CDictCan where the cc_tyars are /not/ function free.
1445 -}
1446
1447 zonkCt :: Ct -> TcM Ct
1448 zonkCt ct@(CHoleCan { cc_ev = ev })
1449 = do { ev' <- zonkCtEvidence ev
1450 ; return $ ct { cc_ev = ev' } }
1451
1452 zonkCt ct@(CDictCan { cc_ev = ev, cc_tyargs = args })
1453 = do { ev' <- zonkCtEvidence ev
1454 ; args' <- mapM zonkTcType args
1455 ; return $ ct { cc_ev = ev', cc_tyargs = args' } }
1456
1457 zonkCt ct@(CTyEqCan { cc_ev = ev, cc_tyvar = tv, cc_rhs = rhs })
1458 = do { ev' <- zonkCtEvidence ev
1459 ; tv_ty' <- zonkTcTyVar tv
1460 ; case getTyVar_maybe tv_ty' of
1461 Just tv' -> do { rhs' <- zonkTcType rhs
1462 ; return ct { cc_ev = ev'
1463 , cc_tyvar = tv'
1464 , cc_rhs = rhs' } }
1465 Nothing -> return (mkNonCanonical ev') }
1466
1467 zonkCt ct@(CIrredCan { cc_ev = ev }) -- Preserve the cc_insol flag
1468 = do { ev' <- zonkCtEvidence ev
1469 ; return (ct { cc_ev = ev' }) }
1470
1471 zonkCt ct
1472 = ASSERT( not (isCFunEqCan ct) )
1473 -- We do not expect to see any CFunEqCans, because zonkCt is only called on
1474 -- unflattened constraints.
1475 do { fl' <- zonkCtEvidence (ctEvidence ct)
1476 ; return (mkNonCanonical fl') }
1477
1478 zonkCtEvidence :: CtEvidence -> TcM CtEvidence
1479 zonkCtEvidence ctev@(CtGiven { ctev_pred = pred })
1480 = do { pred' <- zonkTcType pred
1481 ; return (ctev { ctev_pred = pred'}) }
1482 zonkCtEvidence ctev@(CtWanted { ctev_pred = pred, ctev_dest = dest })
1483 = do { pred' <- zonkTcType pred
1484 ; let dest' = case dest of
1485 EvVarDest ev -> EvVarDest $ setVarType ev pred'
1486 -- necessary in simplifyInfer
1487 HoleDest h -> HoleDest h
1488 ; return (ctev { ctev_pred = pred', ctev_dest = dest' }) }
1489 zonkCtEvidence ctev@(CtDerived { ctev_pred = pred })
1490 = do { pred' <- zonkTcType pred
1491 ; return (ctev { ctev_pred = pred' }) }
1492
1493 zonkSkolemInfo :: SkolemInfo -> TcM SkolemInfo
1494 zonkSkolemInfo (SigSkol cx ty tv_prs) = do { ty' <- zonkTcType ty
1495 ; return (SigSkol cx ty' tv_prs) }
1496 zonkSkolemInfo (InferSkol ntys) = do { ntys' <- mapM do_one ntys
1497 ; return (InferSkol ntys') }
1498 where
1499 do_one (n, ty) = do { ty' <- zonkTcType ty; return (n, ty') }
1500 zonkSkolemInfo skol_info = return skol_info
1501
1502 {-
1503 %************************************************************************
1504 %* *
1505 \subsection{Zonking -- the main work-horses: zonkTcType, zonkTcTyVar}
1506 * *
1507 * For internal use only! *
1508 * *
1509 ************************************************************************
1510
1511 -}
1512
1513 -- zonkId is used *during* typechecking just to zonk the Id's type
1514 zonkId :: TcId -> TcM TcId
1515 zonkId id
1516 = do { ty' <- zonkTcType (idType id)
1517 ; return (Id.setIdType id ty') }
1518
1519 zonkCoVar :: CoVar -> TcM CoVar
1520 zonkCoVar = zonkId
1521
1522 -- | A suitable TyCoMapper for zonking a type during type-checking,
1523 -- before all metavars are filled in.
1524 zonkTcTypeMapper :: TyCoMapper () TcM
1525 zonkTcTypeMapper = TyCoMapper
1526 { tcm_smart = True
1527 , tcm_tyvar = const zonkTcTyVar
1528 , tcm_covar = const (\cv -> mkCoVarCo <$> zonkTyCoVarKind cv)
1529 , tcm_hole = hole
1530 , tcm_tybinder = \_env tv _vis -> ((), ) <$> zonkTcTyCoVarBndr tv
1531 , tcm_tycon = return }
1532 where
1533 hole :: () -> CoercionHole -> TcM Coercion
1534 hole _ hole@(CoercionHole { ch_ref = ref, ch_co_var = cv })
1535 = do { contents <- readTcRef ref
1536 ; case contents of
1537 Just co -> do { co' <- zonkCo co
1538 ; checkCoercionHole cv co' }
1539 Nothing -> do { cv' <- zonkCoVar cv
1540 ; return $ HoleCo (hole { ch_co_var = cv' }) } }
1541
1542 -- For unbound, mutable tyvars, zonkType uses the function given to it
1543 -- For tyvars bound at a for-all, zonkType zonks them to an immutable
1544 -- type variable and zonks the kind too
1545 zonkTcType :: TcType -> TcM TcType
1546 zonkTcType = mapType zonkTcTypeMapper ()
1547
1548 -- | "Zonk" a coercion -- really, just zonk any types in the coercion
1549 zonkCo :: Coercion -> TcM Coercion
1550 zonkCo = mapCoercion zonkTcTypeMapper ()
1551
1552 zonkTcTyCoVarBndr :: TcTyCoVar -> TcM TcTyCoVar
1553 -- A tyvar binder is never a unification variable (TauTv),
1554 -- rather it is always a skolem. It *might* be a SigTv.
1555 -- (Because non-CUSK type declarations use SigTvs.)
1556 -- Regardless, it may have a kind
1557 -- that has not yet been zonked, and may include kind
1558 -- unification variables.
1559 zonkTcTyCoVarBndr tyvar
1560 | isSigTyVar tyvar
1561 = tcGetTyVar "zonkTcTyCoVarBndr SigTv" <$> zonkTcTyVar tyvar
1562
1563 | otherwise
1564 -- can't use isCoVar, because it looks at a TyCon. Argh.
1565 = ASSERT2( isImmutableTyVar tyvar || (not $ isTyVar tyvar), pprTyVar tyvar )
1566 updateTyVarKindM zonkTcType tyvar
1567
1568 zonkTcTyVarBinder :: TyVarBndr TcTyVar vis -> TcM (TyVarBndr TcTyVar vis)
1569 zonkTcTyVarBinder (TvBndr tv vis)
1570 = do { tv' <- zonkTcTyCoVarBndr tv
1571 ; return (TvBndr tv' vis) }
1572
1573 zonkTcTyVar :: TcTyVar -> TcM TcType
1574 -- Simply look through all Flexis
1575 zonkTcTyVar tv
1576 | isTcTyVar tv
1577 = case tcTyVarDetails tv of
1578 SkolemTv {} -> zonk_kind_and_return
1579 RuntimeUnk {} -> zonk_kind_and_return
1580 MetaTv { mtv_ref = ref }
1581 -> do { cts <- readMutVar ref
1582 ; case cts of
1583 Flexi -> zonk_kind_and_return
1584 Indirect ty -> zonkTcType ty }
1585
1586 | otherwise -- coercion variable
1587 = zonk_kind_and_return
1588 where
1589 zonk_kind_and_return = do { z_tv <- zonkTyCoVarKind tv
1590 ; return (mkTyVarTy z_tv) }
1591
1592 -- Variant that assumes that any result of zonking is still a TyVar.
1593 -- Should be used only on skolems and SigTvs
1594 zonkTcTyVarToTyVar :: HasDebugCallStack => TcTyVar -> TcM TcTyVar
1595 zonkTcTyVarToTyVar tv
1596 = do { ty <- zonkTcTyVar tv
1597 ; let tv' = case tcGetTyVar_maybe ty of
1598 Just tv' -> tv'
1599 Nothing -> pprPanic "zonkTcTyVarToTyVar"
1600 (ppr tv $$ ppr ty)
1601 ; return tv' }
1602
1603 zonkSigTyVarPairs :: [(Name,TcTyVar)] -> TcM [(Name,TcTyVar)]
1604 zonkSigTyVarPairs prs
1605 = mapM do_one prs
1606 where
1607 do_one (nm, tv) = do { tv' <- zonkTcTyVarToTyVar tv
1608 ; return (nm, tv') }
1609
1610 {-
1611 %************************************************************************
1612 %* *
1613 Tidying
1614 * *
1615 ************************************************************************
1616 -}
1617
1618 zonkTidyTcType :: TidyEnv -> TcType -> TcM (TidyEnv, TcType)
1619 zonkTidyTcType env ty = do { ty' <- zonkTcType ty
1620 ; return (tidyOpenType env ty') }
1621
1622 zonkTidyTcTypes :: TidyEnv -> [TcType] -> TcM (TidyEnv, [TcType])
1623 zonkTidyTcTypes = zonkTidyTcTypes' []
1624 where zonkTidyTcTypes' zs env [] = return (env, reverse zs)
1625 zonkTidyTcTypes' zs env (ty:tys)
1626 = do { (env', ty') <- zonkTidyTcType env ty
1627 ; zonkTidyTcTypes' (ty':zs) env' tys }
1628
1629 zonkTidyOrigin :: TidyEnv -> CtOrigin -> TcM (TidyEnv, CtOrigin)
1630 zonkTidyOrigin env (GivenOrigin skol_info)
1631 = do { skol_info1 <- zonkSkolemInfo skol_info
1632 ; let skol_info2 = tidySkolemInfo env skol_info1
1633 ; return (env, GivenOrigin skol_info2) }
1634 zonkTidyOrigin env orig@(TypeEqOrigin { uo_actual = act
1635 , uo_expected = exp })
1636 = do { (env1, act') <- zonkTidyTcType env act
1637 ; (env2, exp') <- zonkTidyTcType env1 exp
1638 ; return ( env2, orig { uo_actual = act'
1639 , uo_expected = exp' }) }
1640 zonkTidyOrigin env (KindEqOrigin ty1 m_ty2 orig t_or_k)
1641 = do { (env1, ty1') <- zonkTidyTcType env ty1
1642 ; (env2, m_ty2') <- case m_ty2 of
1643 Just ty2 -> second Just <$> zonkTidyTcType env1 ty2
1644 Nothing -> return (env1, Nothing)
1645 ; (env3, orig') <- zonkTidyOrigin env2 orig
1646 ; return (env3, KindEqOrigin ty1' m_ty2' orig' t_or_k) }
1647 zonkTidyOrigin env (FunDepOrigin1 p1 l1 p2 l2)
1648 = do { (env1, p1') <- zonkTidyTcType env p1
1649 ; (env2, p2') <- zonkTidyTcType env1 p2
1650 ; return (env2, FunDepOrigin1 p1' l1 p2' l2) }
1651 zonkTidyOrigin env (FunDepOrigin2 p1 o1 p2 l2)
1652 = do { (env1, p1') <- zonkTidyTcType env p1
1653 ; (env2, p2') <- zonkTidyTcType env1 p2
1654 ; (env3, o1') <- zonkTidyOrigin env2 o1
1655 ; return (env3, FunDepOrigin2 p1' o1' p2' l2) }
1656 zonkTidyOrigin env orig = return (env, orig)
1657
1658 ----------------
1659 tidyCt :: TidyEnv -> Ct -> Ct
1660 -- Used only in error reporting
1661 -- Also converts it to non-canonical
1662 tidyCt env ct
1663 = case ct of
1664 CHoleCan { cc_ev = ev }
1665 -> ct { cc_ev = tidy_ev env ev }
1666 _ -> mkNonCanonical (tidy_ev env (ctEvidence ct))
1667 where
1668 tidy_ev :: TidyEnv -> CtEvidence -> CtEvidence
1669 -- NB: we do not tidy the ctev_evar field because we don't
1670 -- show it in error messages
1671 tidy_ev env ctev@(CtGiven { ctev_pred = pred })
1672 = ctev { ctev_pred = tidyType env pred }
1673 tidy_ev env ctev@(CtWanted { ctev_pred = pred })
1674 = ctev { ctev_pred = tidyType env pred }
1675 tidy_ev env ctev@(CtDerived { ctev_pred = pred })
1676 = ctev { ctev_pred = tidyType env pred }
1677
1678 ----------------
1679 tidyEvVar :: TidyEnv -> EvVar -> EvVar
1680 tidyEvVar env var = setVarType var (tidyType env (varType var))
1681
1682 ----------------
1683 tidySkolemInfo :: TidyEnv -> SkolemInfo -> SkolemInfo
1684 tidySkolemInfo env (DerivSkol ty) = DerivSkol (tidyType env ty)
1685 tidySkolemInfo env (SigSkol cx ty tv_prs) = tidySigSkol env cx ty tv_prs
1686 tidySkolemInfo env (InferSkol ids) = InferSkol (mapSnd (tidyType env) ids)
1687 tidySkolemInfo env (UnifyForAllSkol ty) = UnifyForAllSkol (tidyType env ty)
1688 tidySkolemInfo _ info = info
1689
1690 tidySigSkol :: TidyEnv -> UserTypeCtxt
1691 -> TcType -> [(Name,TcTyVar)] -> SkolemInfo
1692 -- We need to take special care when tidying SigSkol
1693 -- See Note [SigSkol SkolemInfo] in TcRnTypes
1694 tidySigSkol env cx ty tv_prs
1695 = SigSkol cx (tidy_ty env ty) tv_prs'
1696 where
1697 tv_prs' = mapSnd (tidyTyVarOcc env) tv_prs
1698 inst_env = mkNameEnv tv_prs'
1699
1700 tidy_ty env (ForAllTy (TvBndr tv vis) ty)
1701 = ForAllTy (TvBndr tv' vis) (tidy_ty env' ty)
1702 where
1703 (env', tv') = tidy_tv_bndr env tv
1704
1705 tidy_ty env (FunTy arg res)
1706 = FunTy (tidyType env arg) (tidy_ty env res)
1707
1708 tidy_ty env ty = tidyType env ty
1709
1710 tidy_tv_bndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
1711 tidy_tv_bndr env@(occ_env, subst) tv
1712 | Just tv' <- lookupNameEnv inst_env (tyVarName tv)
1713 = ((occ_env, extendVarEnv subst tv tv'), tv')
1714
1715 | otherwise
1716 = tidyTyCoVarBndr env tv
1717
1718 -------------------------------------------------------------------------
1719 {-
1720 %************************************************************************
1721 %* *
1722 Levity polymorphism checks
1723 * *
1724 ************************************************************************
1725
1726 See Note [Levity polymorphism checking] in DsMonad
1727
1728 -}
1729
1730 -- | According to the rules around representation polymorphism
1731 -- (see https://ghc.haskell.org/trac/ghc/wiki/NoSubKinds), no binder
1732 -- can have a representation-polymorphic type. This check ensures
1733 -- that we respect this rule. It is a bit regrettable that this error
1734 -- occurs in zonking, after which we should have reported all errors.
1735 -- But it's hard to see where else to do it, because this can be discovered
1736 -- only after all solving is done. And, perhaps most importantly, this
1737 -- isn't really a compositional property of a type system, so it's
1738 -- not a terrible surprise that the check has to go in an awkward spot.
1739 ensureNotLevPoly :: Type -- its zonked type
1740 -> SDoc -- where this happened
1741 -> TcM ()
1742 ensureNotLevPoly ty doc
1743 = whenNoErrs $ -- sometimes we end up zonking bogus definitions of type
1744 -- forall a. a. See, for example, test ghci/scripts/T9140
1745 checkForLevPoly doc ty
1746
1747 -- See Note [Levity polymorphism checking] in DsMonad
1748 checkForLevPoly :: SDoc -> Type -> TcM ()
1749 checkForLevPoly = checkForLevPolyX addErr
1750
1751 checkForLevPolyX :: Monad m
1752 => (SDoc -> m ()) -- how to report an error
1753 -> SDoc -> Type -> m ()
1754 checkForLevPolyX add_err extra ty
1755 | isTypeLevPoly ty
1756 = add_err (formatLevPolyErr ty $$ extra)
1757 | otherwise
1758 = return ()
1759
1760 formatLevPolyErr :: Type -- levity-polymorphic type
1761 -> SDoc
1762 formatLevPolyErr ty
1763 = hang (text "A levity-polymorphic type is not allowed here:")
1764 2 (vcat [ text "Type:" <+> pprWithTYPE tidy_ty
1765 , text "Kind:" <+> pprWithTYPE tidy_ki ])
1766 where
1767 (tidy_env, tidy_ty) = tidyOpenType emptyTidyEnv ty
1768 tidy_ki = tidyType tidy_env (typeKind ty)