Re-add FunTy (big patch)
[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, 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 (FunTy 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 (FunTy 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 (FunTy act_arg act_res) (FunTy 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 unifyType :: Outputable a => Maybe a -- ^ If present, has type 'ty1'
980 -> TcTauType -> TcTauType -> TcM TcCoercionN
981 -- Actual and expected types
982 -- Returns a coercion : ty1 ~ ty2
983 unifyType thing ty1 ty2 = uType origin TypeLevel ty1 ty2
984 where
985 origin = TypeEqOrigin { uo_actual = ty1, uo_expected = mkCheckExpType ty2
986 , uo_thing = mkErrorThing <$> thing }
987
988 -- | Variant of 'unifyType' that takes an 'ExpType' as its second type
989 unifyExpType :: Outputable a => Maybe a
990 -> TcTauType -> ExpType -> TcM TcCoercionN
991 unifyExpType mb_thing ty1 ty2
992 = uExpType ty_orig ty1 ty2
993 where
994 ty_orig = TypeEqOrigin { uo_actual = ty1
995 , uo_expected = ty2
996 , uo_thing = mkErrorThing <$> mb_thing }
997
998 -- | Use this instead of 'Nothing' when calling 'unifyType' without
999 -- a good "thing" (where the "thing" has the "actual" type passed in)
1000 -- This has an 'Outputable' instance, avoiding amgiguity problems.
1001 noThing :: Maybe (HsExpr Name)
1002 noThing = Nothing
1003
1004 unifyKind :: Outputable a => Maybe a -> TcKind -> TcKind -> TcM CoercionN
1005 unifyKind thing ty1 ty2 = uType origin KindLevel ty1 ty2
1006 where origin = TypeEqOrigin { uo_actual = ty1, uo_expected = mkCheckExpType ty2
1007 , uo_thing = mkErrorThing <$> thing }
1008
1009 ---------------
1010 unifyPred :: PredType -> PredType -> TcM TcCoercionN
1011 -- Actual and expected types
1012 unifyPred = unifyType noThing
1013
1014 ---------------
1015 unifyTheta :: TcThetaType -> TcThetaType -> TcM [TcCoercionN]
1016 -- Actual and expected types
1017 unifyTheta theta1 theta2
1018 = do { checkTc (equalLength theta1 theta2)
1019 (vcat [text "Contexts differ in length",
1020 nest 2 $ parens $ text "Use RelaxedPolyRec to allow this"])
1021 ; zipWithM unifyPred theta1 theta2 }
1022
1023 {-
1024 %************************************************************************
1025 %* *
1026 uType and friends
1027 %* *
1028 %************************************************************************
1029
1030 uType is the heart of the unifier.
1031 -}
1032
1033 uExpType :: CtOrigin -> TcType -> ExpType -> TcM CoercionN
1034 uExpType orig ty1 et
1035 = uExpTypeX orig ty1 et return $
1036 uType orig TypeLevel ty1
1037
1038 -- | Tries to unify with an ExpType. If the ExpType is filled in, calls the first
1039 -- continuation with the produced coercion. Otherwise, calls the second
1040 -- continuation. This can happen either with a Check or with an untouchable
1041 -- ExpType that reverts to a tau-type. See Note [TcLevel of ExpType]
1042 uExpTypeX :: CtOrigin -> TcType -> ExpType
1043 -> (TcCoercionN -> TcM a) -- Infer case, co :: TcType ~N ExpType
1044 -> (TcType -> TcM a) -- Check / untouchable case
1045 -> TcM a
1046 uExpTypeX orig ty1 et@(Infer _ tc_lvl ki _) coercion_cont type_cont
1047 = do { cur_lvl <- getTcLevel
1048 ; if cur_lvl `sameDepthAs` tc_lvl
1049 then do { ki_co <- uType kind_orig KindLevel (typeKind ty1) ki
1050 ; writeExpType et (ty1 `mkCastTy` ki_co)
1051 ; coercion_cont $ mkTcNomReflCo ty1 `mkTcCoherenceRightCo` ki_co }
1052 else do { traceTc "Preventing writing to untouchable ExpType" empty
1053 ; tau <- expTypeToType et -- See Note [TcLevel of ExpType]
1054 ; type_cont tau }}
1055 where
1056 kind_orig = KindEqOrigin ty1 Nothing orig (Just TypeLevel)
1057 uExpTypeX _ _ (Check ty2) _ type_cont
1058 = type_cont ty2
1059
1060 ------------
1061 uType, uType_defer
1062 :: CtOrigin
1063 -> TypeOrKind
1064 -> TcType -- ty1 is the *actual* type
1065 -> TcType -- ty2 is the *expected* type
1066 -> TcM Coercion
1067
1068 --------------
1069 -- It is always safe to defer unification to the main constraint solver
1070 -- See Note [Deferred unification]
1071 uType_defer origin t_or_k ty1 ty2
1072 = do { hole <- newCoercionHole
1073 ; loc <- getCtLocM origin (Just t_or_k)
1074 ; emitSimple $ mkNonCanonical $
1075 CtWanted { ctev_dest = HoleDest hole
1076 , ctev_pred = mkPrimEqPred ty1 ty2
1077 , ctev_loc = loc }
1078
1079 -- Error trace only
1080 -- NB. do *not* call mkErrInfo unless tracing is on, because
1081 -- it is hugely expensive (#5631)
1082 ; whenDOptM Opt_D_dump_tc_trace $ do
1083 { ctxt <- getErrCtxt
1084 ; doc <- mkErrInfo emptyTidyEnv ctxt
1085 ; traceTc "utype_defer" (vcat [ppr hole, ppr ty1,
1086 ppr ty2, pprCtOrigin origin, doc])
1087 }
1088 ; return (mkHoleCo hole Nominal ty1 ty2) }
1089
1090 --------------
1091 uType origin t_or_k orig_ty1 orig_ty2
1092 = do { tclvl <- getTcLevel
1093 ; traceTc "u_tys " $ vcat
1094 [ text "tclvl" <+> ppr tclvl
1095 , sep [ ppr orig_ty1, text "~", ppr orig_ty2]
1096 , pprCtOrigin origin]
1097 ; co <- go orig_ty1 orig_ty2
1098 ; if isReflCo co
1099 then traceTc "u_tys yields no coercion" Outputable.empty
1100 else traceTc "u_tys yields coercion:" (ppr co)
1101 ; return co }
1102 where
1103 go :: TcType -> TcType -> TcM Coercion
1104 -- The arguments to 'go' are always semantically identical
1105 -- to orig_ty{1,2} except for looking through type synonyms
1106
1107 -- Variables; go for uVar
1108 -- Note that we pass in *original* (before synonym expansion),
1109 -- so that type variables tend to get filled in with
1110 -- the most informative version of the type
1111 go (TyVarTy tv1) ty2
1112 = do { lookup_res <- lookupTcTyVar tv1
1113 ; case lookup_res of
1114 Filled ty1 -> do { traceTc "found filled tyvar" (ppr tv1 <+> text ":->" <+> ppr ty1)
1115 ; go ty1 ty2 }
1116 Unfilled ds1 -> uUnfilledVar origin t_or_k NotSwapped tv1 ds1 ty2 }
1117 go ty1 (TyVarTy tv2)
1118 = do { lookup_res <- lookupTcTyVar tv2
1119 ; case lookup_res of
1120 Filled ty2 -> do { traceTc "found filled tyvar" (ppr tv2 <+> text ":->" <+> ppr ty2)
1121 ; go ty1 ty2 }
1122 Unfilled ds2 -> uUnfilledVar origin t_or_k IsSwapped tv2 ds2 ty1 }
1123
1124 -- See Note [Expanding synonyms during unification]
1125 go ty1@(TyConApp tc1 []) (TyConApp tc2 [])
1126 | tc1 == tc2
1127 = return $ mkReflCo Nominal ty1
1128
1129 -- See Note [Expanding synonyms during unification]
1130 --
1131 -- Also NB that we recurse to 'go' so that we don't push a
1132 -- new item on the origin stack. As a result if we have
1133 -- type Foo = Int
1134 -- and we try to unify Foo ~ Bool
1135 -- we'll end up saying "can't match Foo with Bool"
1136 -- rather than "can't match "Int with Bool". See Trac #4535.
1137 go ty1 ty2
1138 | Just ty1' <- coreView ty1 = go ty1' ty2
1139 | Just ty2' <- coreView ty2 = go ty1 ty2'
1140
1141 go (CastTy t1 co1) t2
1142 = do { co_tys <- go t1 t2
1143 ; return (mkCoherenceLeftCo co_tys co1) }
1144
1145 go t1 (CastTy t2 co2)
1146 = do { co_tys <- go t1 t2
1147 ; return (mkCoherenceRightCo co_tys co2) }
1148
1149 -- Functions (or predicate functions) just check the two parts
1150 go (FunTy fun1 arg1) (FunTy fun2 arg2)
1151 = do { co_l <- uType origin t_or_k fun1 fun2
1152 ; co_r <- uType origin t_or_k arg1 arg2
1153 ; return $ mkFunCo Nominal co_l co_r }
1154
1155 -- Always defer if a type synonym family (type function)
1156 -- is involved. (Data families behave rigidly.)
1157 go ty1@(TyConApp tc1 _) ty2
1158 | isTypeFamilyTyCon tc1 = defer ty1 ty2
1159 go ty1 ty2@(TyConApp tc2 _)
1160 | isTypeFamilyTyCon tc2 = defer ty1 ty2
1161
1162 go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
1163 -- See Note [Mismatched type lists and application decomposition]
1164 | tc1 == tc2, length tys1 == length tys2
1165 = ASSERT2( isGenerativeTyCon tc1 Nominal, ppr tc1 )
1166 do { cos <- zipWithM (uType origin t_or_k) tys1 tys2
1167 ; return $ mkTyConAppCo Nominal tc1 cos }
1168
1169 go (LitTy m) ty@(LitTy n)
1170 | m == n
1171 = return $ mkNomReflCo ty
1172
1173 -- See Note [Care with type applications]
1174 -- Do not decompose FunTy against App;
1175 -- it's often a type error, so leave it for the constraint solver
1176 go (AppTy s1 t1) (AppTy s2 t2)
1177 = go_app s1 t1 s2 t2
1178
1179 go (AppTy s1 t1) (TyConApp tc2 ts2)
1180 | Just (ts2', t2') <- snocView ts2
1181 = ASSERT( mightBeUnsaturatedTyCon tc2 )
1182 go_app s1 t1 (TyConApp tc2 ts2') t2'
1183
1184 go (TyConApp tc1 ts1) (AppTy s2 t2)
1185 | Just (ts1', t1') <- snocView ts1
1186 = ASSERT( mightBeUnsaturatedTyCon tc1 )
1187 go_app (TyConApp tc1 ts1') t1' s2 t2
1188
1189 go (CoercionTy co1) (CoercionTy co2)
1190 = do { let ty1 = coercionType co1
1191 ty2 = coercionType co2
1192 ; kco <- uType (KindEqOrigin orig_ty1 (Just orig_ty2) origin
1193 (Just t_or_k))
1194 KindLevel
1195 ty1 ty2
1196 ; return $ mkProofIrrelCo Nominal kco co1 co2 }
1197
1198 -- Anything else fails
1199 -- E.g. unifying for-all types, which is relative unusual
1200 go ty1 ty2 = defer ty1 ty2
1201
1202 ------------------
1203 defer ty1 ty2 -- See Note [Check for equality before deferring]
1204 | ty1 `tcEqType` ty2 = return (mkNomReflCo ty1)
1205 | otherwise = uType_defer origin t_or_k ty1 ty2
1206
1207 ------------------
1208 go_app s1 t1 s2 t2
1209 = do { co_s <- uType origin t_or_k s1 s2
1210 ; co_t <- uType origin t_or_k t1 t2
1211 ; return $ mkAppCo co_s co_t }
1212
1213 {- Note [Check for equality before deferring]
1214 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1215 Particularly in ambiguity checks we can get equalities like (ty ~ ty).
1216 If ty involves a type function we may defer, which isn't very sensible.
1217 An egregious example of this was in test T9872a, which has a type signature
1218 Proxy :: Proxy (Solutions Cubes)
1219 Doing the ambiguity check on this signature generates the equality
1220 Solutions Cubes ~ Solutions Cubes
1221 and currently the constraint solver normalises both sides at vast cost.
1222 This little short-cut in 'defer' helps quite a bit.
1223
1224 Note [Care with type applications]
1225 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1226 Note: type applications need a bit of care!
1227 They can match FunTy and TyConApp, so use splitAppTy_maybe
1228 NB: we've already dealt with type variables and Notes,
1229 so if one type is an App the other one jolly well better be too
1230
1231 Note [Mismatched type lists and application decomposition]
1232 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1233 When we find two TyConApps, you might think that the argument lists
1234 are guaranteed equal length. But they aren't. Consider matching
1235 w (T x) ~ Foo (T x y)
1236 We do match (w ~ Foo) first, but in some circumstances we simply create
1237 a deferred constraint; and then go ahead and match (T x ~ T x y).
1238 This came up in Trac #3950.
1239
1240 So either
1241 (a) either we must check for identical argument kinds
1242 when decomposing applications,
1243
1244 (b) or we must be prepared for ill-kinded unification sub-problems
1245
1246 Currently we adopt (b) since it seems more robust -- no need to maintain
1247 a global invariant.
1248
1249 Note [Expanding synonyms during unification]
1250 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1251 We expand synonyms during unification, but:
1252 * We expand *after* the variable case so that we tend to unify
1253 variables with un-expanded type synonym. This just makes it
1254 more likely that the inferred types will mention type synonyms
1255 understandable to the user
1256
1257 * We expand *before* the TyConApp case. For example, if we have
1258 type Phantom a = Int
1259 and are unifying
1260 Phantom Int ~ Phantom Char
1261 it is *wrong* to unify Int and Char.
1262
1263 * The problem case immediately above can happen only with arguments
1264 to the tycon. So we check for nullary tycons *before* expanding.
1265 This is particularly helpful when checking (* ~ *), because * is
1266 now a type synonym.
1267
1268 Note [Deferred Unification]
1269 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1270 We may encounter a unification ty1 ~ ty2 that cannot be performed syntactically,
1271 and yet its consistency is undetermined. Previously, there was no way to still
1272 make it consistent. So a mismatch error was issued.
1273
1274 Now these unifications are deferred until constraint simplification, where type
1275 family instances and given equations may (or may not) establish the consistency.
1276 Deferred unifications are of the form
1277 F ... ~ ...
1278 or x ~ ...
1279 where F is a type function and x is a type variable.
1280 E.g.
1281 id :: x ~ y => x -> y
1282 id e = e
1283
1284 involves the unification x = y. It is deferred until we bring into account the
1285 context x ~ y to establish that it holds.
1286
1287 If available, we defer original types (rather than those where closed type
1288 synonyms have already been expanded via tcCoreView). This is, as usual, to
1289 improve error messages.
1290
1291
1292 ************************************************************************
1293 * *
1294 uVar and friends
1295 * *
1296 ************************************************************************
1297
1298 @uVar@ is called when at least one of the types being unified is a
1299 variable. It does {\em not} assume that the variable is a fixed point
1300 of the substitution; rather, notice that @uVar@ (defined below) nips
1301 back into @uTys@ if it turns out that the variable is already bound.
1302 -}
1303
1304 uUnfilledVar :: CtOrigin
1305 -> TypeOrKind
1306 -> SwapFlag
1307 -> TcTyVar -> TcTyVarDetails -- Tyvar 1
1308 -> TcTauType -- Type 2
1309 -> TcM Coercion
1310 -- "Unfilled" means that the variable is definitely not a filled-in meta tyvar
1311 -- It might be a skolem, or untouchable, or meta
1312
1313 uUnfilledVar origin t_or_k swapped tv1 details1 (TyVarTy tv2)
1314 | tv1 == tv2 -- Same type variable => no-op
1315 = return (mkNomReflCo (mkTyVarTy tv1))
1316
1317 | otherwise -- Distinct type variables
1318 = do { lookup2 <- lookupTcTyVar tv2
1319 ; case lookup2 of
1320 Filled ty2'
1321 -> uUnfilledVar origin t_or_k swapped tv1 details1 ty2'
1322 Unfilled details2
1323 -> uUnfilledVars origin t_or_k swapped tv1 details1 tv2 details2
1324 }
1325
1326 uUnfilledVar origin t_or_k swapped tv1 details1 non_var_ty2
1327 -- ty2 is not a type variable
1328 = case details1 of
1329 MetaTv { mtv_ref = ref1 }
1330 -> do { dflags <- getDynFlags
1331 ; mb_ty2' <- checkTauTvUpdate dflags origin t_or_k tv1 non_var_ty2
1332 ; case mb_ty2' of
1333 Just (ty2', co_k) -> maybe_sym swapped <$>
1334 updateMeta tv1 ref1 ty2' co_k
1335 Nothing -> do { traceTc "Occ/type-family defer"
1336 (ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1)
1337 $$ ppr non_var_ty2 $$ ppr (typeKind non_var_ty2))
1338 ; defer }
1339 }
1340
1341 _other -> do { traceTc "Skolem defer" (ppr tv1); defer } -- Skolems of all sorts
1342 where
1343 defer = unSwap swapped (uType_defer origin t_or_k) (mkTyVarTy tv1) non_var_ty2
1344 -- Occurs check or an untouchable: just defer
1345 -- NB: occurs check isn't necessarily fatal:
1346 -- eg tv1 occured in type family parameter
1347
1348 ----------------
1349 uUnfilledVars :: CtOrigin
1350 -> TypeOrKind
1351 -> SwapFlag
1352 -> TcTyVar -> TcTyVarDetails -- Tyvar 1
1353 -> TcTyVar -> TcTyVarDetails -- Tyvar 2
1354 -> TcM Coercion
1355 -- Invarant: The type variables are distinct,
1356 -- Neither is filled in yet
1357
1358 uUnfilledVars origin t_or_k swapped tv1 details1 tv2 details2
1359 = do { traceTc "uUnfilledVars for" (ppr tv1 <+> text "and" <+> ppr tv2)
1360 ; traceTc "uUnfilledVars" ( text "trying to unify" <+> ppr k1
1361 <+> text "with" <+> ppr k2)
1362 ; co_k <- uType kind_origin KindLevel k1 k2
1363 ; let no_swap ref = maybe_sym swapped <$>
1364 updateMeta tv1 ref ty2 (mkSymCo co_k)
1365 do_swap ref = maybe_sym (flipSwap swapped) <$>
1366 updateMeta tv2 ref ty1 co_k
1367 ; case (details1, details2) of
1368 { ( MetaTv { mtv_info = i1, mtv_ref = ref1 }
1369 , MetaTv { mtv_info = i2, mtv_ref = ref2 } )
1370 | nicer_to_update_tv1 tv1 i1 i2 -> no_swap ref1
1371 | otherwise -> do_swap ref2
1372 ; (MetaTv { mtv_ref = ref1 }, _) -> no_swap ref1
1373 ; (_, MetaTv { mtv_ref = ref2 }) -> do_swap ref2
1374
1375 -- Can't do it in-place, so defer
1376 -- This happens for skolems of all sorts
1377 ; _ -> do { traceTc "deferring because I can't find a meta-tyvar:"
1378 (pprTcTyVarDetails details1 <+> pprTcTyVarDetails details2)
1379 ; unSwap swapped (uType_defer origin t_or_k) ty1 ty2 } } }
1380 where
1381 k1 = tyVarKind tv1
1382 k2 = tyVarKind tv2
1383 ty1 = mkTyVarTy tv1
1384 ty2 = mkTyVarTy tv2
1385 kind_origin = KindEqOrigin ty1 (Just ty2) origin (Just t_or_k)
1386
1387 -- | apply sym iff swapped
1388 maybe_sym :: SwapFlag -> Coercion -> Coercion
1389 maybe_sym IsSwapped = mkSymCo
1390 maybe_sym NotSwapped = id
1391
1392 nicer_to_update_tv1 :: TcTyVar -> MetaInfo -> MetaInfo -> Bool
1393 nicer_to_update_tv1 _ _ SigTv = True
1394 nicer_to_update_tv1 _ SigTv _ = False
1395 -- Try not to update SigTvs; and try to update sys-y type
1396 -- variables in preference to ones gotten (say) by
1397 -- instantiating a polymorphic function with a user-written
1398 -- type sig
1399 nicer_to_update_tv1 tv1 _ _ = isSystemName (Var.varName tv1)
1400
1401 ----------------
1402 checkTauTvUpdate :: DynFlags
1403 -> CtOrigin
1404 -> TypeOrKind
1405 -> TcTyVar -- tv :: k1
1406 -> TcType -- ty :: k2
1407 -> TcM (Maybe ( TcType -- possibly-expanded ty
1408 , Coercion )) -- :: k2 ~N k1
1409 -- (checkTauTvUpdate tv ty)
1410 -- We are about to update the TauTv tv with ty.
1411 -- Check (a) that tv doesn't occur in ty (occurs check)
1412 -- (b) that kind(ty) matches kind(tv)
1413 --
1414 -- We have two possible outcomes:
1415 -- (1) Return the type to update the type variable with,
1416 -- [we know the update is ok]
1417 -- (2) Return Nothing,
1418 -- [the update might be dodgy]
1419 --
1420 -- Note that "Nothing" does not mean "definite error". For example
1421 -- type family F a
1422 -- type instance F Int = Int
1423 -- consider
1424 -- a ~ F a
1425 -- This is perfectly reasonable, if we later get a ~ Int. For now, though,
1426 -- we return Nothing, leaving it to the later constraint simplifier to
1427 -- sort matters out.
1428
1429 checkTauTvUpdate dflags origin t_or_k tv ty
1430 | SigTv <- info
1431 = ASSERT( not (isTyVarTy ty) )
1432 return Nothing
1433 | otherwise
1434 = do { ty <- zonkTcType ty
1435 ; co_k <- uType kind_origin KindLevel (typeKind ty) (tyVarKind tv)
1436 ; if | defer_me ty -> -- Quick test
1437 -- Failed quick test so try harder
1438 case occurCheckExpand dflags tv ty of
1439 OC_OK ty2 | defer_me ty2 -> return Nothing
1440 | otherwise -> return (Just (ty2, co_k))
1441 _ -> return Nothing
1442 | otherwise -> return (Just (ty, co_k)) }
1443
1444 where
1445 kind_origin = KindEqOrigin (mkTyVarTy tv) (Just ty) origin (Just t_or_k)
1446 details = tcTyVarDetails tv
1447 info = mtv_info details
1448
1449 impredicative = canUnifyWithPolyType dflags details
1450
1451 defer_me :: TcType -> Bool
1452 -- Checks for (a) occurrence of tv
1453 -- (b) type family applications
1454 -- (c) foralls
1455 -- See Note [Prevent unification with type families]
1456 -- See Note [Refactoring hazard: checkTauTvUpdate]
1457 defer_me (LitTy {}) = False
1458 defer_me (TyVarTy tv') = tv == tv' || defer_me (tyVarKind tv')
1459 defer_me (TyConApp tc tys) = isTypeFamilyTyCon tc || any defer_me tys
1460 || not (impredicative || isTauTyCon tc)
1461 defer_me (ForAllTy bndr t) = defer_me (binderType bndr) || defer_me t
1462 || not impredicative
1463 defer_me (FunTy fun arg) = defer_me fun || defer_me arg
1464 defer_me (AppTy fun arg) = defer_me fun || defer_me arg
1465 defer_me (CastTy ty co) = defer_me ty || defer_me_co co
1466 defer_me (CoercionTy co) = defer_me_co co
1467
1468 -- We don't really care if there are type families in a coercion,
1469 -- but we still can't have an occurs-check failure
1470 defer_me_co co = tv `elemVarSet` tyCoVarsOfCo co
1471
1472 {-
1473 Note [Prevent unification with type families]
1474 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1475 We prevent unification with type families because of an uneasy compromise.
1476 It's perfectly sound to unify with type families, and it even improves the
1477 error messages in the testsuite. It also modestly improves performance, at
1478 least in some cases. But it's disastrous for test case perf/compiler/T3064.
1479 Here is the problem: Suppose we have (F ty) where we also have [G] F ty ~ a.
1480 What do we do? Do we reduce F? Or do we use the given? Hard to know what's
1481 best. GHC reduces. This is a disaster for T3064, where the type's size
1482 spirals out of control during reduction. (We're not helped by the fact that
1483 the flattener re-flattens all the arguments every time around.) If we prevent
1484 unification with type families, then the solver happens to use the equality
1485 before expanding the type family.
1486
1487 It would be lovely in the future to revisit this problem and remove this
1488 extra, unnecessary check. But we retain it for now as it seems to work
1489 better in practice.
1490
1491 Note [Refactoring hazard: checkTauTvUpdate]
1492 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1493 I (Richard E.) have a sad story about refactoring this code, retained here
1494 to prevent others (or a future me!) from falling into the same traps.
1495
1496 It all started with #11407, which was caused by the fact that the TyVarTy
1497 case of defer_me didn't look in the kind. But it seemed reasonable to
1498 simply remove the defer_me check instead.
1499
1500 It referred to two Notes (since removed) that were out of date, and the
1501 fast_check code in occurCheckExpand seemed to do just about the same thing as
1502 defer_me. The one piece that defer_me did that wasn't repeated by
1503 occurCheckExpand was the type-family check. (See Note [Prevent unification
1504 with type families].) So I checked the result of occurCheckExpand for any
1505 type family occurrences and deferred if there were any. This was done
1506 in commit e9bf7bb5cc9fb3f87dd05111aa23da76b86a8967 .
1507
1508 This approach turned out not to be performant, because the expanded type
1509 was bigger than the original type, and tyConsOfType looks through type
1510 synonyms. So it then struck me that we could dispense with the defer_me
1511 check entirely. This simplified the code nicely, and it cut the allocations
1512 in T5030 by half. But, as documented in Note [Prevent unification with
1513 type families], this destroyed performance in T3064. Regardless, I missed this
1514 regression and the change was committed as
1515 3f5d1a13f112f34d992f6b74656d64d95a3f506d .
1516
1517 Bottom lines:
1518 * defer_me is back, but now fixed w.r.t. #11407.
1519 * Tread carefully before you start to refactor here. There can be
1520 lots of hard-to-predict consequences.
1521
1522 Note [Type synonyms and the occur check]
1523 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1524 Generally speaking we try to update a variable with type synonyms not
1525 expanded, which improves later error messages, unless looking
1526 inside a type synonym may help resolve a spurious occurs check
1527 error. Consider:
1528 type A a = ()
1529
1530 f :: (A a -> a -> ()) -> ()
1531 f = \ _ -> ()
1532
1533 x :: ()
1534 x = f (\ x p -> p x)
1535
1536 We will eventually get a constraint of the form t ~ A t. The ok function above will
1537 properly expand the type (A t) to just (), which is ok to be unified with t. If we had
1538 unified with the original type A t, we would lead the type checker into an infinite loop.
1539
1540 Hence, if the occurs check fails for a type synonym application, then (and *only* then),
1541 the ok function expands the synonym to detect opportunities for occurs check success using
1542 the underlying definition of the type synonym.
1543
1544 The same applies later on in the constraint interaction code; see TcInteract,
1545 function @occ_check_ok@.
1546
1547 Note [Non-TcTyVars in TcUnify]
1548 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1549 Because the same code is now shared between unifying types and unifying
1550 kinds, we sometimes will see proper TyVars floating around the unifier.
1551 Example (from test case polykinds/PolyKinds12):
1552
1553 type family Apply (f :: k1 -> k2) (x :: k1) :: k2
1554 type instance Apply g y = g y
1555
1556 When checking the instance declaration, we first *kind-check* the LHS
1557 and RHS, discovering that the instance really should be
1558
1559 type instance Apply k3 k4 (g :: k3 -> k4) (y :: k3) = g y
1560
1561 During this kind-checking, all the tyvars will be TcTyVars. Then, however,
1562 as a second pass, we desugar the RHS (which is done in functions prefixed
1563 with "tc" in TcTyClsDecls"). By this time, all the kind-vars are proper
1564 TyVars, not TcTyVars, get some kind unification must happen.
1565
1566 Thus, we always check if a TyVar is a TcTyVar before asking if it's a
1567 meta-tyvar.
1568
1569 This used to not be necessary for type-checking (that is, before * :: *)
1570 because expressions get desugared via an algorithm separate from
1571 type-checking (with wrappers, etc.). Types get desugared very differently,
1572 causing this wibble in behavior seen here.
1573 -}
1574
1575 data LookupTyVarResult -- The result of a lookupTcTyVar call
1576 = Unfilled TcTyVarDetails -- SkolemTv or virgin MetaTv
1577 | Filled TcType
1578
1579 lookupTcTyVar :: TcTyVar -> TcM LookupTyVarResult
1580 lookupTcTyVar tyvar
1581 | MetaTv { mtv_ref = ref } <- details
1582 = do { meta_details <- readMutVar ref
1583 ; case meta_details of
1584 Indirect ty -> return (Filled ty)
1585 Flexi -> do { is_touchable <- isTouchableTcM tyvar
1586 -- Note [Unifying untouchables]
1587 ; if is_touchable then
1588 return (Unfilled details)
1589 else
1590 return (Unfilled vanillaSkolemTv) } }
1591 | otherwise
1592 = return (Unfilled details)
1593 where
1594 details = tcTyVarDetails tyvar
1595
1596 -- | Fill in a meta-tyvar
1597 updateMeta :: TcTyVar -- ^ tv to fill in, tv :: k1
1598 -> TcRef MetaDetails -- ^ ref to tv's metadetails
1599 -> TcType -- ^ ty2 :: k2
1600 -> Coercion -- ^ kind_co :: k2 ~N k1
1601 -> TcM Coercion -- ^ :: tv ~N ty2 (= ty2 |> kind_co ~N ty2)
1602 updateMeta tv1 ref1 ty2 kind_co
1603 = do { let ty2_refl = mkNomReflCo ty2
1604 (ty2', co) = ( ty2 `mkCastTy` kind_co
1605 , mkCoherenceLeftCo ty2_refl kind_co )
1606 ; writeMetaTyVarRef tv1 ref1 ty2'
1607 ; return co }
1608
1609 {-
1610 Note [Unifying untouchables]
1611 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1612 We treat an untouchable type variable as if it was a skolem. That
1613 ensures it won't unify with anything. It's a slight had, because
1614 we return a made-up TcTyVarDetails, but I think it works smoothly.
1615 -}
1616
1617 -- | Breaks apart a function kind into its pieces.
1618 matchExpectedFunKind :: Arity -- ^ # of args remaining, only for errors
1619 -> TcType -- ^ type, only for errors
1620 -> TcKind -- ^ function kind
1621 -> TcM (Coercion, TcKind, TcKind)
1622 -- ^ co :: old_kind ~ arg -> res
1623 matchExpectedFunKind num_args_remaining ty = go
1624 where
1625 go k | Just k' <- coreView k = go k'
1626
1627 go k@(TyVarTy kvar)
1628 | isTcTyVar kvar, isMetaTyVar kvar
1629 = do { maybe_kind <- readMetaTyVar kvar
1630 ; case maybe_kind of
1631 Indirect fun_kind -> go fun_kind
1632 Flexi -> defer k }
1633
1634 go k@(FunTy arg res) = return (mkNomReflCo k, arg, res)
1635 go other = defer other
1636
1637 defer k
1638 = do { arg_kind <- newMetaKindVar
1639 ; res_kind <- newMetaKindVar
1640 ; let new_fun = mkFunTy arg_kind res_kind
1641 thing = mkTypeErrorThingArgs ty num_args_remaining
1642 origin = TypeEqOrigin { uo_actual = k
1643 , uo_expected = mkCheckExpType new_fun
1644 , uo_thing = Just thing
1645 }
1646 ; co <- uType origin KindLevel k new_fun
1647 ; return (co, arg_kind, res_kind) }
1648 where