Major bugfixing pass through the type checker
[ghc-hetmet.git] / compiler / typecheck / TcUnify.lhs
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 \begin{code}
9 module TcUnify (
10         -- Full-blown subsumption
11   tcWrapResult, tcSubType, tcGen, 
12   checkConstraints, newImplication, sigCtxt,
13
14         -- Various unifications
15   unifyType, unifyTypeList, unifyTheta, unifyKind, 
16
17   --------------------------------
18   -- Holes
19   tcInfer, 
20   matchExpectedListTy, matchExpectedPArrTy, 
21   matchExpectedTyConApp, matchExpectedAppTy, 
22   matchExpectedFunTys, matchExpectedFunKind,
23   wrapFunResCoercion
24   ) where
25
26 #include "HsVersions.h"
27
28 import HsSyn
29 import TypeRep
30
31 import TcErrors ( typeExtraInfoMsg, unifyCtxt )
32 import TcMType
33 import TcEnv
34 import TcIface
35 import TcRnMonad
36 import TcType
37 import Type
38 import Coercion
39 import Inst
40 import TyCon
41 import TysWiredIn
42 import Var
43 import VarSet
44 import VarEnv
45 import Name
46 import ErrUtils
47 import BasicTypes
48 import Bag
49
50 import Maybes ( allMaybes )  
51 import Util
52 import Outputable
53 import FastString
54
55 import Control.Monad
56 \end{code}
57
58
59 %************************************************************************
60 %*                                                                      *
61              matchExpected functions
62 %*                                                                      *
63 %************************************************************************
64
65 Note [Herald for matchExpectedFunTys]
66 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
67 The 'herald' always looks like:
68    "The equation(s) for 'f' have"
69    "The abstraction (\x.e) takes"
70    "The section (+ x) expects"
71    "The function 'f' is applied to"
72
73 This is used to construct a message of form
74
75    The abstraction `\Just 1 -> ...' takes two arguments
76    but its type `Maybe a -> a' has only one
77
78    The equation(s) for `f' have two arguments
79    but its type `Maybe a -> a' has only one
80
81    The section `(f 3)' requires 'f' to take two arguments
82    but its type `Int -> Int' has only one
83
84    The function 'f' is applied to two arguments
85    but its type `Int -> Int' has only one
86
87 Note [matchExpectedFunTys]
88 ~~~~~~~~~~~~~~~~~~~~~~~~~~
89 matchExpectedFunTys checks that an (Expected rho) has the form
90 of an n-ary function.  It passes the decomposed type to the
91 thing_inside, and returns a wrapper to coerce between the two types
92
93 It's used wherever a language construct must have a functional type,
94 namely:
95         A lambda expression
96         A function definition
97      An operator section
98
99 This is not (currently) where deep skolemisation occurs;
100 matchExpectedFunTys does not skolmise nested foralls in the 
101 expected type, becuase it expects that to have been done already
102
103
104 \begin{code}
105 matchExpectedFunTys :: SDoc     -- See Note [Herald for matchExpectedFunTys]
106                     -> Arity
107                     -> TcRhoType 
108                     -> TcM (CoercionI, [TcSigmaType], TcRhoType)                        
109
110 -- If    matchExpectFunTys n ty = (co, [t1,..,tn], ty_r)
111 -- then  co : ty ~ (t1 -> ... -> tn -> ty_r)
112 --
113 -- Does not allocate unnecessary meta variables: if the input already is 
114 -- a function, we just take it apart.  Not only is this efficient, 
115 -- it's important for higher rank: the argument might be of form
116 --              (forall a. ty) -> other
117 -- If allocated (fresh-meta-var1 -> fresh-meta-var2) and unified, we'd
118 -- hide the forall inside a meta-variable
119
120 matchExpectedFunTys herald arity orig_ty 
121   = go arity orig_ty
122   where
123     -- If     go n ty = (co, [t1,..,tn], ty_r)
124     -- then   co : ty ~ t1 -> .. -> tn -> ty_r
125
126     go n_req ty
127       | n_req == 0 = return (IdCo ty, [], ty)
128
129     go n_req ty
130       | Just ty' <- tcView ty = go n_req ty'
131
132     go n_req (FunTy arg_ty res_ty)
133       | not (isPredTy arg_ty) 
134       = do { (coi, tys, ty_r) <- go (n_req-1) res_ty
135            ; return (mkFunTyCoI (IdCo arg_ty) coi, arg_ty:tys, ty_r) }
136
137     go _ (TyConApp tc _)              -- A common case
138       | not (isSynFamilyTyCon tc)
139       = do { (env,msg) <- mk_ctxt emptyTidyEnv
140            ; failWithTcM (env,msg) }
141
142     go n_req ty@(TyVarTy tv)
143       | ASSERT( isTcTyVar tv) isMetaTyVar tv
144       = do { cts <- readMetaTyVar tv
145            ; case cts of
146                Indirect ty' -> go n_req ty'
147                Flexi        -> defer n_req ty }
148
149        -- In all other cases we bale out into ordinary unification
150     go n_req ty = defer n_req ty
151
152     ------------
153     defer n_req fun_ty 
154       = addErrCtxtM mk_ctxt $
155         do { arg_tys <- newFlexiTyVarTys n_req argTypeKind
156            ; res_ty  <- newFlexiTyVarTy openTypeKind
157            ; coi     <- unifyType fun_ty (mkFunTys arg_tys res_ty)
158            ; return (coi, arg_tys, res_ty) }
159
160     ------------
161     mk_ctxt :: TidyEnv -> TcM (TidyEnv, Message)
162     mk_ctxt env = do { orig_ty1 <- zonkTcType orig_ty
163                      ; let (env', orig_ty2) = tidyOpenType env orig_ty1
164                            (args, _) = tcSplitFunTys orig_ty2
165                            n_actual = length args
166                      ; return (env', mk_msg orig_ty2 n_actual) }
167
168     mk_msg ty n_args
169       = herald <+> speakNOf arity (ptext (sLit "argument")) <> comma $$ 
170         sep [ptext (sLit "but its type") <+> quotes (pprType ty), 
171              if n_args == 0 then ptext (sLit "has none") 
172              else ptext (sLit "has only") <+> speakN n_args]
173 \end{code}
174
175
176 \begin{code}
177 ----------------------
178 matchExpectedListTy :: TcRhoType -> TcM (CoercionI, TcRhoType)
179 -- Special case for lists
180 matchExpectedListTy exp_ty
181  = do { (coi, [elt_ty]) <- matchExpectedTyConApp listTyCon exp_ty
182       ; return (coi, elt_ty) }
183
184 ----------------------
185 matchExpectedPArrTy :: TcRhoType -> TcM (CoercionI, TcRhoType)
186 -- Special case for parrs
187 matchExpectedPArrTy exp_ty
188   = do { (coi, [elt_ty]) <- matchExpectedTyConApp parrTyCon exp_ty
189        ; return (coi, elt_ty) }
190
191 ----------------------
192 matchExpectedTyConApp :: TyCon                -- T :: k1 -> ... -> kn -> *
193                       -> TcRhoType            -- orig_ty
194                       -> TcM (CoercionI,      -- T a b c ~ orig_ty
195                               [TcSigmaType])  -- Element types, a b c
196                               
197 -- It's used for wired-in tycons, so we call checkWiredInTyCon
198 -- Precondition: never called with FunTyCon
199 -- Precondition: input type :: *
200
201 matchExpectedTyConApp tc orig_ty
202   = do  { checkWiredInTyCon tc
203         ; go (tyConArity tc) orig_ty [] }
204   where
205     go :: Int -> TcRhoType -> [TcSigmaType] -> TcM (CoercionI, [TcSigmaType])
206     -- If     go n ty tys = (co, [t1..tn] ++ tys)
207     -- then   co : T t1..tn ~ ty
208
209     go n_req ty tys
210       | Just ty' <- tcView ty = go n_req ty' tys
211
212     go n_req ty@(TyVarTy tv) tys
213       | ASSERT( isTcTyVar tv) isMetaTyVar tv
214       = do { cts <- readMetaTyVar tv
215            ; case cts of
216                Indirect ty -> go n_req ty tys
217                Flexi       -> defer n_req ty tys }
218
219     go n_req ty@(TyConApp tycon args) tys
220       | tc == tycon
221       = ASSERT( n_req == length args)   -- ty::*
222         return (IdCo ty, args ++ tys)
223
224     go n_req (AppTy fun arg) tys
225       | n_req > 0
226       = do { (coi, args) <- go (n_req - 1) fun (arg : tys) 
227            ; return (mkAppTyCoI coi (IdCo arg), args) }
228
229     go n_req ty tys = defer n_req ty tys
230
231     ----------
232     defer n_req ty tys
233       = do { tau_tys <- mapM newFlexiTyVarTy arg_kinds
234            ; coi <- unifyType (mkTyConApp tc tau_tys) ty
235            ; return (coi, tau_tys ++ tys) }
236       where
237         (arg_kinds, _) = splitKindFunTysN n_req (tyConKind tc)
238
239 ----------------------
240 matchExpectedAppTy :: TcRhoType                         -- orig_ty
241                    -> TcM (CoercionI,                   -- m a ~ orig_ty
242                            (TcSigmaType, TcSigmaType))  -- Returns m, a
243 -- If the incoming type is a mutable type variable of kind k, then
244 -- matchExpectedAppTy returns a new type variable (m: * -> k); note the *.
245
246 matchExpectedAppTy orig_ty
247   = go orig_ty
248   where
249     go ty
250       | Just ty' <- tcView ty = go ty'
251
252       | Just (fun_ty, arg_ty) <- tcSplitAppTy_maybe ty
253       = return (IdCo orig_ty, (fun_ty, arg_ty))
254
255     go (TyVarTy tv)
256       | ASSERT( isTcTyVar tv) isMetaTyVar tv
257       = do { cts <- readMetaTyVar tv
258            ; case cts of
259                Indirect ty -> go ty
260                Flexi       -> defer }
261
262     go _ = defer
263
264     -- Defer splitting by generating an equality constraint
265     defer = do { ty1 <- newFlexiTyVarTy kind1
266                ; ty2 <- newFlexiTyVarTy kind2
267                ; coi <- unifyType (mkAppTy ty1 ty2) orig_ty
268                ; return (coi, (ty1, ty2)) }
269
270     orig_kind = typeKind orig_ty
271     kind1 = mkArrowKind liftedTypeKind (defaultKind orig_kind)
272     kind2 = liftedTypeKind    -- m :: * -> k
273                               -- arg type :: *
274         -- The defaultKind is a bit smelly.  If you remove it,
275         -- try compiling        f x = do { x }
276         -- and you'll get a kind mis-match.  It smells, but
277         -- not enough to lose sleep over.
278 \end{code}
279
280
281 %************************************************************************
282 %*                                                                      *
283                 Subsumption checking
284 %*                                                                      *
285 %************************************************************************
286
287 All the tcSub calls have the form
288
289                 tcSub actual_ty expected_ty
290 which checks
291                 actual_ty <= expected_ty
292
293 That is, that a value of type actual_ty is acceptable in
294 a place expecting a value of type expected_ty.
295
296 It returns a coercion function
297         co_fn :: actual_ty ~ expected_ty
298 which takes an HsExpr of type actual_ty into one of type
299 expected_ty.
300
301 \begin{code}
302 tcSubType :: CtOrigin -> SkolemInfo -> TcSigmaType -> TcSigmaType -> TcM HsWrapper
303 -- Check that ty_actual is more polymorphic than ty_expected
304 -- Both arguments might be polytypes, so we must instantiate and skolemise
305 -- Returns a wrapper of shape   ty_actual ~ ty_expected
306 tcSubType origin skol_info ty_actual ty_expected 
307   | isSigmaTy ty_actual
308   = do { let extra_tvs = tyVarsOfType ty_actual
309        ; (sk_wrap, inst_wrap) 
310             <- tcGen skol_info extra_tvs ty_expected $ \ _ sk_rho -> do 
311             { (in_wrap, in_rho) <- deeplyInstantiate origin ty_actual
312             ; coi <- unifyType in_rho sk_rho
313             ; return (coiToHsWrapper coi <.> in_wrap) }
314        ; return (sk_wrap <.> inst_wrap) }
315
316   | otherwise   -- Urgh!  It seems deeply weird to have equality
317                 -- when actual is not a polytype, and it makes a big 
318                 -- difference e.g. tcfail104
319   = do { coi <- unifyType ty_actual ty_expected
320        ; return (coiToHsWrapper coi) }
321   
322 tcInfer :: (TcType -> TcM a) -> TcM (a, TcType)
323 tcInfer tc_infer = do { ty  <- newFlexiTyVarTy openTypeKind
324                       ; res <- tc_infer ty
325                       ; return (res, ty) }
326
327 -----------------
328 tcWrapResult :: HsExpr TcId -> TcRhoType -> TcRhoType -> TcM (HsExpr TcId)
329 tcWrapResult expr actual_ty res_ty
330   = do { coi <- unifyType actual_ty res_ty
331                 -- Both types are deeply skolemised
332        ; return (mkHsWrapCoI coi expr) }
333
334 -----------------------------------
335 wrapFunResCoercion
336         :: [TcType]     -- Type of args
337         -> HsWrapper    -- HsExpr a -> HsExpr b
338         -> TcM HsWrapper        -- HsExpr (arg_tys -> a) -> HsExpr (arg_tys -> b)
339 wrapFunResCoercion arg_tys co_fn_res
340   | isIdHsWrapper co_fn_res
341   = return idHsWrapper
342   | null arg_tys
343   = return co_fn_res
344   | otherwise
345   = do  { arg_ids <- newSysLocalIds (fsLit "sub") arg_tys
346         ; return (mkWpLams arg_ids <.> co_fn_res <.> mkWpEvVarApps arg_ids) }
347 \end{code}
348
349
350
351 %************************************************************************
352 %*                                                                      *
353 \subsection{Generalisation}
354 %*                                                                      *
355 %************************************************************************
356
357 \begin{code}
358 tcGen :: SkolemInfo -> TcTyVarSet -> TcType  
359       -> ([TcTyVar] -> TcRhoType -> TcM result)
360       -> TcM (HsWrapper, result)
361         -- The expression has type: spec_ty -> expected_ty
362
363 tcGen skol_info extra_tvs 
364        expected_ty thing_inside    -- We expect expected_ty to be a forall-type
365                                    -- If not, the call is a no-op
366   = do  { traceTc "tcGen" empty
367         ; (wrap, tvs', given, rho') <- deeplySkolemise skol_info expected_ty
368
369         ; when debugIsOn $
370               traceTc "tcGen" $ vcat [
371                            text "expected_ty" <+> ppr expected_ty,
372                            text "inst ty" <+> ppr tvs' <+> ppr rho' ]
373
374         -- In 'free_tvs' we must check that the "forall_tvs" havn't been constrained
375         -- The interesting bit here is that we must include the free variables
376         -- of the expected_ty.  Here's an example:
377         --       runST (newVar True)
378         -- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
379         -- for (newVar True), with s fresh.  Then we unify with the runST's arg type
380         -- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
381         -- So now s' isn't unconstrained because it's linked to a.
382         -- Conclusion: pass the free vars of the expected_ty to checkConsraints
383         ; let free_tvs = tyVarsOfType expected_ty `unionVarSet` extra_tvs
384
385         ; (ev_binds, result) <- checkConstraints skol_info free_tvs tvs' given $
386                                 thing_inside tvs' rho'
387
388         ; return (wrap <.> mkWpLet ev_binds, result) }
389           -- The ev_binds returned by checkConstraints is very
390           -- often empty, in which case mkWpLet is a no-op
391
392 checkConstraints :: SkolemInfo
393                  -> TcTyVarSet          -- Free variables (other than the type envt)
394                                         -- for the skolem escape check
395                  -> [TcTyVar]           -- Skolems
396                  -> [EvVar]             -- Given
397                  -> TcM result
398                  -> TcM (TcEvBinds, result)
399
400 checkConstraints skol_info free_tvs skol_tvs given thing_inside
401   | null skol_tvs && null given
402   = do { res <- thing_inside; return (emptyTcEvBinds, res) }
403       -- Just for efficiency.  We check every function argument with
404       -- tcPolyExpr, which uses tcGen and hence checkConstraints.
405
406   | otherwise
407   = do { (ev_binds, wanted, result) <- newImplication skol_info free_tvs 
408                                              skol_tvs given thing_inside
409        ; emitConstraints wanted
410        ; return (ev_binds, result) }
411
412 newImplication :: SkolemInfo -> TcTyVarSet -> [TcTyVar]
413                -> [EvVar] -> TcM result
414                -> TcM (TcEvBinds, WantedConstraints, result)
415 newImplication skol_info free_tvs skol_tvs given thing_inside
416   = ASSERT2( all isTcTyVar skol_tvs, ppr skol_tvs )
417     ASSERT2( all isSkolemTyVar skol_tvs, ppr skol_tvs )
418     do { gbl_tvs  <- tcGetGlobalTyVars
419        ; free_tvs <- zonkTcTyVarsAndFV free_tvs
420        ; let untch = gbl_tvs `unionVarSet` free_tvs
421
422        ; (result, wanted) <- getConstraints               $ 
423                              setUntouchables untch $
424                              thing_inside
425
426        ; if isEmptyBag wanted && not (hasEqualities given) 
427             -- Optimisation : if there are no wanteds, and the givens
428             -- are sufficiently simple, don't generate an implication
429             -- at all.  Reason for the hasEqualities test:
430             -- we don't want to lose the "inaccessible alternative"
431             -- error check
432          then 
433             return (emptyTcEvBinds, emptyWanteds, result)
434          else do
435        { ev_binds_var <- newTcEvBinds
436        ; lcl_env <- getLclTypeEnv
437        ; loc <- getCtLoc skol_info
438        ; let implic = Implic { ic_untch = untch
439                              , ic_env = lcl_env
440                              , ic_skols = mkVarSet skol_tvs
441                              , ic_scoped = panic "emitImplication"
442                              , ic_given = given
443                              , ic_wanted = wanted
444                              , ic_binds = ev_binds_var
445                              , ic_loc = loc }
446
447        ; return (TcEvBinds ev_binds_var, unitBag (WcImplic implic), result) } }
448 \end{code}
449
450 %************************************************************************
451 %*                                                                      *
452                 Boxy unification
453 %*                                                                      *
454 %************************************************************************
455
456 The exported functions are all defined as versions of some
457 non-exported generic functions.
458
459 \begin{code}
460 ---------------
461 unifyType :: TcTauType -> TcTauType -> TcM CoercionI
462 -- Actual and expected types
463 -- Returns a coercion : ty1 ~ ty2
464 unifyType ty1 ty2 = uType [] ty1 ty2
465
466 ---------------
467 unifyPred :: PredType -> PredType -> TcM CoercionI
468 -- Actual and expected types
469 unifyPred p1 p2 = uPred [UnifyOrigin (mkPredTy p1) (mkPredTy p2)] p1 p2
470
471 ---------------
472 unifyTheta :: TcThetaType -> TcThetaType -> TcM [CoercionI]
473 -- Actual and expected types
474 unifyTheta theta1 theta2
475   = do  { checkTc (equalLength theta1 theta2)
476                   (vcat [ptext (sLit "Contexts differ in length"),
477                          nest 2 $ parens $ ptext (sLit "Use -XRelaxedPolyRec to allow this")])
478         ; zipWithM unifyPred theta1 theta2 }
479 \end{code}
480
481 @unifyTypeList@ takes a single list of @TauType@s and unifies them
482 all together.  It is used, for example, when typechecking explicit
483 lists, when all the elts should be of the same type.
484
485 \begin{code}
486 unifyTypeList :: [TcTauType] -> TcM ()
487 unifyTypeList []                 = return ()
488 unifyTypeList [_]                = return ()
489 unifyTypeList (ty1:tys@(ty2:_)) = do { _ <- unifyType ty1 ty2
490                                      ; unifyTypeList tys }
491 \end{code}
492
493 %************************************************************************
494 %*                                                                      *
495                  uType and friends                                                                      
496 %*                                                                      *
497 %************************************************************************
498
499 uType is the heart of the unifier.  Each arg occurs twice, because
500 we want to report errors in terms of synomyms if possible.  The first of
501 the pair is used in error messages only; it is always the same as the
502 second, except that if the first is a synonym then the second may be a
503 de-synonym'd version.  This way we get better error messages.
504
505 \begin{code}
506 data SwapFlag 
507   = NotSwapped  -- Args are: actual,   expected
508   | IsSwapped   -- Args are: expected, actual
509
510 instance Outputable SwapFlag where
511   ppr IsSwapped  = ptext (sLit "Is-swapped")
512   ppr NotSwapped = ptext (sLit "Not-swapped")
513
514 unSwap :: SwapFlag -> (a->a->b) -> a -> a -> b
515 unSwap NotSwapped f a b = f a b
516 unSwap IsSwapped  f a b = f b a
517
518 ------------
519 uType, uType_np, uType_defer
520   :: [EqOrigin]
521   -> TcType    -- ty1 is the *actual* type
522   -> TcType    -- ty2 is the *expected* type
523   -> TcM CoercionI
524
525 --------------
526 -- It is always safe to defer unification to the main constraint solver
527 -- See Note [Deferred unification]
528 uType_defer (item : origin) ty1 ty2
529   = do { co_var <- newWantedCoVar ty1 ty2
530        ; traceTc "utype_defer" (vcat [ppr co_var, ppr ty1, ppr ty2, ppr origin])
531        ; loc <- getCtLoc (TypeEqOrigin item)
532        ; wrapEqCtxt origin $
533          emitConstraint (WcEvVar (WantedEvVar co_var loc)) 
534        ; return $ ACo $ mkTyVarTy co_var }
535 uType_defer [] _ _
536   = panic "uType_defer"
537
538 --------------
539 -- Push a new item on the origin stack (the most common case)
540 uType origin ty1 ty2  -- Push a new item on the origin stack
541   = uType_np (pushOrigin ty1 ty2 origin) ty1 ty2
542
543 --------------
544 -- unify_np (short for "no push" on the origin stack) does the work
545 uType_np origin orig_ty1 orig_ty2
546   = do { traceTc "u_tys " $ vcat 
547               [ sep [ ppr orig_ty1, text "~", ppr orig_ty2]
548               , ppr origin]
549        ; coi <- go origin orig_ty1 orig_ty2
550        ; case coi of
551             ACo co -> traceTc "u_tys yields coercion:" (ppr co)
552             IdCo _ -> traceTc "u_tys yields no coercion" empty
553        ; return coi }
554   where
555     bale_out :: [EqOrigin] -> TcM a
556     bale_out origin = failWithMisMatch origin
557
558     go :: [EqOrigin] -> TcType -> TcType -> TcM CoercionI
559         -- The arguments to 'go' are always semantically identical 
560         -- to orig_ty{1,2} except for looking through type synonyms
561
562         -- Variables; go for uVar
563         -- Note that we pass in *original* (before synonym expansion), 
564         -- so that type variables tend to get filled in with 
565         -- the most informative version of the type
566     go origin (TyVarTy tyvar1) ty2 = uVar origin NotSwapped tyvar1 ty2
567     go origin ty1 (TyVarTy tyvar2) = uVar origin IsSwapped  tyvar2 ty1
568
569         -- Expand synonyms: 
570         --      see Note [Unification and synonyms]
571         -- Do this after the variable case so that we tend to unify
572         -- variables with un-expended type synonym
573     go origin ty1 ty2
574       | Just ty1' <- tcView ty1 = uType origin ty1' ty2
575       | Just ty2' <- tcView ty2 = uType origin ty1  ty2'
576
577         -- Predicates
578     go origin (PredTy p1) (PredTy p2) = uPred origin p1 p2
579
580         -- Coercion functions: (t1a ~ t1b) => t1c  ~  (t2a ~ t2b) => t2c
581     go origin ty1 ty2 
582       | Just (t1a,t1b,t1c) <- splitCoPredTy_maybe ty1, 
583         Just (t2a,t2b,t2c) <- splitCoPredTy_maybe ty2
584       = do { co1 <- uType origin t1a t2a 
585            ; co2 <- uType origin t1b t2b
586            ; co3 <- uType origin t1c t2c 
587            ; return $ mkCoPredCoI co1 co2 co3 }
588
589         -- Functions (or predicate functions) just check the two parts
590     go origin (FunTy fun1 arg1) (FunTy fun2 arg2)
591       = do { coi_l <- uType origin fun1 fun2
592            ; coi_r <- uType origin arg1 arg2
593            ; return $ mkFunTyCoI coi_l coi_r }
594
595         -- Always defer if a type synonym family (type function)
596         -- is involved.  (Data families behave rigidly.)
597     go origin ty1@(TyConApp tc1 _) ty2
598       | isSynFamilyTyCon tc1 = uType_defer origin ty1 ty2   
599     go origin ty1 ty2@(TyConApp tc2 _)
600       | isSynFamilyTyCon tc2 = uType_defer origin ty1 ty2   
601
602     go origin (TyConApp tc1 tys1) (TyConApp tc2 tys2)
603       | tc1 == tc2         -- See Note [TyCon app]
604       = do { cois <- uList origin uType tys1 tys2
605            ; return $ mkTyConAppCoI tc1 cois }
606      
607         -- See Note [Care with type applications]
608     go origin (AppTy s1 t1) ty2
609       | Just (s2,t2) <- tcSplitAppTy_maybe ty2
610       = do { coi_s <- uType_np origin s1 s2  -- See Note [Unifying AppTy]
611            ; coi_t <- uType origin t1 t2        
612            ; return $ mkAppTyCoI coi_s coi_t }
613
614     go origin ty1 (AppTy s2 t2)
615       | Just (s1,t1) <- tcSplitAppTy_maybe ty1
616       = do { coi_s <- uType_np origin s1 s2
617            ; coi_t <- uType origin t1 t2
618            ; return $ mkAppTyCoI coi_s coi_t }
619
620     go _ ty1 ty2
621       | tcIsForAllTy ty1 || tcIsForAllTy ty2 
622 {--      | isSigmaTy ty1 || isSigmaTy ty2 --} 
623       = unifySigmaTy origin ty1 ty2
624
625         -- Anything else fails
626     go origin _ _ = bale_out origin
627
628 unifySigmaTy :: [EqOrigin] -> TcType -> TcType -> TcM CoercionI
629 unifySigmaTy origin ty1 ty2
630   = do { let (tvs1, body1) = tcSplitForAllTys ty1
631              (tvs2, body2) = tcSplitForAllTys ty2
632        ; unless (equalLength tvs1 tvs2) (failWithMisMatch origin)
633        ; skol_tvs <- tcInstSkolTyVars UnkSkol tvs1     -- Not a helpful SkolemInfo
634                   -- Get location from monad, not from tvs1
635        ; let tys      = mkTyVarTys skol_tvs
636              in_scope = mkInScopeSet (mkVarSet skol_tvs)
637              phi1     = substTy (mkTvSubst in_scope (zipTyEnv tvs1 tys)) body1
638              phi2     = substTy (mkTvSubst in_scope (zipTyEnv tvs2 tys)) body2
639              untch = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
640
641        ; (coi, lie) <- getConstraints $ 
642                        setUntouchables untch $ 
643                        uType origin phi1 phi2
644
645           -- Check for escape; e.g. (forall a. a->b) ~ (forall a. a->a)
646        ; let bad_lie  = filterBag is_bad lie
647              is_bad w = any (`elemVarSet` tyVarsOfWanted w) skol_tvs
648        ; when (not (isEmptyBag bad_lie))
649               (failWithMisMatch origin) -- ToDo: give details from bad_lie
650
651        ; emitConstraints lie
652        ; return (foldr mkForAllTyCoI coi skol_tvs) }
653
654 ----------
655 uPred :: [EqOrigin] -> PredType -> PredType -> TcM CoercionI
656 uPred origin (IParam n1 t1) (IParam n2 t2)
657   | n1 == n2
658   = do { coi <- uType origin t1 t2
659        ; return $ mkIParamPredCoI n1 coi }
660 uPred origin (ClassP c1 tys1) (ClassP c2 tys2)
661   | c1 == c2 
662   = do { cois <- uList origin uType tys1 tys2
663           -- Guaranteed equal lengths because the kinds check
664        ; return $ mkClassPPredCoI c1 cois }
665 uPred origin (EqPred ty1a ty1b) (EqPred ty2a ty2b)
666   = do { coia <- uType origin ty1a ty2a
667        ; coib <- uType origin ty1b ty2b
668        ; return $ mkEqPredCoI coia coib }
669
670 uPred origin _ _ = failWithMisMatch origin
671
672 ---------------
673 uList :: [EqOrigin] 
674       -> ([EqOrigin] -> a -> a -> TcM b)
675       -> [a] -> [a] -> TcM [b]
676 -- Unify corresponding elements of two lists of types, which
677 -- should be of equal length.  We charge down the list explicitly so that
678 -- we can complain if their lengths differ.
679 uList _       _     []         []        = return []
680 uList origin unify (ty1:tys1) (ty2:tys2) = do { x  <- unify origin ty1 ty2;
681                                               ; xs <- uList origin unify tys1 tys2
682                                               ; return (x:xs) }
683 uList origin _ _ _ = failWithMisMatch origin
684        -- See Note [Mismatched type lists and application decomposition]
685
686 \end{code}
687
688 Note [Care with type applications]
689 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
690 Note: type applications need a bit of care!
691 They can match FunTy and TyConApp, so use splitAppTy_maybe
692 NB: we've already dealt with type variables and Notes,
693 so if one type is an App the other one jolly well better be too
694
695 Note [Unifying AppTy]
696 ~~~~~~~~~~~~~~~~~~~~~
697 Considerm unifying  (m Int) ~ (IO Int) where m is a unification variable 
698 that is now bound to (say) (Bool ->).  Then we want to report 
699      "Can't unify (Bool -> Int) with (IO Int)
700 and not 
701      "Can't unify ((->) Bool) with IO"
702 That is why we use the "_np" variant of uType, which does not alter the error
703 message.
704
705 Note [TyCon app]
706 ~~~~~~~~~~~~~~~~
707 When we find two TyConApps, the argument lists are guaranteed equal
708 length.  Reason: intially the kinds of the two types to be unified is
709 the same. The only way it can become not the same is when unifying two
710 AppTys (f1 a1)~(f2 a2).  In that case there can't be a TyConApp in
711 the f1,f2 (because it'd absorb the app).  If we unify f1~f2 first,
712 which we do, that ensures that f1,f2 have the same kind; and that
713 means a1,a2 have the same kind.  And now the argument repeats.
714
715 Note [Mismatched type lists and application decomposition]
716 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
717 When we find two TyConApps, you might think that the argument lists 
718 are guaranteed equal length.  But they aren't. Consider matching
719         w (T x) ~ Foo (T x y)
720 We do match (w ~ Foo) first, but in some circumstances we simply create
721 a deferred constraint; and then go ahead and match (T x ~ T x y).
722 This came up in Trac #3950.
723
724 So either 
725    (a) either we must check for identical argument kinds 
726        when decomposing applications,
727   
728    (b) or we must be prepared for ill-kinded unification sub-problems
729
730 Currently we adopt (b) since it seems more robust -- no need to maintain
731 a global invariant.
732
733 Note [Unification and synonyms]
734 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
735 If you are tempted to make a short cut on synonyms, as in this
736 pseudocode...
737
738    uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
739      = if (con1 == con2) then
740    -- Good news!  Same synonym constructors, so we can shortcut
741    -- by unifying their arguments and ignoring their expansions.
742    unifyTypepeLists args1 args2
743     else
744    -- Never mind.  Just expand them and try again
745    uTys ty1 ty2
746
747 then THINK AGAIN.  Here is the whole story, as detected and reported
748 by Chris Okasaki:
749
750 Here's a test program that should detect the problem:
751
752         type Bogus a = Int
753         x = (1 :: Bogus Char) :: Bogus Bool
754
755 The problem with [the attempted shortcut code] is that
756
757         con1 == con2
758
759 is not a sufficient condition to be able to use the shortcut!
760 You also need to know that the type synonym actually USES all
761 its arguments.  For example, consider the following type synonym
762 which does not use all its arguments.
763
764         type Bogus a = Int
765
766 If you ever tried unifying, say, (Bogus Char) with )Bogus Bool), the
767 unifier would blithely try to unify Char with Bool and would fail,
768 even though the expanded forms (both Int) should match. Similarly,
769 unifying (Bogus Char) with (Bogus t) would unnecessarily bind t to
770 Char.
771
772 ... You could explicitly test for the problem synonyms and mark them
773 somehow as needing expansion, perhaps also issuing a warning to the
774 user.
775
776 Note [Deferred Unification]
777 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
778 We may encounter a unification ty1 ~ ty2 that cannot be performed syntactically,
779 and yet its consistency is undetermined. Previously, there was no way to still
780 make it consistent. So a mismatch error was issued.
781
782 Now these unfications are deferred until constraint simplification, where type
783 family instances and given equations may (or may not) establish the consistency.
784 Deferred unifications are of the form
785                 F ... ~ ...
786 or              x ~ ...
787 where F is a type function and x is a type variable.
788 E.g.
789         id :: x ~ y => x -> y
790         id e = e
791
792 involves the unfication x = y. It is deferred until we bring into account the
793 context x ~ y to establish that it holds.
794
795 If available, we defer original types (rather than those where closed type
796 synonyms have already been expanded via tcCoreView).  This is, as usual, to
797 improve error messages.
798
799
800 %************************************************************************
801 %*                                                                      *
802                  uVar and friends
803 %*                                                                      *
804 %************************************************************************
805
806 @uVar@ is called when at least one of the types being unified is a
807 variable.  It does {\em not} assume that the variable is a fixed point
808 of the substitution; rather, notice that @uVar@ (defined below) nips
809 back into @uTys@ if it turns out that the variable is already bound.
810
811 \begin{code}
812 uVar :: [EqOrigin] -> SwapFlag -> TcTyVar -> TcTauType -> TcM CoercionI
813 uVar origin swapped tv1 ty2
814   = do  { traceTc "uVar" (vcat [ ppr origin
815                                 , ppr swapped
816                                 , ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1)
817                                 , nest 2 (ptext (sLit " ~ "))
818                                 , ppr ty2 <+> dcolon <+> ppr (typeKind ty2)])
819         ; details <- lookupTcTyVar tv1
820         ; case details of
821             Filled ty1  -> unSwap swapped (uType_np origin) ty1 ty2
822             Unfilled details1 -> uUnfilledVar origin swapped tv1 details1 ty2
823         }
824
825 ----------------
826 uUnfilledVar :: [EqOrigin]
827              -> SwapFlag
828              -> TcTyVar -> TcTyVarDetails       -- Tyvar 1
829              -> TcTauType                       -- Type 2
830              -> TcM CoercionI
831 -- "Unfilled" means that the variable is definitely not a filled-in meta tyvar
832 --            It might be a skolem, or untouchable, or meta
833
834 uUnfilledVar origin swapped tv1 details1 (TyVarTy tv2)
835   | tv1 == tv2  -- Same type variable => no-op
836   = return (IdCo (mkTyVarTy tv1))
837
838   | otherwise  -- Distinct type variables
839   = do  { lookup2 <- lookupTcTyVar tv2
840         ; case lookup2 of
841             Filled ty2'       -> uUnfilledVar origin swapped tv1 details1 ty2' 
842             Unfilled details2 -> uUnfilledVars origin swapped tv1 details1 tv2 details2
843         }
844
845 uUnfilledVar origin swapped tv1 details1 non_var_ty2  -- ty2 is not a type variable
846   = case details1 of
847       MetaTv TauTv ref1 
848         -> do { mb_ty2' <- checkTauTvUpdate tv1 non_var_ty2
849               ; case mb_ty2' of
850                   Nothing   -> do { traceTc "Occ/kind defer" (ppr tv1); defer }
851                   Just ty2' -> updateMeta tv1 ref1 ty2'
852               }
853
854       _other -> do { traceTc "Skolem defer" (ppr tv1); defer }          -- Skolems of all sorts
855   where
856     defer = unSwap swapped (uType_defer origin) (mkTyVarTy tv1) non_var_ty2
857           -- Occurs check or an untouchable: just defer
858           -- NB: occurs check isn't necessarily fatal: 
859           --     eg tv1 occured in type family parameter
860
861 ----------------
862 uUnfilledVars :: [EqOrigin]
863               -> SwapFlag
864               -> TcTyVar -> TcTyVarDetails      -- Tyvar 1
865               -> TcTyVar -> TcTyVarDetails      -- Tyvar 2
866               -> TcM CoercionI
867 -- Invarant: The type variables are distinct,
868 --           Neither is filled in yet
869
870 uUnfilledVars origin swapped tv1 details1 tv2 details2
871   = case (details1, details2) of
872       (MetaTv i1 ref1, MetaTv i2 ref2)
873           | k1_sub_k2 -> if k2_sub_k1 && nicer_to_update_tv1 i1 i2
874                          then updateMeta tv1 ref1 ty2
875                          else updateMeta tv2 ref2 ty1
876           | k2_sub_k1 -> updateMeta tv1 ref1 ty2
877
878       (_, MetaTv _ ref2) | k1_sub_k2 -> updateMeta tv2 ref2 ty1
879       (MetaTv _ ref1, _) | k2_sub_k1 -> updateMeta tv1 ref1 ty2
880
881       (_, _) -> unSwap swapped (uType_defer origin) ty1 ty2
882                 -- Defer for skolems of all sorts
883   where
884     k1        = tyVarKind tv1
885     k2        = tyVarKind tv2
886     k1_sub_k2 = k1 `isSubKind` k2
887     k2_sub_k1 = k2 `isSubKind` k1
888     ty1       = mkTyVarTy tv1
889     ty2       = mkTyVarTy tv2
890
891     nicer_to_update_tv1 _         (SigTv _) = True
892     nicer_to_update_tv1 (SigTv _) _         = False
893     nicer_to_update_tv1 _         _         = isSystemName (Var.varName tv1)
894         -- Try not to update SigTvs; and try to update sys-y type
895         -- variables in preference to ones gotten (say) by
896         -- instantiating a polymorphic function with a user-written
897         -- type sig
898
899 ----------------
900 checkTauTvUpdate :: TcTyVar -> TcType -> TcM (Maybe TcType)
901 --    (checkTauTvUpdate tv ty)
902 -- We are about to update the TauTv tv with ty.
903 -- Check (a) that tv doesn't occur in ty (occurs check)
904 --       (b) that kind(ty) is a sub-kind of kind(tv)
905 --       (c) that ty does not contain any type families, see Note [Type family sharing]
906 -- 
907 -- We have two possible outcomes:
908 -- (1) Return the type to update the type variable with, 
909 --        [we know the update is ok]
910 -- (2) Return Nothing,
911 --        [the update might be dodgy]
912 --
913 -- Note that "Nothing" does not mean "definite error".  For example
914 --   type family F a
915 --   type instance F Int = Int
916 -- consider
917 --   a ~ F a
918 -- This is perfectly reasonable, if we later get a ~ Int.  For now, though,
919 -- we return Nothing, leaving it to the later constraint simplifier to
920 -- sort matters out.
921
922 checkTauTvUpdate tv ty
923   = do { ty' <- zonkTcType ty
924        ; if typeKind ty' `isSubKind` tyVarKind tv then
925            case ok ty' of 
926              Nothing -> return Nothing 
927              Just ty'' -> return (Just ty'')
928          else return Nothing }
929
930   where ok :: TcType -> Maybe TcType 
931         ok (TyVarTy tv') | not (tv == tv') = Just (TyVarTy tv') 
932         ok this_ty@(TyConApp tc tys) 
933           | not (isSynFamilyTyCon tc), Just tys' <- allMaybes (map ok tys) 
934           = Just (TyConApp tc tys') 
935           | isSynTyCon tc, Just ty_expanded <- tcView this_ty
936           = ok ty_expanded -- See Note [Type synonyms and the occur check] 
937         ok (PredTy sty) | Just sty' <- ok_pred sty = Just (PredTy sty') 
938         ok (FunTy arg res) | Just arg' <- ok arg, Just res' <- ok res
939                            = Just (FunTy arg' res') 
940         ok (AppTy fun arg) | Just fun' <- ok fun, Just arg' <- ok arg 
941                            = Just (AppTy fun' arg') 
942         ok (ForAllTy tv1 ty1) | Just ty1' <- ok ty1 = Just (ForAllTy tv1 ty1') 
943         -- Fall-through 
944         ok _ty = Nothing 
945        
946         ok_pred (IParam nm ty) | Just ty' <- ok ty = Just (IParam nm ty') 
947         ok_pred (ClassP cl tys) 
948           | Just tys' <- allMaybes (map ok tys) 
949           = Just (ClassP cl tys') 
950         ok_pred (EqPred ty1 ty2) 
951           | Just ty1' <- ok ty1, Just ty2' <- ok ty2 
952           = Just (EqPred ty1' ty2') 
953         -- Fall-through 
954         ok_pred _pty = Nothing 
955
956 \end{code}
957
958 Note [Type synonyms and the occur check]
959 ~~~~~~~~~~~~~~~~~~~~
960 Generally speaking we need to update a variable with type synonyms not expanded, which
961 improves later error messages, except for when looking inside a type synonym may help resolve
962 a spurious occurs check error. Consider: 
963           type A a = ()
964
965           f :: (A a -> a -> ()) -> ()
966           f = \ _ -> ()
967
968           x :: ()
969           x = f (\ x p -> p x)
970
971 We will eventually get a constraint of the form t ~ A t. The ok function above will 
972 properly expand the type (A t) to just (), which is ok to be unified with t. If we had
973 unified with the original type A t, we would lead the type checker into an infinite loop. 
974
975 Hence, if the occurs check fails for a type synonym application, then (and *only* then), 
976 the ok function expands the synonym to detect opportunities for occurs check success using
977 the underlying definition of the type synonym. 
978
979 The same applies later on in the constraint interaction code; see TcInteract, 
980 function @occ_check_ok@. 
981
982
983 Note [Type family sharing]
984 ~~~~~~~~~~~~~~ 
985 We must avoid eagerly unifying type variables to types that contain function symbols, 
986 because this may lead to loss of sharing, and in turn, in very poor performance of the
987 constraint simplifier. Assume that we have a wanted constraint: 
988
989   m1 ~ [F m2], 
990   m2 ~ [F m3], 
991   m3 ~ [F m4], 
992   D m1, 
993   D m2, 
994   D m3 
995
996 where D is some type class. If we eagerly unify m1 := [F m2], m2 := [F m3], m3 := [F m2], 
997 then, after zonking, our constraint simplifier will be faced with the following wanted 
998 constraint: 
999
1000   D [F [F [F m4]]], 
1001   D [F [F m4]], 
1002   D [F m4] 
1003
1004 which has to be flattened by the constraint solver. However, because the sharing is lost, 
1005 an polynomially larger number of flatten skolems will be created and the constraint sets 
1006 we are working with will be polynomially larger. 
1007
1008 Instead, if we defer the unifications m1 := [F m2], etc. we will only be generating three 
1009 flatten skolems, which is the maximum possible sharing arising from the original constraint. 
1010
1011 \begin{code}
1012 data LookupTyVarResult  -- The result of a lookupTcTyVar call
1013   = Unfilled TcTyVarDetails     -- SkolemTv or virgin MetaTv
1014   | Filled   TcType
1015
1016 lookupTcTyVar :: TcTyVar -> TcM LookupTyVarResult
1017 lookupTcTyVar tyvar 
1018   | MetaTv _ ref <- details
1019   = do { meta_details <- readMutVar ref
1020        ; case meta_details of
1021            Indirect ty -> return (Filled ty)
1022            Flexi -> do { is_untch <- isUntouchable tyvar
1023                        ; let    -- Note [Unifying untouchables]
1024                              ret_details | is_untch = SkolemTv UnkSkol
1025                                          | otherwise = details
1026                        ; return (Unfilled ret_details) } }
1027   | otherwise
1028   = return (Unfilled details)
1029   where
1030     details = ASSERT2( isTcTyVar tyvar, ppr tyvar )
1031               tcTyVarDetails tyvar
1032
1033 updateMeta :: TcTyVar -> TcRef MetaDetails -> TcType -> TcM CoercionI
1034 updateMeta tv1 ref1 ty2
1035   = do { writeMetaTyVarRef tv1 ref1 ty2
1036        ; return (IdCo ty2) }
1037 \end{code}
1038
1039 Note [Unifying untouchables]
1040 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1041 We treat an untouchable type variable as if it was a skolem.  That
1042 ensures it won't unify with anything.  It's a slight had, because
1043 we return a made-up TcTyVarDetails, but I think it works smoothly.
1044
1045
1046 %************************************************************************
1047 %*                                                                      *
1048         Errors and contexts
1049 %*                                                                      *
1050 %************************************************************************
1051
1052 \begin{code}
1053 pushOrigin :: TcType -> TcType -> [EqOrigin] -> [EqOrigin]
1054 pushOrigin ty_act ty_exp origin
1055   = UnifyOrigin { uo_actual = ty_act, uo_expected = ty_exp } : origin
1056
1057 ---------------
1058 wrapEqCtxt :: [EqOrigin] -> TcM a -> TcM a
1059 -- Build a suitable error context from the origin and do the thing inside
1060 -- The "couldn't match" error comes from the innermost item on the stack,
1061 -- and, if there is more than one item, the "Expected/inferred" part
1062 -- comes from the outermost item
1063 wrapEqCtxt []    thing_inside = thing_inside
1064 wrapEqCtxt items thing_inside = addErrCtxtM (unifyCtxt (last items)) thing_inside
1065
1066 ---------------
1067 failWithMisMatch :: [EqOrigin] -> TcM a
1068 -- Generate the message when two types fail to match,
1069 -- going to some trouble to make it helpful.
1070 -- We take the failing types from the top of the origin stack
1071 -- rather than reporting the particular ones we are looking 
1072 -- at right now
1073 failWithMisMatch (item:origin)
1074   = wrapEqCtxt origin $
1075     do  { ty_act <- zonkTcType (uo_actual item)
1076         ; ty_exp <- zonkTcType (uo_expected item)
1077         ; env0 <- tcInitTidyEnv
1078         ; let (env1, pp_exp) = tidyOpenType env0 ty_exp
1079               (env2, pp_act) = tidyOpenType env1 ty_act
1080         ; failWithTcM (misMatchMsg env2 pp_act pp_exp) }
1081 failWithMisMatch [] 
1082   = panic "failWithMisMatch"
1083
1084 misMatchMsg :: TidyEnv -> TcType -> TcType -> (TidyEnv, SDoc)
1085 misMatchMsg env ty_act ty_exp
1086   = (env2, sep [sep [ ptext (sLit "Couldn't match expected type") <+> quotes (ppr ty_exp)
1087                     , nest 12 $   ptext (sLit "with actual type") <+> quotes (ppr ty_act)]
1088                , nest 2 (extra1 $$ extra2) ])
1089   where
1090     (env1, extra1) = typeExtraInfoMsg env  ty_exp
1091     (env2, extra2) = typeExtraInfoMsg env1 ty_act
1092 \end{code}
1093
1094
1095 -----------------------------------------
1096         UNUSED FOR NOW
1097 -----------------------------------------
1098
1099 ----------------
1100 ----------------
1101 -- If an error happens we try to figure out whether the function
1102 -- function has been given too many or too few arguments, and say so.
1103 addSubCtxt :: InstOrigin -> TcType -> TcType -> TcM a -> TcM a
1104 addSubCtxt orig actual_res_ty expected_res_ty thing_inside
1105   = addErrCtxtM mk_err thing_inside
1106   where
1107     mk_err tidy_env
1108       = do { exp_ty' <- zonkTcType expected_res_ty
1109            ; act_ty' <- zonkTcType actual_res_ty
1110            ; let (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1111                  (env2, act_ty'') = tidyOpenType env1     act_ty'
1112                  (exp_args, _)    = tcSplitFunTys exp_ty''
1113                  (act_args, _)    = tcSplitFunTys act_ty''
1114
1115                  len_act_args     = length act_args
1116                  len_exp_args     = length exp_args
1117
1118                  message = case orig of
1119                              OccurrenceOf fun
1120                                   | len_exp_args < len_act_args -> wrongArgsCtxt "too few"  fun
1121                                   | len_exp_args > len_act_args -> wrongArgsCtxt "too many" fun
1122                              _ -> mkExpectedActualMsg act_ty'' exp_ty''
1123            ; return (env2, message) }
1124
1125
1126 %************************************************************************
1127 %*                                                                      *
1128                 Kind unification
1129 %*                                                                      *
1130 %************************************************************************
1131
1132 Unifying kinds is much, much simpler than unifying types.
1133
1134 \begin{code}
1135 matchExpectedFunKind :: TcKind -> TcM (Maybe (TcKind, TcKind))
1136 -- Like unifyFunTy, but does not fail; instead just returns Nothing
1137
1138 matchExpectedFunKind (TyVarTy kvar) = do
1139     maybe_kind <- readKindVar kvar
1140     case maybe_kind of
1141       Indirect fun_kind -> matchExpectedFunKind fun_kind
1142       Flexi ->
1143           do { arg_kind <- newKindVar
1144              ; res_kind <- newKindVar
1145              ; writeKindVar kvar (mkArrowKind arg_kind res_kind)
1146              ; return (Just (arg_kind,res_kind)) }
1147
1148 matchExpectedFunKind (FunTy arg_kind res_kind) = return (Just (arg_kind,res_kind))
1149 matchExpectedFunKind _                         = return Nothing
1150
1151 -----------------
1152 unifyKind :: TcKind                 -- Expected
1153           -> TcKind                 -- Actual
1154           -> TcM ()
1155
1156 unifyKind (TyConApp kc1 []) (TyConApp kc2 [])
1157   | isSubKindCon kc2 kc1 = return ()
1158
1159 unifyKind (FunTy a1 r1) (FunTy a2 r2)
1160   = do { unifyKind a2 a1; unifyKind r1 r2 }
1161                 -- Notice the flip in the argument,
1162                 -- so that the sub-kinding works right
1163 unifyKind (TyVarTy kv1) k2 = uKVar False kv1 k2
1164 unifyKind k1 (TyVarTy kv2) = uKVar True kv2 k1
1165 unifyKind k1 k2 = unifyKindMisMatch k1 k2
1166
1167 ----------------
1168 uKVar :: Bool -> KindVar -> TcKind -> TcM ()
1169 uKVar swapped kv1 k2
1170   = do  { mb_k1 <- readKindVar kv1
1171         ; case mb_k1 of
1172             Flexi -> uUnboundKVar swapped kv1 k2
1173             Indirect k1 | swapped   -> unifyKind k2 k1
1174                         | otherwise -> unifyKind k1 k2 }
1175
1176 ----------------
1177 uUnboundKVar :: Bool -> KindVar -> TcKind -> TcM ()
1178 uUnboundKVar swapped kv1 k2@(TyVarTy kv2)
1179   | kv1 == kv2 = return ()
1180   | otherwise   -- Distinct kind variables
1181   = do  { mb_k2 <- readKindVar kv2
1182         ; case mb_k2 of
1183             Indirect k2 -> uUnboundKVar swapped kv1 k2
1184             Flexi -> writeKindVar kv1 k2 }
1185
1186 uUnboundKVar swapped kv1 non_var_k2
1187   = do  { k2' <- zonkTcKind non_var_k2
1188         ; kindOccurCheck kv1 k2'
1189         ; k2'' <- kindSimpleKind swapped k2'
1190                 -- KindVars must be bound only to simple kinds
1191                 -- Polarities: (kindSimpleKind True ?) succeeds
1192                 -- returning *, corresponding to unifying
1193                 --      expected: ?
1194                 --      actual:   kind-ver
1195         ; writeKindVar kv1 k2'' }
1196
1197 ----------------
1198 kindOccurCheck :: TyVar -> Type -> TcM ()
1199 kindOccurCheck kv1 k2   -- k2 is zonked
1200   = checkTc (not_in k2) (kindOccurCheckErr kv1 k2)
1201   where
1202     not_in (TyVarTy kv2) = kv1 /= kv2
1203     not_in (FunTy a2 r2) = not_in a2 && not_in r2
1204     not_in _             = True
1205
1206 kindSimpleKind :: Bool -> Kind -> TcM SimpleKind
1207 -- (kindSimpleKind True k) returns a simple kind sk such that sk <: k
1208 -- If the flag is False, it requires k <: sk
1209 -- E.g.         kindSimpleKind False ?? = *
1210 -- What about (kv -> *) ~ ?? -> *
1211 kindSimpleKind orig_swapped orig_kind
1212   = go orig_swapped orig_kind
1213   where
1214     go sw (FunTy k1 k2) = do { k1' <- go (not sw) k1
1215                              ; k2' <- go sw k2
1216                              ; return (mkArrowKind k1' k2') }
1217     go True k
1218      | isOpenTypeKind k = return liftedTypeKind
1219      | isArgTypeKind k  = return liftedTypeKind
1220     go _ k
1221      | isLiftedTypeKind k   = return liftedTypeKind
1222      | isUnliftedTypeKind k = return unliftedTypeKind
1223     go _ k@(TyVarTy _) = return k -- KindVars are always simple
1224     go _ _ = failWithTc (ptext (sLit "Unexpected kind unification failure:")
1225                                   <+> ppr orig_swapped <+> ppr orig_kind)
1226         -- I think this can't actually happen
1227
1228 -- T v = MkT v           v must be a type
1229 -- T v w = MkT (v -> w)  v must not be an umboxed tuple
1230
1231 unifyKindMisMatch :: TcKind -> TcKind -> TcM ()
1232 unifyKindMisMatch ty1 ty2 = do
1233     ty1' <- zonkTcKind ty1
1234     ty2' <- zonkTcKind ty2
1235     let
1236         msg = hang (ptext (sLit "Couldn't match kind"))
1237                    2 (sep [quotes (ppr ty1'), 
1238                            ptext (sLit "against"), 
1239                            quotes (ppr ty2')])
1240     failWithTc msg
1241
1242 ----------------
1243 kindOccurCheckErr :: Var -> Type -> SDoc
1244 kindOccurCheckErr tyvar ty
1245   = hang (ptext (sLit "Occurs check: cannot construct the infinite kind:"))
1246        2 (sep [ppr tyvar, char '=', ppr ty])
1247 \end{code}
1248
1249 %************************************************************************
1250 %*                                                                      *
1251 \subsection{Checking signature type variables}
1252 %*                                                                      *
1253 %************************************************************************
1254
1255 @checkSigTyVars@ checks that a set of universally quantified type varaibles
1256 are not mentioned in the environment.  In particular:
1257
1258         (a) Not mentioned in the type of a variable in the envt
1259                 eg the signature for f in this:
1260
1261                         g x = ... where
1262                                         f :: a->[a]
1263                                         f y = [x,y]
1264
1265                 Here, f is forced to be monorphic by the free occurence of x.
1266
1267         (d) Not (unified with another type variable that is) in scope.
1268                 eg f x :: (r->r) = (\y->y) :: forall a. a->r
1269             when checking the expression type signature, we find that
1270             even though there is nothing in scope whose type mentions r,
1271             nevertheless the type signature for the expression isn't right.
1272
1273             Another example is in a class or instance declaration:
1274                 class C a where
1275                    op :: forall b. a -> b
1276                    op x = x
1277             Here, b gets unified with a
1278
1279 Before doing this, the substitution is applied to the signature type variable.
1280
1281 -- \begin{code}
1282 checkSigTyVars :: [TcTyVar] -> TcM ()
1283 checkSigTyVars sig_tvs = check_sig_tyvars emptyVarSet sig_tvs
1284
1285 checkSigTyVarsWrt :: TcTyVarSet -> [TcTyVar] -> TcM ()
1286 -- The extra_tvs can include boxy type variables;
1287 --      e.g. TcMatches.tcCheckExistentialPat
1288 checkSigTyVarsWrt extra_tvs sig_tvs
1289   = do  { extra_tvs' <- zonkTcTyVarsAndFV extra_tvs
1290         ; check_sig_tyvars extra_tvs' sig_tvs }
1291
1292 check_sig_tyvars
1293         :: TcTyVarSet   -- Global type variables. The universally quantified
1294                         --      tyvars should not mention any of these
1295                         --      Guaranteed already zonked.
1296         -> [TcTyVar]    -- Universally-quantified type variables in the signature
1297                         --      Guaranteed to be skolems
1298         -> TcM ()
1299 check_sig_tyvars _ []
1300   = return ()
1301 check_sig_tyvars extra_tvs sig_tvs
1302   = ASSERT( all isTcTyVar sig_tvs && all isSkolemTyVar sig_tvs )
1303     do  { gbl_tvs <- tcGetGlobalTyVars
1304         ; traceTc "check_sig_tyvars" $ vcat 
1305                [ text "sig_tys" <+> ppr sig_tvs
1306                , text "gbl_tvs" <+> ppr gbl_tvs
1307                , text "extra_tvs" <+> ppr extra_tvs]
1308
1309         ; let env_tvs = gbl_tvs `unionVarSet` extra_tvs
1310         ; when (any (`elemVarSet` env_tvs) sig_tvs)
1311                (bleatEscapedTvs env_tvs sig_tvs sig_tvs)
1312         }
1313
1314 bleatEscapedTvs :: TcTyVarSet   -- The global tvs
1315                 -> [TcTyVar]    -- The possibly-escaping type variables
1316                 -> [TcTyVar]    -- The zonked versions thereof
1317                 -> TcM ()
1318 -- Complain about escaping type variables
1319 -- We pass a list of type variables, at least one of which
1320 -- escapes.  The first list contains the original signature type variable,
1321 -- while the second  contains the type variable it is unified to (usually itself)
1322 bleatEscapedTvs globals sig_tvs zonked_tvs
1323   = do  { env0 <- tcInitTidyEnv
1324         ; let (env1, tidy_tvs)        = tidyOpenTyVars env0 sig_tvs
1325               (env2, tidy_zonked_tvs) = tidyOpenTyVars env1 zonked_tvs
1326
1327         ; (env3, msgs) <- foldlM check (env2, []) (tidy_tvs `zip` tidy_zonked_tvs)
1328         ; failWithTcM (env3, main_msg $$ nest 2 (vcat msgs)) }
1329   where
1330     main_msg = ptext (sLit "Inferred type is less polymorphic than expected")
1331
1332     check (tidy_env, msgs) (sig_tv, zonked_tv)
1333       | not (zonked_tv `elemVarSet` globals) = return (tidy_env, msgs)
1334       | otherwise
1335       = do { lcl_env <- getLclTypeEnv
1336            ; (tidy_env1, globs) <- findGlobals (unitVarSet zonked_tv) lcl_env tidy_env
1337            ; return (tidy_env1, escape_msg sig_tv zonked_tv globs : msgs) }
1338
1339 -----------------------
1340 escape_msg :: Var -> Var -> [SDoc] -> SDoc
1341 escape_msg sig_tv zonked_tv globs
1342   | notNull globs
1343   = vcat [sep [msg, ptext (sLit "is mentioned in the environment:")],
1344           nest 2 (vcat globs)]
1345   | otherwise
1346   = msg <+> ptext (sLit "escapes")
1347         -- Sigh.  It's really hard to give a good error message
1348         -- all the time.   One bad case is an existential pattern match.
1349         -- We rely on the "When..." context to help.
1350   where
1351     msg = ptext (sLit "Quantified type variable") <+> quotes (ppr sig_tv) <+> is_bound_to
1352     is_bound_to
1353         | sig_tv == zonked_tv = empty
1354         | otherwise = ptext (sLit "is unified with") <+> quotes (ppr zonked_tv) <+> ptext (sLit "which")
1355 -- \end{code}
1356
1357 These two context are used with checkSigTyVars
1358
1359 \begin{code}
1360 sigCtxt :: Id -> [TcTyVar] -> TcThetaType -> TcTauType
1361         -> TidyEnv -> TcM (TidyEnv, Message)
1362 sigCtxt id sig_tvs sig_theta sig_tau tidy_env = do
1363     actual_tau <- zonkTcType sig_tau
1364     let
1365         (env1, tidy_sig_tvs)    = tidyOpenTyVars tidy_env sig_tvs
1366         (env2, tidy_sig_rho)    = tidyOpenType env1 (mkPhiTy sig_theta sig_tau)
1367         (env3, tidy_actual_tau) = tidyOpenType env2 actual_tau
1368         sub_msg = vcat [ptext (sLit "Signature type:    ") <+> pprType (mkForAllTys tidy_sig_tvs tidy_sig_rho),
1369                         ptext (sLit "Type to generalise:") <+> pprType tidy_actual_tau
1370                    ]
1371         msg = vcat [ptext (sLit "When trying to generalise the type inferred for") <+> quotes (ppr id),
1372                     nest 2 sub_msg]
1373
1374     return (env3, msg)
1375 \end{code}