Make SigSkol take TcType not ExpType
[ghc.git] / compiler / typecheck / TcUnify.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5
6 Type subsumption and unification
7 -}
8
9 {-# LANGUAGE CPP, MultiWayIf, TupleSections #-}
10
11 module TcUnify (
12 -- Full-blown subsumption
13 tcWrapResult, tcWrapResultO, tcSkolemise, tcSkolemiseET,
14 tcSubTypeHR, tcSubType, tcSubTypeO, tcSubType_NC, tcSubTypeDS, tcSubTypeDS_O,
15 tcSubTypeDS_NC, tcSubTypeDS_NC_O, tcSubTypeET, tcSubTypeET_NC,
16 checkConstraints, buildImplicationFor,
17
18 -- Various unifications
19 unifyType_, unifyType, unifyTheta, unifyKind, noThing,
20 uType, unifyExpType,
21
22 --------------------------------
23 -- Holes
24 tcInfer,
25 matchExpectedListTy,
26 matchExpectedPArrTy,
27 matchExpectedTyConApp,
28 matchExpectedAppTy,
29 matchExpectedFunTys,
30 matchActualFunTys, matchActualFunTysPart,
31 matchExpectedFunKind,
32
33 wrapFunResCoercion
34
35 ) where
36
37 #include "HsVersions.h"
38
39 import HsSyn
40 import TyCoRep
41 import TcMType
42 import TcRnMonad
43 import TcType
44 import Type
45 import Coercion
46 import TcEvidence
47 import Name ( isSystemName )
48 import Inst
49 import TyCon
50 import TysWiredIn
51 import Var
52 import VarSet
53 import VarEnv
54 import ErrUtils
55 import DynFlags
56 import BasicTypes
57 import Name ( Name )
58 import Bag
59 import Util
60 import Outputable
61 import FastString
62
63 import Control.Monad
64 import Control.Arrow ( second )
65
66 {-
67 ************************************************************************
68 * *
69 matchExpected functions
70 * *
71 ************************************************************************
72
73 Note [Herald for matchExpectedFunTys]
74 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
75 The 'herald' always looks like:
76 "The equation(s) for 'f' have"
77 "The abstraction (\x.e) takes"
78 "The section (+ x) expects"
79 "The function 'f' is applied to"
80
81 This is used to construct a message of form
82
83 The abstraction `\Just 1 -> ...' takes two arguments
84 but its type `Maybe a -> a' has only one
85
86 The equation(s) for `f' have two arguments
87 but its type `Maybe a -> a' has only one
88
89 The section `(f 3)' requires 'f' to take two arguments
90 but its type `Int -> Int' has only one
91
92 The function 'f' is applied to two arguments
93 but its type `Int -> Int' has only one
94
95 Note [matchExpectedFunTys]
96 ~~~~~~~~~~~~~~~~~~~~~~~~~~
97 matchExpectedFunTys checks that a sigma has the form
98 of an n-ary function. It passes the decomposed type to the
99 thing_inside, and returns a wrapper to coerce between the two types
100
101 It's used wherever a language construct must have a functional type,
102 namely:
103 A lambda expression
104 A function definition
105 An operator section
106
107 This function must be written CPS'd because it needs to fill in the
108 ExpTypes produced for arguments before it can fill in the ExpType
109 passed in.
110
111 -}
112
113 -- Use this one when you have an "expected" type.
114 matchExpectedFunTys :: SDoc -- See Note [Herald for matchExpectedFunTys]
115 -> Arity
116 -> ExpRhoType -- deeply skolemised
117 -> ([ExpSigmaType] -> ExpRhoType -> TcM a)
118 -- must fill in these ExpTypes here
119 -> TcM (a, HsWrapper)
120 -- If matchExpectedFunTys n ty = (_, wrap)
121 -- then wrap : (t1 -> ... -> tn -> ty_r) "->" ty,
122 -- where [t1, ..., tn], ty_r are passed to the thing_inside
123 matchExpectedFunTys herald arity orig_ty thing_inside
124 = case orig_ty of
125 Check ty -> go [] arity ty
126 _ -> defer [] arity orig_ty
127 where
128 go acc_arg_tys 0 ty
129 = do { result <- thing_inside (reverse acc_arg_tys) (mkCheckExpType ty)
130 ; return (result, idHsWrapper) }
131
132 go acc_arg_tys n ty
133 | Just ty' <- coreView ty = go acc_arg_tys n ty'
134
135 go acc_arg_tys n (ForAllTy (Anon arg_ty) res_ty)
136 = ASSERT( not (isPredTy arg_ty) )
137 do { (result, wrap_res) <- go (mkCheckExpType arg_ty : acc_arg_tys)
138 (n-1) res_ty
139 ; return ( result
140 , mkWpFun idHsWrapper wrap_res arg_ty res_ty ) }
141
142 go acc_arg_tys n ty@(TyVarTy tv)
143 | ASSERT( isTcTyVar tv) isMetaTyVar tv
144 = do { cts <- readMetaTyVar tv
145 ; case cts of
146 Indirect ty' -> go acc_arg_tys n ty'
147 Flexi -> defer acc_arg_tys n (mkCheckExpType ty) }
148
149 -- In all other cases we bale out into ordinary unification
150 -- However unlike the meta-tyvar case, we are sure that the
151 -- number of arguments doesn't match arity of the original
152 -- type, so we can add a bit more context to the error message
153 -- (cf Trac #7869).
154 --
155 -- It is not always an error, because specialized type may have
156 -- different arity, for example:
157 --
158 -- > f1 = f2 'a'
159 -- > f2 :: Monad m => m Bool
160 -- > f2 = undefined
161 --
162 -- But in that case we add specialized type into error context
163 -- anyway, because it may be useful. See also Trac #9605.
164 go acc_arg_tys n ty = addErrCtxtM mk_ctxt $
165 defer acc_arg_tys n (mkCheckExpType ty)
166
167 ------------
168 defer acc_arg_tys n fun_ty
169 = do { more_arg_tys <- replicateM n newOpenInferExpType
170 ; res_ty <- newOpenInferExpType
171 ; result <- thing_inside (reverse acc_arg_tys ++ more_arg_tys) res_ty
172 ; more_arg_tys <- mapM readExpType more_arg_tys
173 ; res_ty <- readExpType res_ty
174 ; let unif_fun_ty = mkFunTys more_arg_tys res_ty
175 ; wrap <- tcSubTypeDS GenSigCtxt noThing unif_fun_ty fun_ty
176 ; return (result, wrap) }
177
178 ------------
179 mk_ctxt :: TidyEnv -> TcM (TidyEnv, MsgDoc)
180 mk_ctxt env = do { (env', ty) <- zonkTidyTcType env orig_tc_ty
181 ; let (args, _) = tcSplitFunTys ty
182 n_actual = length args
183 (env'', orig_ty') = tidyOpenType env' orig_tc_ty
184 ; return ( env''
185 , mk_fun_tys_msg orig_ty' ty n_actual arity herald) }
186 where
187 orig_tc_ty = checkingExpType "matchExpectedFunTys" orig_ty
188 -- this is safe b/c we're called from "go"
189
190 -- Like 'matchExpectedFunTys', but used when you have an "actual" type,
191 -- for example in function application
192 matchActualFunTys :: Outputable a
193 => SDoc -- See Note [Herald for matchExpectedFunTys]
194 -> CtOrigin
195 -> Maybe a -- the thing with type TcSigmaType
196 -> Arity
197 -> TcSigmaType
198 -> TcM (HsWrapper, [TcSigmaType], TcSigmaType)
199 -- If matchActualFunTys n ty = (wrap, [t1,..,tn], ty_r)
200 -- then wrap : ty "->" (t1 -> ... -> tn -> ty_r)
201 matchActualFunTys herald ct_orig mb_thing arity ty
202 = matchActualFunTysPart herald ct_orig mb_thing arity ty [] arity
203
204 -- | Variant of 'matchActualFunTys' that works when supplied only part
205 -- (that is, to the right of some arrows) of the full function type
206 matchActualFunTysPart :: Outputable a
207 => SDoc -- See Note [Herald for matchExpectedFunTys]
208 -> CtOrigin
209 -> Maybe a -- the thing with type TcSigmaType
210 -> Arity
211 -> TcSigmaType
212 -> [TcSigmaType] -- reversed args. See (*) below.
213 -> Arity -- overall arity of the function, for errs
214 -> TcM (HsWrapper, [TcSigmaType], TcSigmaType)
215 matchActualFunTysPart herald ct_orig mb_thing arity orig_ty
216 orig_old_args full_arity
217 = go arity orig_old_args orig_ty
218 -- Does not allocate unnecessary meta variables: if the input already is
219 -- a function, we just take it apart. Not only is this efficient,
220 -- it's important for higher rank: the argument might be of form
221 -- (forall a. ty) -> other
222 -- If allocated (fresh-meta-var1 -> fresh-meta-var2) and unified, we'd
223 -- hide the forall inside a meta-variable
224
225 -- (*) Sometimes it's necessary to call matchActualFunTys with only part
226 -- (that is, to the right of some arrows) of the type of the function in
227 -- question. (See TcExpr.tcArgs.) This argument is the reversed list of
228 -- arguments already seen (that is, not part of the TcSigmaType passed
229 -- in elsewhere).
230
231 where
232 -- This function has a bizarre mechanic: it accumulates arguments on
233 -- the way down and also builds an argument list on the way up. Why:
234 -- 1. The returns args list and the accumulated args list might be different.
235 -- The accumulated args include all the arg types for the function,
236 -- including those from before this function was called. The returned
237 -- list should include only those arguments produced by this call of
238 -- matchActualFunTys
239 --
240 -- 2. The HsWrapper can be built only on the way up. It seems (more)
241 -- bizarre to build the HsWrapper but not the arg_tys.
242 --
243 -- Refactoring is welcome.
244 go :: Arity
245 -> [TcSigmaType] -- accumulator of arguments (reversed)
246 -> TcSigmaType -- the remainder of the type as we're processing
247 -> TcM (HsWrapper, [TcSigmaType], TcSigmaType)
248 go 0 _ ty = return (idHsWrapper, [], ty)
249
250 go n acc_args ty
251 | not (null tvs && null theta)
252 = do { (wrap1, rho) <- topInstantiate ct_orig ty
253 ; (wrap2, arg_tys, res_ty) <- go n acc_args rho
254 ; return (wrap2 <.> wrap1, arg_tys, res_ty) }
255 where
256 (tvs, theta, _) = tcSplitSigmaTy ty
257
258 go n acc_args ty
259 | Just ty' <- coreView ty = go n acc_args ty'
260
261 go n acc_args (ForAllTy (Anon arg_ty) res_ty)
262 = ASSERT( not (isPredTy arg_ty) )
263 do { (wrap_res, tys, ty_r) <- go (n-1) (arg_ty : acc_args) res_ty
264 ; return ( mkWpFun idHsWrapper wrap_res arg_ty ty_r
265 , arg_ty : tys, ty_r ) }
266
267 go n acc_args ty@(TyVarTy tv)
268 | ASSERT( isTcTyVar tv) isMetaTyVar tv
269 = do { cts <- readMetaTyVar tv
270 ; case cts of
271 Indirect ty' -> go n acc_args ty'
272 Flexi -> defer n ty }
273
274 -- In all other cases we bale out into ordinary unification
275 -- However unlike the meta-tyvar case, we are sure that the
276 -- number of arguments doesn't match arity of the original
277 -- type, so we can add a bit more context to the error message
278 -- (cf Trac #7869).
279 --
280 -- It is not always an error, because specialized type may have
281 -- different arity, for example:
282 --
283 -- > f1 = f2 'a'
284 -- > f2 :: Monad m => m Bool
285 -- > f2 = undefined
286 --
287 -- But in that case we add specialized type into error context
288 -- anyway, because it may be useful. See also Trac #9605.
289 go n acc_args ty = addErrCtxtM (mk_ctxt (reverse acc_args) ty) $
290 defer n ty
291
292 ------------
293 defer n fun_ty
294 = do { arg_tys <- replicateM n newOpenFlexiTyVarTy
295 ; res_ty <- newOpenFlexiTyVarTy
296 ; let unif_fun_ty = mkFunTys arg_tys res_ty
297 ; co <- unifyType mb_thing fun_ty unif_fun_ty
298 ; return (mkWpCastN co, arg_tys, res_ty) }
299
300 ------------
301 mk_ctxt :: [TcSigmaType] -> TcSigmaType -> TidyEnv -> TcM (TidyEnv, MsgDoc)
302 mk_ctxt arg_tys res_ty env
303 = do { let ty = mkFunTys arg_tys res_ty
304 ; (env1, zonked) <- zonkTidyTcType env ty
305 -- zonking might change # of args
306 ; let (zonked_args, _) = tcSplitFunTys zonked
307 n_actual = length zonked_args
308 (env2, unzonked) = tidyOpenType env1 ty
309 ; return ( env2
310 , mk_fun_tys_msg unzonked zonked n_actual full_arity herald) }
311
312 mk_fun_tys_msg :: TcType -- the full type passed in (unzonked)
313 -> TcType -- the full type passed in (zonked)
314 -> Arity -- the # of args found
315 -> Arity -- the # of args wanted
316 -> SDoc -- overall herald
317 -> SDoc
318 mk_fun_tys_msg full_ty ty n_args full_arity herald
319 = herald <+> speakNOf full_arity (text "argument") <> comma $$
320 if n_args == full_arity
321 then text "its type is" <+> quotes (pprType full_ty) <>
322 comma $$
323 text "it is specialized to" <+> quotes (pprType ty)
324 else sep [text "but its type" <+> quotes (pprType ty),
325 if n_args == 0 then text "has none"
326 else text "has only" <+> speakN n_args]
327
328 ----------------------
329 matchExpectedListTy :: TcRhoType -> TcM (TcCoercionN, TcRhoType)
330 -- Special case for lists
331 matchExpectedListTy exp_ty
332 = do { (co, [elt_ty]) <- matchExpectedTyConApp listTyCon exp_ty
333 ; return (co, elt_ty) }
334
335 ----------------------
336 matchExpectedPArrTy :: TcRhoType -> TcM (TcCoercionN, TcRhoType)
337 -- Special case for parrs
338 matchExpectedPArrTy exp_ty
339 = do { (co, [elt_ty]) <- matchExpectedTyConApp parrTyCon exp_ty
340 ; return (co, elt_ty) }
341
342 ---------------------
343 matchExpectedTyConApp :: TyCon -- T :: forall kv1 ... kvm. k1 -> ... -> kn -> *
344 -> TcRhoType -- orig_ty
345 -> TcM (TcCoercionN, -- T k1 k2 k3 a b c ~N orig_ty
346 [TcSigmaType]) -- Element types, k1 k2 k3 a b c
347
348 -- It's used for wired-in tycons, so we call checkWiredInTyCon
349 -- Precondition: never called with FunTyCon
350 -- Precondition: input type :: *
351 -- Postcondition: (T k1 k2 k3 a b c) is well-kinded
352
353 matchExpectedTyConApp tc orig_ty
354 = go orig_ty
355 where
356 go ty
357 | Just ty' <- coreView ty
358 = go ty'
359
360 go ty@(TyConApp tycon args)
361 | tc == tycon -- Common case
362 = return (mkTcNomReflCo ty, args)
363
364 go (TyVarTy tv)
365 | ASSERT( isTcTyVar tv) isMetaTyVar tv
366 = do { cts <- readMetaTyVar tv
367 ; case cts of
368 Indirect ty -> go ty
369 Flexi -> defer }
370
371 go _ = defer
372
373 -- If the common case does not occur, instantiate a template
374 -- T k1 .. kn t1 .. tm, and unify with the original type
375 -- Doing it this way ensures that the types we return are
376 -- kind-compatible with T. For example, suppose we have
377 -- matchExpectedTyConApp T (f Maybe)
378 -- where data T a = MkT a
379 -- Then we don't want to instantate T's data constructors with
380 -- (a::*) ~ Maybe
381 -- because that'll make types that are utterly ill-kinded.
382 -- This happened in Trac #7368
383 defer
384 = do { (_subst, args) <- tcInstBinders (tyConBinders tc)
385 ; co <- unifyType noThing (mkTyConApp tc args) orig_ty
386 ; return (co, args) }
387
388 ----------------------
389 matchExpectedAppTy :: TcRhoType -- orig_ty
390 -> TcM (TcCoercion, -- m a ~N orig_ty
391 (TcSigmaType, TcSigmaType)) -- Returns m, a
392 -- If the incoming type is a mutable type variable of kind k, then
393 -- matchExpectedAppTy returns a new type variable (m: * -> k); note the *.
394
395 matchExpectedAppTy orig_ty
396 = go orig_ty
397 where
398 go ty
399 | Just ty' <- coreView ty = go ty'
400
401 | Just (fun_ty, arg_ty) <- tcSplitAppTy_maybe ty
402 = return (mkTcNomReflCo orig_ty, (fun_ty, arg_ty))
403
404 go (TyVarTy tv)
405 | ASSERT( isTcTyVar tv) isMetaTyVar tv
406 = do { cts <- readMetaTyVar tv
407 ; case cts of
408 Indirect ty -> go ty
409 Flexi -> defer }
410
411 go _ = defer
412
413 -- Defer splitting by generating an equality constraint
414 defer
415 = do { ty1 <- newFlexiTyVarTy kind1
416 ; ty2 <- newFlexiTyVarTy kind2
417 ; co <- unifyType noThing (mkAppTy ty1 ty2) orig_ty
418 ; return (co, (ty1, ty2)) }
419
420 orig_kind = typeKind orig_ty
421 kind1 = mkFunTy liftedTypeKind orig_kind
422 kind2 = liftedTypeKind -- m :: * -> k
423 -- arg type :: *
424
425 {-
426 ************************************************************************
427 * *
428 Subsumption checking
429 * *
430 ************************************************************************
431
432 Note [Subsumption checking: tcSubType]
433 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
434 All the tcSubType calls have the form
435 tcSubType actual_ty expected_ty
436 which checks
437 actual_ty <= expected_ty
438
439 That is, that a value of type actual_ty is acceptable in
440 a place expecting a value of type expected_ty. I.e. that
441
442 actual ty is more polymorphic than expected_ty
443
444 It returns a coercion function
445 co_fn :: actual_ty ~ expected_ty
446 which takes an HsExpr of type actual_ty into one of type
447 expected_ty.
448
449 These functions do not actually check for subsumption. They check if
450 expected_ty is an appropriate annotation to use for something of type
451 actual_ty. This difference matters when thinking about visible type
452 application. For example,
453
454 forall a. a -> forall b. b -> b
455 DOES NOT SUBSUME
456 forall a b. a -> b -> b
457
458 because the type arguments appear in a different order. (Neither does
459 it work the other way around.) BUT, these types are appropriate annotations
460 for one another. Because the user directs annotations, it's OK if some
461 arguments shuffle around -- after all, it's what the user wants.
462 Bottom line: none of this changes with visible type application.
463
464 There are a number of wrinkles (below).
465
466 Notice that Wrinkle 1 and 2 both require eta-expansion, which technically
467 may increase termination. We just put up with this, in exchange for getting
468 more predictable type inference.
469
470 Wrinkle 1: Note [Deep skolemisation]
471 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
472 We want (forall a. Int -> a -> a) <= (Int -> forall a. a->a)
473 (see section 4.6 of "Practical type inference for higher rank types")
474 So we must deeply-skolemise the RHS before we instantiate the LHS.
475
476 That is why tc_sub_type starts with a call to tcSkolemise (which does the
477 deep skolemisation), and then calls the DS variant (which assumes
478 that expected_ty is deeply skolemised)
479
480 Wrinkle 2: Note [Co/contra-variance of subsumption checking]
481 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
482 Consider g :: (Int -> Int) -> Int
483 f1 :: (forall a. a -> a) -> Int
484 f1 = g
485
486 f2 :: (forall a. a -> a) -> Int
487 f2 x = g x
488 f2 will typecheck, and it would be odd/fragile if f1 did not.
489 But f1 will only typecheck if we have that
490 (Int->Int) -> Int <= (forall a. a->a) -> Int
491 And that is only true if we do the full co/contravariant thing
492 in the subsumption check. That happens in the FunTy case of
493 tcSubTypeDS_NC_O, and is the sole reason for the WpFun form of
494 HsWrapper.
495
496 Another powerful reason for doing this co/contra stuff is visible
497 in Trac #9569, involving instantiation of constraint variables,
498 and again involving eta-expansion.
499
500 Wrinkle 3: Note [Higher rank types]
501 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
502 Consider tc150:
503 f y = \ (x::forall a. a->a). blah
504 The following happens:
505 * We will infer the type of the RHS, ie with a res_ty = alpha.
506 * Then the lambda will split alpha := beta -> gamma.
507 * And then we'll check tcSubType IsSwapped beta (forall a. a->a)
508
509 So it's important that we unify beta := forall a. a->a, rather than
510 skolemising the type.
511 -}
512
513
514 -- | Call this variant when you are in a higher-rank situation and
515 -- you know the right-hand type is deeply skolemised.
516 tcSubTypeHR :: Outputable a
517 => CtOrigin -- ^ of the actual type
518 -> Maybe a -- ^ If present, it has type ty_actual
519 -> TcSigmaType -> ExpRhoType -> TcM HsWrapper
520 tcSubTypeHR orig = tcSubTypeDS_NC_O orig GenSigCtxt
521
522 tcSubType :: Outputable a
523 => UserTypeCtxt -> Maybe a -- ^ If present, it has type ty_actual
524 -> TcSigmaType -> ExpSigmaType -> TcM HsWrapper
525 -- Checks that actual <= expected
526 -- Returns HsWrapper :: actual ~ expected
527 tcSubType ctxt maybe_thing ty_actual ty_expected
528 = tcSubTypeO origin ctxt ty_actual ty_expected
529 where
530 origin = TypeEqOrigin { uo_actual = ty_actual
531 , uo_expected = ty_expected
532 , uo_thing = mkErrorThing <$> maybe_thing }
533
534
535 -- | This is like 'tcSubType' but accepts an 'ExpType' as the /actual/ type.
536 -- You probably want this only when looking at patterns, never expressions.
537 tcSubTypeET :: CtOrigin -> ExpSigmaType -> TcSigmaType -> TcM HsWrapper
538 tcSubTypeET orig ty_actual ty_expected
539 = uExpTypeX orig ty_expected ty_actual
540 (return . mkWpCastN . mkTcSymCo)
541 (\ty_a -> tcSubTypeO orig GenSigCtxt ty_a
542 (mkCheckExpType ty_expected))
543
544 -- | This is like 'tcSubType' but accepts an 'ExpType' as the /actual/ type.
545 -- You probably want this only when looking at patterns, never expressions.
546 -- Does not add context.
547 tcSubTypeET_NC :: UserTypeCtxt -> ExpSigmaType -> TcSigmaType -> TcM HsWrapper
548 tcSubTypeET_NC _ ty_actual@(Infer {}) ty_expected
549 = mkWpCastN . mkTcSymCo <$> unifyExpType noThing ty_expected ty_actual
550 tcSubTypeET_NC ctxt (Check ty_actual) ty_expected
551 = tc_sub_type orig orig ctxt ty_actual ty_expected'
552 where
553 ty_expected' = mkCheckExpType ty_expected
554 orig = TypeEqOrigin { uo_actual = ty_actual
555 , uo_expected = ty_expected'
556 , uo_thing = Nothing }
557
558 tcSubTypeO :: CtOrigin -- ^ of the actual type
559 -> UserTypeCtxt -- ^ of the expected type
560 -> TcSigmaType
561 -> ExpSigmaType
562 -> TcM HsWrapper
563 tcSubTypeO origin ctxt ty_actual ty_expected
564 = addSubTypeCtxt ty_actual ty_expected $
565 do { traceTc "tcSubType" (vcat [ pprCtOrigin origin
566 , pprUserTypeCtxt ctxt
567 , ppr ty_actual
568 , ppr ty_expected ])
569 ; tc_sub_type eq_orig origin ctxt ty_actual ty_expected }
570 where
571 eq_orig | TypeEqOrigin {} <- origin = origin
572 | otherwise
573 = TypeEqOrigin { uo_actual = ty_actual
574 , uo_expected = ty_expected
575 , uo_thing = Nothing }
576
577 tcSubTypeDS :: Outputable a => UserTypeCtxt -> Maybe a -- ^ has type ty_actual
578 -> TcSigmaType -> ExpRhoType -> TcM HsWrapper
579 -- Just like tcSubType, but with the additional precondition that
580 -- ty_expected is deeply skolemised (hence "DS")
581 tcSubTypeDS ctxt m_expr ty_actual ty_expected
582 = addSubTypeCtxt ty_actual ty_expected $
583 tcSubTypeDS_NC ctxt m_expr ty_actual ty_expected
584
585 -- | Like 'tcSubTypeDS', but takes a 'CtOrigin' to use when instantiating
586 -- the "actual" type
587 tcSubTypeDS_O :: Outputable a
588 => CtOrigin -> UserTypeCtxt
589 -> Maybe a -> TcSigmaType -> ExpRhoType
590 -> TcM HsWrapper
591 tcSubTypeDS_O orig ctxt maybe_thing ty_actual ty_expected
592 = addSubTypeCtxt ty_actual ty_expected $
593 do { traceTc "tcSubTypeDS_O" (vcat [ pprCtOrigin orig
594 , pprUserTypeCtxt ctxt
595 , ppr ty_actual
596 , ppr ty_expected ])
597 ; tcSubTypeDS_NC_O orig ctxt maybe_thing ty_actual ty_expected }
598
599 addSubTypeCtxt :: TcType -> ExpType -> TcM a -> TcM a
600 addSubTypeCtxt ty_actual ty_expected thing_inside
601 | isRhoTy ty_actual -- If there is no polymorphism involved, the
602 , isRhoExpTy ty_expected -- TypeEqOrigin stuff (added by the _NC functions)
603 = thing_inside -- gives enough context by itself
604 | otherwise
605 = addErrCtxtM mk_msg thing_inside
606 where
607 mk_msg tidy_env
608 = do { (tidy_env, ty_actual) <- zonkTidyTcType tidy_env ty_actual
609 -- might not be filled if we're debugging. ugh.
610 ; mb_ty_expected <- readExpType_maybe ty_expected
611 ; (tidy_env, ty_expected) <- case mb_ty_expected of
612 Just ty -> second mkCheckExpType <$>
613 zonkTidyTcType tidy_env ty
614 Nothing -> return (tidy_env, ty_expected)
615 ; ty_expected <- readExpType ty_expected
616 ; (tidy_env, ty_expected) <- zonkTidyTcType tidy_env ty_expected
617 ; let msg = vcat [ hang (text "When checking that:")
618 4 (ppr ty_actual)
619 , nest 2 (hang (text "is more polymorphic than:")
620 2 (ppr ty_expected)) ]
621 ; return (tidy_env, msg) }
622
623 ---------------
624 -- The "_NC" variants do not add a typechecker-error context;
625 -- the caller is assumed to do that
626
627 tcSubType_NC :: UserTypeCtxt -> TcSigmaType -> ExpSigmaType -> TcM HsWrapper
628 tcSubType_NC ctxt ty_actual ty_expected
629 = do { traceTc "tcSubType_NC" (vcat [pprUserTypeCtxt ctxt, ppr ty_actual, ppr ty_expected])
630 ; tc_sub_type origin origin ctxt ty_actual ty_expected }
631 where
632 origin = TypeEqOrigin { uo_actual = ty_actual
633 , uo_expected = ty_expected
634 , uo_thing = Nothing }
635
636 tcSubTypeDS_NC :: Outputable a
637 => UserTypeCtxt
638 -> Maybe a -- ^ If present, this has type ty_actual
639 -> TcSigmaType -> ExpRhoType -> TcM HsWrapper
640 tcSubTypeDS_NC ctxt maybe_thing ty_actual ty_expected
641 = do { traceTc "tcSubTypeDS_NC" (vcat [pprUserTypeCtxt ctxt, ppr ty_actual, ppr ty_expected])
642 ; tcSubTypeDS_NC_O origin ctxt maybe_thing ty_actual ty_expected }
643 where
644 origin = TypeEqOrigin { uo_actual = ty_actual
645 , uo_expected = ty_expected
646 , uo_thing = mkErrorThing <$> maybe_thing }
647
648 tcSubTypeDS_NC_O :: Outputable a
649 => CtOrigin -- origin used for instantiation only
650 -> UserTypeCtxt
651 -> Maybe a
652 -> TcSigmaType -> ExpRhoType -> TcM HsWrapper
653 -- Just like tcSubType, but with the additional precondition that
654 -- ty_expected is deeply skolemised
655 tcSubTypeDS_NC_O inst_orig ctxt m_thing ty_actual et
656 = uExpTypeX eq_orig ty_actual et
657 (return . mkWpCastN)
658 (tc_sub_type_ds eq_orig inst_orig ctxt ty_actual)
659 where
660 eq_orig = TypeEqOrigin { uo_actual = ty_actual, uo_expected = et
661 , uo_thing = mkErrorThing <$> m_thing }
662
663 ---------------
664 tc_sub_type :: CtOrigin -- origin used when calling uType
665 -> CtOrigin -- origin used when instantiating
666 -> UserTypeCtxt -> TcSigmaType -> ExpSigmaType -> TcM HsWrapper
667 tc_sub_type eq_orig inst_orig ctxt ty_actual et
668 = uExpTypeX eq_orig ty_actual et
669 (return . mkWpCastN)
670 (tc_sub_tc_type eq_orig inst_orig ctxt ty_actual)
671
672 tc_sub_tc_type :: CtOrigin -- used when calling uType
673 -> CtOrigin -- used when instantiating
674 -> UserTypeCtxt -> TcSigmaType -> TcSigmaType -> TcM HsWrapper
675 tc_sub_tc_type eq_orig inst_orig ctxt ty_actual ty_expected
676 | Just tv_actual <- tcGetTyVar_maybe ty_actual -- See Note [Higher rank types]
677 = do { lookup_res <- lookupTcTyVar tv_actual
678 ; case lookup_res of
679 Filled ty_actual' -> tc_sub_tc_type eq_orig inst_orig
680 ctxt ty_actual' ty_expected
681
682 -- It's tempting to see if tv_actual can unify with a polytype
683 -- and, if so, call uType; otherwise, skolemise first. But this
684 -- is wrong, because skolemising will bump the TcLevel and the
685 -- unification will fail anyway.
686 -- It's also tempting to call uUnfilledVar directly, but calling
687 -- uType seems safer in the presence of possible refactoring
688 -- later.
689 Unfilled _ -> mkWpCastN <$>
690 uType eq_orig TypeLevel ty_actual ty_expected }
691
692 | otherwise -- See Note [Deep skolemisation]
693 = do { (sk_wrap, inner_wrap) <- tcSkolemise ctxt ty_expected $
694 \ _ sk_rho ->
695 tc_sub_type_ds eq_orig inst_orig ctxt
696 ty_actual sk_rho
697 ; return (sk_wrap <.> inner_wrap) }
698
699 ---------------
700 tc_sub_type_ds :: CtOrigin -- used when calling uType
701 -> CtOrigin -- used when instantiating
702 -> UserTypeCtxt -> TcSigmaType -> TcRhoType -> TcM HsWrapper
703 -- Just like tcSubType, but with the additional precondition that
704 -- ty_expected is deeply skolemised
705 tc_sub_type_ds eq_orig inst_orig ctxt ty_actual ty_expected
706 = go ty_actual ty_expected
707 where
708 go ty_a ty_e | Just ty_a' <- coreView ty_a = go ty_a' ty_e
709 | Just ty_e' <- coreView ty_e = go ty_a ty_e'
710
711 go (TyVarTy tv_a) ty_e
712 = do { lookup_res <- lookupTcTyVar tv_a
713 ; case lookup_res of
714 Filled ty_a' ->
715 do { traceTc "tcSubTypeDS_NC_O following filled act meta-tyvar:"
716 (ppr tv_a <+> text "-->" <+> ppr ty_a')
717 ; tc_sub_type_ds eq_orig inst_orig ctxt ty_a' ty_e }
718 Unfilled _ -> unify }
719
720
721 go ty_a (TyVarTy tv_e)
722 = do { dflags <- getDynFlags
723 ; tclvl <- getTcLevel
724 ; lookup_res <- lookupTcTyVar tv_e
725 ; case lookup_res of
726 Filled ty_e' ->
727 do { traceTc "tcSubTypeDS_NC_O following filled exp meta-tyvar:"
728 (ppr tv_e <+> text "-->" <+> ppr ty_e')
729 ; tc_sub_tc_type eq_orig inst_orig ctxt ty_a ty_e' }
730 Unfilled details
731 | canUnifyWithPolyType dflags details
732 && isTouchableMetaTyVar tclvl tv_e -- don't want skolems here
733 -> unify
734
735 -- We've avoided instantiating ty_actual just in case ty_expected is
736 -- polymorphic. But we've now assiduously determined that it is *not*
737 -- polymorphic. So instantiate away. This is needed for e.g. test
738 -- typecheck/should_compile/T4284.
739 | otherwise
740 -> inst_and_unify }
741
742 go (ForAllTy (Anon act_arg) act_res) (ForAllTy (Anon exp_arg) exp_res)
743 | not (isPredTy act_arg)
744 , not (isPredTy exp_arg)
745 = -- See Note [Co/contra-variance of subsumption checking]
746 do { res_wrap <- tc_sub_type_ds eq_orig inst_orig ctxt act_res exp_res
747 ; arg_wrap
748 <- tc_sub_tc_type eq_orig (GivenOrigin
749 (SigSkol GenSigCtxt exp_arg))
750 ctxt exp_arg act_arg
751 ; return (mkWpFun arg_wrap res_wrap exp_arg exp_res) }
752 -- arg_wrap :: exp_arg ~ act_arg
753 -- res_wrap :: act-res ~ exp_res
754
755 go ty_a ty_e
756 | let (tvs, theta, _) = tcSplitSigmaTy ty_a
757 , not (null tvs && null theta)
758 = do { (in_wrap, in_rho) <- topInstantiate inst_orig ty_a
759 ; body_wrap <- tc_sub_type_ds
760 (eq_orig { uo_actual = in_rho
761 , uo_expected =
762 mkCheckExpType ty_expected })
763 inst_orig ctxt in_rho ty_e
764 ; return (body_wrap <.> in_wrap) }
765
766 | otherwise -- Revert to unification
767 = inst_and_unify
768 -- It's still possible that ty_actual has nested foralls. Instantiate
769 -- these, as there's no way unification will succeed with them in.
770 -- See typecheck/should_compile/T11305 for an example of when this
771 -- is important. The problem is that we're checking something like
772 -- a -> forall b. b -> b <= alpha beta gamma
773 -- where we end up with alpha := (->)
774
775 inst_and_unify = do { (wrap, rho_a) <- deeplyInstantiate inst_orig ty_actual
776
777 -- if we haven't recurred through an arrow, then
778 -- the eq_orig will list ty_actual. In this case,
779 -- we want to update the origin to reflect the
780 -- instantiation. If we *have* recurred through
781 -- an arrow, it's better not to update.
782 ; let eq_orig' = case eq_orig of
783 TypeEqOrigin { uo_actual = orig_ty_actual }
784 | orig_ty_actual `tcEqType` ty_actual
785 , not (isIdHsWrapper wrap)
786 -> eq_orig { uo_actual = rho_a }
787 _ -> eq_orig
788
789 ; cow <- uType eq_orig' TypeLevel rho_a ty_expected
790 ; return (mkWpCastN cow <.> wrap) }
791
792
793 -- use versions without synonyms expanded
794 unify = mkWpCastN <$> uType eq_orig TypeLevel ty_actual ty_expected
795
796 -----------------
797 -- needs both un-type-checked (for origins) and type-checked (for wrapping)
798 -- expressions
799 tcWrapResult :: HsExpr Name -> HsExpr TcId -> TcSigmaType -> ExpRhoType
800 -> TcM (HsExpr TcId)
801 tcWrapResult rn_expr = tcWrapResultO (exprCtOrigin rn_expr)
802
803 -- | Sometimes we don't have a @HsExpr Name@ to hand, and this is more
804 -- convenient.
805 tcWrapResultO :: CtOrigin -> HsExpr TcId -> TcSigmaType -> ExpRhoType
806 -> TcM (HsExpr TcId)
807 tcWrapResultO orig expr actual_ty res_ty
808 = do { traceTc "tcWrapResult" (vcat [ text "Actual: " <+> ppr actual_ty
809 , text "Expected:" <+> ppr res_ty ])
810 ; cow <- tcSubTypeDS_NC_O orig GenSigCtxt
811 (Just expr) actual_ty res_ty
812 ; return (mkHsWrap cow expr) }
813
814 -----------------------------------
815 wrapFunResCoercion
816 :: [TcType] -- Type of args
817 -> HsWrapper -- HsExpr a -> HsExpr b
818 -> TcM HsWrapper -- HsExpr (arg_tys -> a) -> HsExpr (arg_tys -> b)
819 wrapFunResCoercion arg_tys co_fn_res
820 | isIdHsWrapper co_fn_res
821 = return idHsWrapper
822 | null arg_tys
823 = return co_fn_res
824 | otherwise
825 = do { arg_ids <- newSysLocalIds (fsLit "sub") arg_tys
826 ; return (mkWpLams arg_ids <.> co_fn_res <.> mkWpEvVarApps arg_ids) }
827
828 -----------------------------------
829 -- | Infer a type using a fresh ExpType
830 -- See also Note [ExpType] in TcMType
831 tcInfer :: (ExpRhoType -> TcM a) -> TcM (a, TcType)
832 tcInfer tc_check
833 = do { res_ty <- newOpenInferExpType
834 ; result <- tc_check res_ty
835 ; res_ty <- readExpType res_ty
836 ; return (result, res_ty) }
837
838 {-
839 ************************************************************************
840 * *
841 \subsection{Generalisation}
842 * *
843 ************************************************************************
844 -}
845
846 -- | Take an "expected type" and strip off quantifiers to expose the
847 -- type underneath, binding the new skolems for the @thing_inside@.
848 -- The returned 'HsWrapper' has type @specific_ty -> expected_ty@.
849 tcSkolemise :: UserTypeCtxt -> TcSigmaType
850 -> ([TcTyVar] -> TcType -> TcM result)
851 -- ^ These are only ever used for scoped type variables.
852 -> TcM (HsWrapper, result)
853 -- ^ The expression has type: spec_ty -> expected_ty
854
855 tcSkolemise ctxt expected_ty thing_inside
856 -- We expect expected_ty to be a forall-type
857 -- If not, the call is a no-op
858 = do { traceTc "tcSkolemise" Outputable.empty
859 ; (wrap, tvs', given, rho') <- deeplySkolemise expected_ty
860
861 ; lvl <- getTcLevel
862 ; when debugIsOn $
863 traceTc "tcSkolemise" $ vcat [
864 ppr lvl,
865 text "expected_ty" <+> ppr expected_ty,
866 text "inst tyvars" <+> ppr tvs',
867 text "given" <+> ppr given,
868 text "inst type" <+> ppr rho' ]
869
870 -- Generally we must check that the "forall_tvs" havn't been constrained
871 -- The interesting bit here is that we must include the free variables
872 -- of the expected_ty. Here's an example:
873 -- runST (newVar True)
874 -- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
875 -- for (newVar True), with s fresh. Then we unify with the runST's arg type
876 -- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
877 -- So now s' isn't unconstrained because it's linked to a.
878 --
879 -- However [Oct 10] now that the untouchables are a range of
880 -- TcTyVars, all this is handled automatically with no need for
881 -- extra faffing around
882
883 -- Use the *instantiated* type in the SkolemInfo
884 -- so that the names of displayed type variables line up
885 ; let skol_info = SigSkol ctxt (mkFunTys (map varType given) rho')
886
887 ; (ev_binds, result) <- checkConstraints skol_info tvs' given $
888 thing_inside tvs' rho'
889
890 ; return (wrap <.> mkWpLet ev_binds, result) }
891 -- The ev_binds returned by checkConstraints is very
892 -- often empty, in which case mkWpLet is a no-op
893
894 -- | Variant of 'tcSkolemise' that takes an ExpType
895 tcSkolemiseET :: UserTypeCtxt -> ExpSigmaType
896 -> (ExpRhoType -> TcM result)
897 -> TcM (HsWrapper, result)
898 tcSkolemiseET _ et@(Infer {}) thing_inside
899 = (idHsWrapper, ) <$> thing_inside et
900 tcSkolemiseET ctxt (Check ty) thing_inside
901 = tcSkolemise ctxt ty $ \_ -> thing_inside . mkCheckExpType
902
903 checkConstraints :: SkolemInfo
904 -> [TcTyVar] -- Skolems
905 -> [EvVar] -- Given
906 -> TcM result
907 -> TcM (TcEvBinds, result)
908
909 checkConstraints skol_info skol_tvs given thing_inside
910 = do { (implics, ev_binds, result)
911 <- buildImplication skol_info skol_tvs given thing_inside
912 ; emitImplications implics
913 ; return (ev_binds, result) }
914
915 buildImplication :: SkolemInfo
916 -> [TcTyVar] -- Skolems
917 -> [EvVar] -- Given
918 -> TcM result
919 -> TcM (Bag Implication, TcEvBinds, result)
920 buildImplication skol_info skol_tvs given thing_inside
921 = do { tc_lvl <- getTcLevel
922 ; deferred_type_errors <- goptM Opt_DeferTypeErrors <||>
923 goptM Opt_DeferTypedHoles
924 ; if null skol_tvs && null given && (not deferred_type_errors ||
925 not (isTopTcLevel tc_lvl))
926 then do { res <- thing_inside
927 ; return (emptyBag, emptyTcEvBinds, res) }
928 -- Fast path. We check every function argument with
929 -- tcPolyExpr, which uses tcSkolemise and hence checkConstraints.
930 -- But with the solver producing unlifted equalities, we need
931 -- to have an EvBindsVar for them when they might be deferred to
932 -- runtime. Otherwise, they end up as top-level unlifted bindings,
933 -- which are verboten. See also Note [Deferred errors for coercion holes]
934 -- in TcErrors.
935 else
936 do { (tclvl, wanted, result) <- pushLevelAndCaptureConstraints thing_inside
937 ; (implics, ev_binds) <- buildImplicationFor tclvl skol_info skol_tvs given wanted
938 ; return (implics, ev_binds, result) }}
939
940 buildImplicationFor :: TcLevel -> SkolemInfo -> [TcTyVar]
941 -> [EvVar] -> WantedConstraints
942 -> TcM (Bag Implication, TcEvBinds)
943 buildImplicationFor tclvl skol_info skol_tvs given wanted
944 | isEmptyWC wanted && null given
945 -- Optimisation : if there are no wanteds, and no givens
946 -- don't generate an implication at all.
947 -- Reason for the (null given): we don't want to lose
948 -- the "inaccessible alternative" error check
949 = return (emptyBag, emptyTcEvBinds)
950
951 | otherwise
952 = ASSERT2( all isTcTyVar skol_tvs, ppr skol_tvs )
953 ASSERT2( all isSkolemTyVar skol_tvs, ppr skol_tvs )
954 do { ev_binds_var <- newTcEvBinds
955 ; env <- getLclEnv
956 ; let implic = Implic { ic_tclvl = tclvl
957 , ic_skols = skol_tvs
958 , ic_no_eqs = False
959 , ic_given = given
960 , ic_wanted = wanted
961 , ic_status = IC_Unsolved
962 , ic_binds = Just ev_binds_var
963 , ic_env = env
964 , ic_info = skol_info }
965
966 ; return (unitBag implic, TcEvBinds ev_binds_var) }
967
968 {-
969 ************************************************************************
970 * *
971 Boxy unification
972 * *
973 ************************************************************************
974
975 The exported functions are all defined as versions of some
976 non-exported generic functions.
977 -}
978
979 -- | Unify two types, discarding a resultant coercion. Any constraints
980 -- generated will still need to be solved, however.
981 unifyType_ :: Outputable a => Maybe a -- ^ If present, has type 'ty1'
982 -> TcTauType -> TcTauType -> TcM ()
983 unifyType_ thing ty1 ty2 = void $ unifyType thing ty1 ty2
984
985 unifyType :: Outputable a => Maybe a -- ^ If present, has type 'ty1'
986 -> TcTauType -> TcTauType -> TcM TcCoercionN
987 -- Actual and expected types
988 -- Returns a coercion : ty1 ~ ty2
989 unifyType thing ty1 ty2 = uType origin TypeLevel ty1 ty2
990 where
991 origin = TypeEqOrigin { uo_actual = ty1, uo_expected = mkCheckExpType ty2
992 , uo_thing = mkErrorThing <$> thing }
993
994 -- | Variant of 'unifyType' that takes an 'ExpType' as its second type
995 unifyExpType :: Outputable a => Maybe a
996 -> TcTauType -> ExpType -> TcM TcCoercionN
997 unifyExpType mb_thing ty1 ty2
998 = uExpType ty_orig ty1 ty2
999 where
1000 ty_orig = TypeEqOrigin { uo_actual = ty1
1001 , uo_expected = ty2
1002 , uo_thing = mkErrorThing <$> mb_thing }
1003
1004 -- | Use this instead of 'Nothing' when calling 'unifyType' without
1005 -- a good "thing" (where the "thing" has the "actual" type passed in)
1006 -- This has an 'Outputable' instance, avoiding amgiguity problems.
1007 noThing :: Maybe (HsExpr Name)
1008 noThing = Nothing
1009
1010 unifyKind :: Outputable a => Maybe a -> TcKind -> TcKind -> TcM CoercionN
1011 unifyKind thing ty1 ty2 = uType origin KindLevel ty1 ty2
1012 where origin = TypeEqOrigin { uo_actual = ty1, uo_expected = mkCheckExpType ty2
1013 , uo_thing = mkErrorThing <$> thing }
1014
1015 ---------------
1016 unifyPred :: PredType -> PredType -> TcM TcCoercionN
1017 -- Actual and expected types
1018 unifyPred = unifyType noThing
1019
1020 ---------------
1021 unifyTheta :: TcThetaType -> TcThetaType -> TcM [TcCoercionN]
1022 -- Actual and expected types
1023 unifyTheta theta1 theta2
1024 = do { checkTc (equalLength theta1 theta2)
1025 (vcat [text "Contexts differ in length",
1026 nest 2 $ parens $ text "Use RelaxedPolyRec to allow this"])
1027 ; zipWithM unifyPred theta1 theta2 }
1028
1029 {-
1030 %************************************************************************
1031 %* *
1032 uType and friends
1033 %* *
1034 %************************************************************************
1035
1036 uType is the heart of the unifier.
1037 -}
1038
1039 uExpType :: CtOrigin -> TcType -> ExpType -> TcM CoercionN
1040 uExpType orig ty1 et
1041 = uExpTypeX orig ty1 et return $
1042 uType orig TypeLevel ty1
1043
1044 -- | Tries to unify with an ExpType. If the ExpType is filled in, calls the first
1045 -- continuation with the produced coercion. Otherwise, calls the second
1046 -- continuation. This can happen either with a Check or with an untouchable
1047 -- ExpType that reverts to a tau-type. See Note [TcLevel of ExpType]
1048 uExpTypeX :: CtOrigin -> TcType -> ExpType
1049 -> (TcCoercionN -> TcM a) -- Infer case, co :: TcType ~N ExpType
1050 -> (TcType -> TcM a) -- Check / untouchable case
1051 -> TcM a
1052 uExpTypeX orig ty1 et@(Infer _ tc_lvl ki _) coercion_cont type_cont
1053 = do { cur_lvl <- getTcLevel
1054 ; if cur_lvl `sameDepthAs` tc_lvl
1055 then do { ki_co <- uType kind_orig KindLevel (typeKind ty1) ki
1056 ; writeExpType et (ty1 `mkCastTy` ki_co)
1057 ; coercion_cont $ mkTcNomReflCo ty1 `mkTcCoherenceRightCo` ki_co }
1058 else do { traceTc "Preventing writing to untouchable ExpType" empty
1059 ; tau <- expTypeToType et -- See Note [TcLevel of ExpType]
1060 ; type_cont tau }}
1061 where
1062 kind_orig = KindEqOrigin ty1 Nothing orig (Just TypeLevel)
1063 uExpTypeX _ _ (Check ty2) _ type_cont
1064 = type_cont ty2
1065
1066 ------------
1067 uType, uType_defer
1068 :: CtOrigin
1069 -> TypeOrKind
1070 -> TcType -- ty1 is the *actual* type
1071 -> TcType -- ty2 is the *expected* type
1072 -> TcM Coercion
1073
1074 --------------
1075 -- It is always safe to defer unification to the main constraint solver
1076 -- See Note [Deferred unification]
1077 uType_defer origin t_or_k ty1 ty2
1078 = do { hole <- newCoercionHole
1079 ; loc <- getCtLocM origin (Just t_or_k)
1080 ; emitSimple $ mkNonCanonical $
1081 CtWanted { ctev_dest = HoleDest hole
1082 , ctev_pred = mkPrimEqPred ty1 ty2
1083 , ctev_loc = loc }
1084
1085 -- Error trace only
1086 -- NB. do *not* call mkErrInfo unless tracing is on, because
1087 -- it is hugely expensive (#5631)
1088 ; whenDOptM Opt_D_dump_tc_trace $ do
1089 { ctxt <- getErrCtxt
1090 ; doc <- mkErrInfo emptyTidyEnv ctxt
1091 ; traceTc "utype_defer" (vcat [ppr hole, ppr ty1,
1092 ppr ty2, pprCtOrigin origin, doc])
1093 }
1094 ; return (mkHoleCo hole Nominal ty1 ty2) }
1095
1096 --------------
1097 uType origin t_or_k orig_ty1 orig_ty2
1098 = do { tclvl <- getTcLevel
1099 ; traceTc "u_tys " $ vcat
1100 [ text "tclvl" <+> ppr tclvl
1101 , sep [ ppr orig_ty1, text "~", ppr orig_ty2]
1102 , pprCtOrigin origin]
1103 ; co <- go orig_ty1 orig_ty2
1104 ; if isReflCo co
1105 then traceTc "u_tys yields no coercion" Outputable.empty
1106 else traceTc "u_tys yields coercion:" (ppr co)
1107 ; return co }
1108 where
1109 go :: TcType -> TcType -> TcM Coercion
1110 -- The arguments to 'go' are always semantically identical
1111 -- to orig_ty{1,2} except for looking through type synonyms
1112
1113 -- Variables; go for uVar
1114 -- Note that we pass in *original* (before synonym expansion),
1115 -- so that type variables tend to get filled in with
1116 -- the most informative version of the type
1117 go (TyVarTy tv1) ty2
1118 = do { lookup_res <- lookupTcTyVar tv1
1119 ; case lookup_res of
1120 Filled ty1 -> do { traceTc "found filled tyvar" (ppr tv1 <+> text ":->" <+> ppr ty1)
1121 ; go ty1 ty2 }
1122 Unfilled ds1 -> uUnfilledVar origin t_or_k NotSwapped tv1 ds1 ty2 }
1123 go ty1 (TyVarTy tv2)
1124 = do { lookup_res <- lookupTcTyVar tv2
1125 ; case lookup_res of
1126 Filled ty2 -> do { traceTc "found filled tyvar" (ppr tv2 <+> text ":->" <+> ppr ty2)
1127 ; go ty1 ty2 }
1128 Unfilled ds2 -> uUnfilledVar origin t_or_k IsSwapped tv2 ds2 ty1 }
1129
1130 -- See Note [Expanding synonyms during unification]
1131 go ty1@(TyConApp tc1 []) (TyConApp tc2 [])
1132 | tc1 == tc2
1133 = return $ mkReflCo Nominal ty1
1134
1135 -- See Note [Expanding synonyms during unification]
1136 --
1137 -- Also NB that we recurse to 'go' so that we don't push a
1138 -- new item on the origin stack. As a result if we have
1139 -- type Foo = Int
1140 -- and we try to unify Foo ~ Bool
1141 -- we'll end up saying "can't match Foo with Bool"
1142 -- rather than "can't match "Int with Bool". See Trac #4535.
1143 go ty1 ty2
1144 | Just ty1' <- coreView ty1 = go ty1' ty2
1145 | Just ty2' <- coreView ty2 = go ty1 ty2'
1146
1147 go (CastTy t1 co1) t2
1148 = do { co_tys <- go t1 t2
1149 ; return (mkCoherenceLeftCo co_tys co1) }
1150
1151 go t1 (CastTy t2 co2)
1152 = do { co_tys <- go t1 t2
1153 ; return (mkCoherenceRightCo co_tys co2) }
1154
1155 -- Functions (or predicate functions) just check the two parts
1156 go (ForAllTy (Anon fun1) arg1) (ForAllTy (Anon fun2) arg2)
1157 = do { co_l <- uType origin t_or_k fun1 fun2
1158 ; co_r <- uType origin t_or_k arg1 arg2
1159 ; return $ mkFunCo Nominal co_l co_r }
1160
1161 -- Always defer if a type synonym family (type function)
1162 -- is involved. (Data families behave rigidly.)
1163 go ty1@(TyConApp tc1 _) ty2
1164 | isTypeFamilyTyCon tc1 = defer ty1 ty2
1165 go ty1 ty2@(TyConApp tc2 _)
1166 | isTypeFamilyTyCon tc2 = defer ty1 ty2
1167
1168 go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
1169 -- See Note [Mismatched type lists and application decomposition]
1170 | tc1 == tc2, length tys1 == length tys2
1171 = ASSERT2( isGenerativeTyCon tc1 Nominal, ppr tc1 )
1172 do { cos <- zipWithM (uType origin t_or_k) tys1 tys2
1173 ; return $ mkTyConAppCo Nominal tc1 cos }
1174
1175 go (LitTy m) ty@(LitTy n)
1176 | m == n
1177 = return $ mkNomReflCo ty
1178
1179 -- See Note [Care with type applications]
1180 -- Do not decompose FunTy against App;
1181 -- it's often a type error, so leave it for the constraint solver
1182 go (AppTy s1 t1) (AppTy s2 t2)
1183 = go_app s1 t1 s2 t2
1184
1185 go (AppTy s1 t1) (TyConApp tc2 ts2)
1186 | Just (ts2', t2') <- snocView ts2
1187 = ASSERT( mightBeUnsaturatedTyCon tc2 )
1188 go_app s1 t1 (TyConApp tc2 ts2') t2'
1189
1190 go (TyConApp tc1 ts1) (AppTy s2 t2)
1191 | Just (ts1', t1') <- snocView ts1
1192 = ASSERT( mightBeUnsaturatedTyCon tc1 )
1193 go_app (TyConApp tc1 ts1') t1' s2 t2
1194
1195 go (CoercionTy co1) (CoercionTy co2)
1196 = do { let ty1 = coercionType co1
1197 ty2 = coercionType co2
1198 ; kco <- uType (KindEqOrigin orig_ty1 (Just orig_ty2) origin
1199 (Just t_or_k))
1200 KindLevel
1201 ty1 ty2
1202 ; return $ mkProofIrrelCo Nominal kco co1 co2 }
1203
1204 -- Anything else fails
1205 -- E.g. unifying for-all types, which is relative unusual
1206 go ty1 ty2 = defer ty1 ty2
1207
1208 ------------------
1209 defer ty1 ty2 -- See Note [Check for equality before deferring]
1210 | ty1 `tcEqType` ty2 = return (mkNomReflCo ty1)
1211 | otherwise = uType_defer origin t_or_k ty1 ty2
1212
1213 ------------------
1214 go_app s1 t1 s2 t2
1215 = do { co_s <- uType origin t_or_k s1 s2
1216 ; co_t <- uType origin t_or_k t1 t2
1217 ; return $ mkAppCo co_s co_t }
1218
1219 {- Note [Check for equality before deferring]
1220 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1221 Particularly in ambiguity checks we can get equalities like (ty ~ ty).
1222 If ty involves a type function we may defer, which isn't very sensible.
1223 An egregious example of this was in test T9872a, which has a type signature
1224 Proxy :: Proxy (Solutions Cubes)
1225 Doing the ambiguity check on this signature generates the equality
1226 Solutions Cubes ~ Solutions Cubes
1227 and currently the constraint solver normalises both sides at vast cost.
1228 This little short-cut in 'defer' helps quite a bit.
1229
1230 Note [Care with type applications]
1231 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1232 Note: type applications need a bit of care!
1233 They can match FunTy and TyConApp, so use splitAppTy_maybe
1234 NB: we've already dealt with type variables and Notes,
1235 so if one type is an App the other one jolly well better be too
1236
1237 Note [Mismatched type lists and application decomposition]
1238 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1239 When we find two TyConApps, you might think that the argument lists
1240 are guaranteed equal length. But they aren't. Consider matching
1241 w (T x) ~ Foo (T x y)
1242 We do match (w ~ Foo) first, but in some circumstances we simply create
1243 a deferred constraint; and then go ahead and match (T x ~ T x y).
1244 This came up in Trac #3950.
1245
1246 So either
1247 (a) either we must check for identical argument kinds
1248 when decomposing applications,
1249
1250 (b) or we must be prepared for ill-kinded unification sub-problems
1251
1252 Currently we adopt (b) since it seems more robust -- no need to maintain
1253 a global invariant.
1254
1255 Note [Expanding synonyms during unification]
1256 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1257 We expand synonyms during unification, but:
1258 * We expand *after* the variable case so that we tend to unify
1259 variables with un-expanded type synonym. This just makes it
1260 more likely that the inferred types will mention type synonyms
1261 understandable to the user
1262
1263 * We expand *before* the TyConApp case. For example, if we have
1264 type Phantom a = Int
1265 and are unifying
1266 Phantom Int ~ Phantom Char
1267 it is *wrong* to unify Int and Char.
1268
1269 * The problem case immediately above can happen only with arguments
1270 to the tycon. So we check for nullary tycons *before* expanding.
1271 This is particularly helpful when checking (* ~ *), because * is
1272 now a type synonym.
1273
1274 Note [Deferred Unification]
1275 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1276 We may encounter a unification ty1 ~ ty2 that cannot be performed syntactically,
1277 and yet its consistency is undetermined. Previously, there was no way to still
1278 make it consistent. So a mismatch error was issued.
1279
1280 Now these unifications are deferred until constraint simplification, where type
1281 family instances and given equations may (or may not) establish the consistency.
1282 Deferred unifications are of the form
1283 F ... ~ ...
1284 or x ~ ...
1285 where F is a type function and x is a type variable.
1286 E.g.
1287 id :: x ~ y => x -> y
1288 id e = e
1289
1290 involves the unification x = y. It is deferred until we bring into account the
1291 context x ~ y to establish that it holds.
1292
1293 If available, we defer original types (rather than those where closed type
1294 synonyms have already been expanded via tcCoreView). This is, as usual, to
1295 improve error messages.
1296
1297
1298 ************************************************************************
1299 * *
1300 uVar and friends
1301 * *
1302 ************************************************************************
1303
1304 @uVar@ is called when at least one of the types being unified is a
1305 variable. It does {\em not} assume that the variable is a fixed point
1306 of the substitution; rather, notice that @uVar@ (defined below) nips
1307 back into @uTys@ if it turns out that the variable is already bound.
1308 -}
1309
1310 uUnfilledVar :: CtOrigin
1311 -> TypeOrKind
1312 -> SwapFlag
1313 -> TcTyVar -> TcTyVarDetails -- Tyvar 1
1314 -> TcTauType -- Type 2
1315 -> TcM Coercion
1316 -- "Unfilled" means that the variable is definitely not a filled-in meta tyvar
1317 -- It might be a skolem, or untouchable, or meta
1318
1319 uUnfilledVar origin t_or_k swapped tv1 details1 (TyVarTy tv2)
1320 | tv1 == tv2 -- Same type variable => no-op
1321 = return (mkNomReflCo (mkTyVarTy tv1))
1322
1323 | otherwise -- Distinct type variables
1324 = do { lookup2 <- lookupTcTyVar tv2
1325 ; case lookup2 of
1326 Filled ty2'
1327 -> uUnfilledVar origin t_or_k swapped tv1 details1 ty2'
1328 Unfilled details2
1329 -> uUnfilledVars origin t_or_k swapped tv1 details1 tv2 details2
1330 }
1331
1332 uUnfilledVar origin t_or_k swapped tv1 details1 non_var_ty2
1333 -- ty2 is not a type variable
1334 = case details1 of
1335 MetaTv { mtv_ref = ref1 }
1336 -> do { dflags <- getDynFlags
1337 ; mb_ty2' <- checkTauTvUpdate dflags origin t_or_k tv1 non_var_ty2
1338 ; case mb_ty2' of
1339 Just (ty2', co_k) -> maybe_sym swapped <$>
1340 updateMeta tv1 ref1 ty2' co_k
1341 Nothing -> do { traceTc "Occ/type-family defer"
1342 (ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1)
1343 $$ ppr non_var_ty2 $$ ppr (typeKind non_var_ty2))
1344 ; defer }
1345 }
1346
1347 _other -> do { traceTc "Skolem defer" (ppr tv1); defer } -- Skolems of all sorts
1348 where
1349 defer = unSwap swapped (uType_defer origin t_or_k) (mkTyVarTy tv1) non_var_ty2
1350 -- Occurs check or an untouchable: just defer
1351 -- NB: occurs check isn't necessarily fatal:
1352 -- eg tv1 occured in type family parameter
1353
1354 ----------------
1355 uUnfilledVars :: CtOrigin
1356 -> TypeOrKind
1357 -> SwapFlag
1358 -> TcTyVar -> TcTyVarDetails -- Tyvar 1
1359 -> TcTyVar -> TcTyVarDetails -- Tyvar 2
1360 -> TcM Coercion
1361 -- Invarant: The type variables are distinct,
1362 -- Neither is filled in yet
1363
1364 uUnfilledVars origin t_or_k swapped tv1 details1 tv2 details2
1365 = do { traceTc "uUnfilledVars for" (ppr tv1 <+> text "and" <+> ppr tv2)
1366 ; traceTc "uUnfilledVars" ( text "trying to unify" <+> ppr k1
1367 <+> text "with" <+> ppr k2)
1368 ; co_k <- uType kind_origin KindLevel k1 k2
1369 ; let no_swap ref = maybe_sym swapped <$>
1370 updateMeta tv1 ref ty2 (mkSymCo co_k)
1371 do_swap ref = maybe_sym (flipSwap swapped) <$>
1372 updateMeta tv2 ref ty1 co_k
1373 ; case (details1, details2) of
1374 { ( MetaTv { mtv_info = i1, mtv_ref = ref1 }
1375 , MetaTv { mtv_info = i2, mtv_ref = ref2 } )
1376 | nicer_to_update_tv1 tv1 i1 i2 -> no_swap ref1
1377 | otherwise -> do_swap ref2
1378 ; (MetaTv { mtv_ref = ref1 }, _) -> no_swap ref1
1379 ; (_, MetaTv { mtv_ref = ref2 }) -> do_swap ref2
1380
1381 -- Can't do it in-place, so defer
1382 -- This happens for skolems of all sorts
1383 ; _ -> do { traceTc "deferring because I can't find a meta-tyvar:"
1384 (pprTcTyVarDetails details1 <+> pprTcTyVarDetails details2)
1385 ; unSwap swapped (uType_defer origin t_or_k) ty1 ty2 } } }
1386 where
1387 k1 = tyVarKind tv1
1388 k2 = tyVarKind tv2
1389 ty1 = mkTyVarTy tv1
1390 ty2 = mkTyVarTy tv2
1391 kind_origin = KindEqOrigin ty1 (Just ty2) origin (Just t_or_k)
1392
1393 -- | apply sym iff swapped
1394 maybe_sym :: SwapFlag -> Coercion -> Coercion
1395 maybe_sym IsSwapped = mkSymCo
1396 maybe_sym NotSwapped = id
1397
1398 nicer_to_update_tv1 :: TcTyVar -> MetaInfo -> MetaInfo -> Bool
1399 nicer_to_update_tv1 _ _ SigTv = True
1400 nicer_to_update_tv1 _ SigTv _ = False
1401 -- Try not to update SigTvs; and try to update sys-y type
1402 -- variables in preference to ones gotten (say) by
1403 -- instantiating a polymorphic function with a user-written
1404 -- type sig
1405 nicer_to_update_tv1 tv1 _ _ = isSystemName (Var.varName tv1)
1406
1407 ----------------
1408 checkTauTvUpdate :: DynFlags
1409 -> CtOrigin
1410 -> TypeOrKind
1411 -> TcTyVar -- tv :: k1
1412 -> TcType -- ty :: k2
1413 -> TcM (Maybe ( TcType -- possibly-expanded ty
1414 , Coercion )) -- :: k2 ~N k1
1415 -- (checkTauTvUpdate tv ty)
1416 -- We are about to update the TauTv tv with ty.
1417 -- Check (a) that tv doesn't occur in ty (occurs check)
1418 -- (b) that kind(ty) matches kind(tv)
1419 --
1420 -- We have two possible outcomes:
1421 -- (1) Return the type to update the type variable with,
1422 -- [we know the update is ok]
1423 -- (2) Return Nothing,
1424 -- [the update might be dodgy]
1425 --
1426 -- Note that "Nothing" does not mean "definite error". For example
1427 -- type family F a
1428 -- type instance F Int = Int
1429 -- consider
1430 -- a ~ F a
1431 -- This is perfectly reasonable, if we later get a ~ Int. For now, though,
1432 -- we return Nothing, leaving it to the later constraint simplifier to
1433 -- sort matters out.
1434
1435 checkTauTvUpdate dflags origin t_or_k tv ty
1436 | SigTv <- info
1437 = ASSERT( not (isTyVarTy ty) )
1438 return Nothing
1439 | otherwise
1440 = do { ty <- zonkTcType ty
1441 ; co_k <- uType kind_origin KindLevel (typeKind ty) (tyVarKind tv)
1442 ; if | defer_me ty -> -- Quick test
1443 -- Failed quick test so try harder
1444 case occurCheckExpand dflags tv ty of
1445 OC_OK ty2 | defer_me ty2 -> return Nothing
1446 | otherwise -> return (Just (ty2, co_k))
1447 _ -> return Nothing
1448 | otherwise -> return (Just (ty, co_k)) }
1449
1450 where
1451 kind_origin = KindEqOrigin (mkTyVarTy tv) (Just ty) origin (Just t_or_k)
1452 details = tcTyVarDetails tv
1453 info = mtv_info details
1454
1455 impredicative = canUnifyWithPolyType dflags details
1456
1457 defer_me :: TcType -> Bool
1458 -- Checks for (a) occurrence of tv
1459 -- (b) type family applications
1460 -- (c) foralls
1461 -- See Note [Prevent unification with type families]
1462 -- See Note [Refactoring hazard: checkTauTvUpdate]
1463 defer_me (LitTy {}) = False
1464 defer_me (TyVarTy tv') = tv == tv' || defer_me (tyVarKind tv')
1465 defer_me (TyConApp tc tys) = isTypeFamilyTyCon tc || any defer_me tys
1466 || not (impredicative || isTauTyCon tc)
1467 defer_me (ForAllTy bndr t) = defer_me (binderType bndr) || defer_me t
1468 || (isNamedBinder bndr && not impredicative)
1469 defer_me (AppTy fun arg) = defer_me fun || defer_me arg
1470 defer_me (CastTy ty co) = defer_me ty || defer_me_co co
1471 defer_me (CoercionTy co) = defer_me_co co
1472
1473 -- We don't really care if there are type families in a coercion,
1474 -- but we still can't have an occurs-check failure
1475 defer_me_co co = tv `elemVarSet` tyCoVarsOfCo co
1476
1477 {-
1478 Note [Prevent unification with type families]
1479 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1480 We prevent unification with type families because of an uneasy compromise.
1481 It's perfectly sound to unify with type families, and it even improves the
1482 error messages in the testsuite. It also modestly improves performance, at
1483 least in some cases. But it's disastrous for test case perf/compiler/T3064.
1484 Here is the problem: Suppose we have (F ty) where we also have [G] F ty ~ a.
1485 What do we do? Do we reduce F? Or do we use the given? Hard to know what's
1486 best. GHC reduces. This is a disaster for T3064, where the type's size
1487 spirals out of control during reduction. (We're not helped by the fact that
1488 the flattener re-flattens all the arguments every time around.) If we prevent
1489 unification with type families, then the solver happens to use the equality
1490 before expanding the type family.
1491
1492 It would be lovely in the future to revisit this problem and remove this
1493 extra, unnecessary check. But we retain it for now as it seems to work
1494 better in practice.
1495
1496 Note [Refactoring hazard: checkTauTvUpdate]
1497 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1498 I (Richard E.) have a sad story about refactoring this code, retained here
1499 to prevent others (or a future me!) from falling into the same traps.
1500
1501 It all started with #11407, which was caused by the fact that the TyVarTy
1502 case of defer_me didn't look in the kind. But it seemed reasonable to
1503 simply remove the defer_me check instead.
1504
1505 It referred to two Notes (since removed) that were out of date, and the
1506 fast_check code in occurCheckExpand seemed to do just about the same thing as
1507 defer_me. The one piece that defer_me did that wasn't repeated by
1508 occurCheckExpand was the type-family check. (See Note [Prevent unification
1509 with type families].) So I checked the result of occurCheckExpand for any
1510 type family occurrences and deferred if there were any. This was done
1511 in commit e9bf7bb5cc9fb3f87dd05111aa23da76b86a8967 .
1512
1513 This approach turned out not to be performant, because the expanded type
1514 was bigger than the original type, and tyConsOfType looks through type
1515 synonyms. So it then struck me that we could dispense with the defer_me
1516 check entirely. This simplified the code nicely, and it cut the allocations
1517 in T5030 by half. But, as documented in Note [Prevent unification with
1518 type families], this destroyed performance in T3064. Regardless, I missed this
1519 regression and the change was committed as
1520 3f5d1a13f112f34d992f6b74656d64d95a3f506d .
1521
1522 Bottom lines:
1523 * defer_me is back, but now fixed w.r.t. #11407.
1524 * Tread carefully before you start to refactor here. There can be
1525 lots of hard-to-predict consequences.
1526
1527 Note [Type synonyms and the occur check]
1528 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1529 Generally speaking we try to update a variable with type synonyms not
1530 expanded, which improves later error messages, unless looking
1531 inside a type synonym may help resolve a spurious occurs check
1532 error. Consider:
1533 type A a = ()
1534
1535 f :: (A a -> a -> ()) -> ()
1536 f = \ _ -> ()
1537
1538 x :: ()
1539 x = f (\ x p -> p x)
1540
1541 We will eventually get a constraint of the form t ~ A t. The ok function above will
1542 properly expand the type (A t) to just (), which is ok to be unified with t. If we had
1543 unified with the original type A t, we would lead the type checker into an infinite loop.
1544
1545 Hence, if the occurs check fails for a type synonym application, then (and *only* then),
1546 the ok function expands the synonym to detect opportunities for occurs check success using
1547 the underlying definition of the type synonym.
1548
1549 The same applies later on in the constraint interaction code; see TcInteract,
1550 function @occ_check_ok@.
1551
1552 Note [Non-TcTyVars in TcUnify]
1553 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1554 Because the same code is now shared between unifying types and unifying
1555 kinds, we sometimes will see proper TyVars floating around the unifier.
1556 Example (from test case polykinds/PolyKinds12):
1557
1558 type family Apply (f :: k1 -> k2) (x :: k1) :: k2
1559 type instance Apply g y = g y
1560
1561 When checking the instance declaration, we first *kind-check* the LHS
1562 and RHS, discovering that the instance really should be
1563
1564 type instance Apply k3 k4 (g :: k3 -> k4) (y :: k3) = g y
1565
1566 During this kind-checking, all the tyvars will be TcTyVars. Then, however,
1567 as a second pass, we desugar the RHS (which is done in functions prefixed
1568 with "tc" in TcTyClsDecls"). By this time, all the kind-vars are proper
1569 TyVars, not TcTyVars, get some kind unification must happen.
1570
1571 Thus, we always check if a TyVar is a TcTyVar before asking if it's a
1572 meta-tyvar.
1573
1574 This used to not be necessary for type-checking (that is, before * :: *)
1575 because expressions get desugared via an algorithm separate from
1576 type-checking (with wrappers, etc.). Types get desugared very differently,
1577 causing this wibble in behavior seen here.
1578 -}
1579
1580 data LookupTyVarResult -- The result of a lookupTcTyVar call
1581 = Unfilled TcTyVarDetails -- SkolemTv or virgin MetaTv
1582 | Filled TcType
1583
1584 lookupTcTyVar :: TcTyVar -> TcM LookupTyVarResult
1585 lookupTcTyVar tyvar
1586 | MetaTv { mtv_ref = ref } <- details
1587 = do { meta_details <- readMutVar ref
1588 ; case meta_details of
1589 Indirect ty -> return (Filled ty)
1590 Flexi -> do { is_touchable <- isTouchableTcM tyvar
1591 -- Note [Unifying untouchables]
1592 ; if is_touchable then
1593 return (Unfilled details)
1594 else
1595 return (Unfilled vanillaSkolemTv) } }
1596 | otherwise
1597 = return (Unfilled details)
1598 where
1599 details = tcTyVarDetails tyvar
1600
1601 -- | Fill in a meta-tyvar
1602 updateMeta :: TcTyVar -- ^ tv to fill in, tv :: k1
1603 -> TcRef MetaDetails -- ^ ref to tv's metadetails
1604 -> TcType -- ^ ty2 :: k2
1605 -> Coercion -- ^ kind_co :: k2 ~N k1
1606 -> TcM Coercion -- ^ :: tv ~N ty2 (= ty2 |> kind_co ~N ty2)
1607 updateMeta tv1 ref1 ty2 kind_co
1608 = do { let ty2_refl = mkNomReflCo ty2
1609 (ty2', co) = ( ty2 `mkCastTy` kind_co
1610 , mkCoherenceLeftCo ty2_refl kind_co )
1611 ; writeMetaTyVarRef tv1 ref1 ty2'
1612 ; return co }
1613
1614 {-
1615 Note [Unifying untouchables]
1616 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1617 We treat an untouchable type variable as if it was a skolem. That
1618 ensures it won't unify with anything. It's a slight had, because
1619 we return a made-up TcTyVarDetails, but I think it works smoothly.
1620 -}
1621
1622 -- | Breaks apart a function kind into its pieces.
1623 matchExpectedFunKind :: Arity -- ^ # of args remaining, only for errors
1624 -> TcType -- ^ type, only for errors
1625 -> TcKind -- ^ function kind
1626 -> TcM (Coercion, TcKind, TcKind)
1627 -- ^ co :: old_kind ~ arg -> res
1628 matchExpectedFunKind num_args_remaining ty = go
1629 where
1630 go k | Just k' <- coreView k = go k'
1631
1632 go k@(TyVarTy kvar)
1633 | isTcTyVar kvar, isMetaTyVar kvar
1634 = do { maybe_kind <- readMetaTyVar kvar
1635 ; case maybe_kind of
1636 Indirect fun_kind -> go fun_kind
1637 Flexi -> defer k }
1638
1639 go k@(ForAllTy (Anon arg) res)
1640 = return (mkNomReflCo k, arg, res)
1641
1642 go other = defer other
1643
1644 defer k
1645 = do { arg_kind <- newMetaKindVar
1646 ; res_kind <- newMetaKindVar
1647 ; let new_fun = mkFunTy arg_kind res_kind
1648 thing = mkTypeErrorThingArgs ty num_args_remaining
1649 origin = TypeEqOrigin { uo_actual = k
1650 , uo_expected = mkCheckExpType new_fun
1651 , uo_thing = Just thing
1652 }
1653 ; co <- uType origin KindLevel k new_fun
1654 ; return (co, arg_kind, res_kind) }
1655 where