TcSimplify.lhs 55.2 KB
Newer Older
1
\begin{code}
2
module TcSimplify( 
3
       simplifyInfer,
4
       simplifyDefault, simplifyDeriv, 
5 6
       simplifyRule, simplifyTop, simplifyInteractive
  ) where
7

8
#include "HsVersions.h"
9

10
import HsSyn	       
11
import TcRnMonad
12
import TcErrors
13
import TcMType
14 15 16 17
import TcType 
import TcSMonad 
import TcInteract
import Inst
18
import Unify	( niFixTvSubst, niSubstTvSet )
19
import Var
20
import VarSet
21
import VarEnv 
22
import Coercion
23
import TypeRep
24

25 26
import Name
import NameEnv	( emptyNameEnv )
27
import Bag
28 29
import ListSetOps
import Util
30 31 32
import PrelInfo
import PrelNames
import Class		( classKey )
33 34
import BasicTypes       ( RuleName, TopLevelFlag, isTopLevel )
import Control.Monad    ( when )
35
import Outputable
36
import FastString
37 38 39
\end{code}


40 41 42 43 44
*********************************************************************************
*                                                                               * 
*                           External interface                                  *
*                                                                               *
*********************************************************************************
45

46 47 48
\begin{code}
simplifyTop :: WantedConstraints -> TcM (Bag EvBind)
-- Simplify top-level constraints
49 50 51
-- Usually these will be implications,
-- but when there is nothing to quantify we don't wrap
-- in a degenerate implication, so we do that here instead
52
simplifyTop wanteds 
53
  = simplifyCheck (SimplCheck (ptext (sLit "top level"))) wanteds
54 55 56 57 58 59 60 61 62 63

------------------
simplifyInteractive :: WantedConstraints -> TcM (Bag EvBind)
simplifyInteractive wanteds 
  = simplifyCheck SimplInteractive wanteds

------------------
simplifyDefault :: ThetaType	-- Wanted; has no type variables in it
                -> TcM ()	-- Succeeds iff the constraint is soluble
simplifyDefault theta
64
  = do { wanted <- newFlatWanteds DefaultOrigin theta
65 66
       ; _ignored_ev_binds <- simplifyCheck (SimplCheck (ptext (sLit "defaults"))) 
                                            (mkFlatWC wanted)
67 68
       ; return () }
\end{code}
69

70

71

72 73 74 75 76
*********************************************************************************
*                                                                                 * 
*                            Deriving
*                                                                                 *
***********************************************************************************
77

78 79
\begin{code}
simplifyDeriv :: CtOrigin
80 81 82 83
              -> PredType
	      -> [TyVar]	
	      -> ThetaType		-- Wanted
	      -> TcM ThetaType	-- Needed
84 85
-- Given  instance (wanted) => C inst_ty 
-- Simplify 'wanted' as much as possibles
86
-- Fail if not possible
87
simplifyDeriv orig pred tvs theta 
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
88 89 90 91 92
  = do { tvs_skols <- tcInstSkolTyVars tvs -- Skolemize
      	 	-- The constraint solving machinery 
		-- expects *TcTyVars* not TyVars.  
		-- We use *non-overlappable* (vanilla) skolems
		-- See Note [Overlap and deriving]
93 94

       ; let skol_subst = zipTopTvSubst tvs $ map mkTyVarTy tvs_skols
95
             subst_skol = zipTopTvSubst tvs_skols $ map mkTyVarTy tvs
96
             skol_set   = mkVarSet tvs_skols
97
	     doc = parens $ ptext (sLit "deriving") <+> parens (ppr pred)
98 99 100 101 102

       ; wanted <- newFlatWanteds orig (substTheta skol_subst theta)

       ; traceTc "simplifyDeriv" (ppr tvs $$ ppr theta $$ ppr wanted)
       ; (residual_wanted, _binds)
103
             <- runTcS (SimplInfer doc) NoUntouchables $
104
                solveWanteds emptyInert (mkFlatWC wanted)
105

106 107 108
       ; let (good, bad) = partitionBagWith get_good (wc_flat residual_wanted)
                         -- See Note [Exotic derived instance contexts]
             get_good :: WantedEvVar -> Either PredType WantedEvVar
109 110
             get_good wev | validDerivPred skol_set p = Left p
                          | otherwise                 = Right wev
111
                          where p = evVarOfPred wev
112

113
       ; reportUnsolved (residual_wanted { wc_flat = bad })
114

115 116
       ; let min_theta = mkMinimalBySCs (bagToList good)
       ; return (substTheta subst_skol min_theta) }
117
\end{code}
118

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
Note [Overlap and deriving]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider some overlapping instances:
  data Show a => Show [a] where ..
  data Show [Char] where ...

Now a data type with deriving:
  data T a = MkT [a] deriving( Show )

We want to get the derived instance
  instance Show [a] => Show (T a) where...
and NOT
  instance Show a => Show (T a) where...
so that the (Show (T Char)) instance does the Right Thing

It's very like the situation when we're inferring the type
of a function
   f x = show [x]
and we want to infer
   f :: Show [a] => a -> String

BOTTOM LINE: use vanilla, non-overlappable skolems when inferring
             the context for the derived instance. 
	     Hence tcInstSkolTyVars not tcInstSuperSkolTyVars

144 145 146 147 148 149 150
Note [Exotic derived instance contexts]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In a 'derived' instance declaration, we *infer* the context.  It's a
bit unclear what rules we should apply for this; the Haskell report is
silent.  Obviously, constraints like (Eq a) are fine, but what about
	data T f a = MkT (f a) deriving( Eq )
where we'd get an Eq (f a) constraint.  That's probably fine too.
151

152 153 154
One could go further: consider
	data T a b c = MkT (Foo a b c) deriving( Eq )
	instance (C Int a, Eq b, Eq c) => Eq (Foo a b c)
155

156 157
Notice that this instance (just) satisfies the Paterson termination 
conditions.  Then we *could* derive an instance decl like this:
158

159 160 161 162
	instance (C Int a, Eq b, Eq c) => Eq (T a b c) 
even though there is no instance for (C Int a), because there just
*might* be an instance for, say, (C Int Bool) at a site where we
need the equality instance for T's.  
163

164 165 166
However, this seems pretty exotic, and it's quite tricky to allow
this, and yet give sensible error messages in the (much more common)
case where we really want that instance decl for C.
167

168 169
So for now we simply require that the derived instance context
should have only type-variable constraints.
170

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
Here is another example:
	data Fix f = In (f (Fix f)) deriving( Eq )
Here, if we are prepared to allow -XUndecidableInstances we
could derive the instance
	instance Eq (f (Fix f)) => Eq (Fix f)
but this is so delicate that I don't think it should happen inside
'deriving'. If you want this, write it yourself!

NB: if you want to lift this condition, make sure you still meet the
termination conditions!  If not, the deriving mechanism generates
larger and larger constraints.  Example:
  data Succ a = S a
  data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show

Note the lack of a Show instance for Succ.  First we'll generate
  instance (Show (Succ a), Show a) => Show (Seq a)
and then
  instance (Show (Succ (Succ a)), Show (Succ a), Show a) => Show (Seq a)
and so on.  Instead we want to complain of no instance for (Show (Succ a)).

The bottom line
~~~~~~~~~~~~~~~
Allow constraints which consist only of type variables, with no repeats.

*********************************************************************************
*                                                                                 * 
*                            Inference
*                                                                                 *
***********************************************************************************
200

201
\begin{code}
202 203 204 205
simplifyInfer :: TopLevelFlag
              -> Bool                  -- Apply monomorphism restriction
              -> [(Name, TcTauType)]   -- Variables to be generalised,
                                       -- and their tau-types
206 207 208 209
              -> WantedConstraints
              -> TcM ([TcTyVar],    -- Quantify over these type variables
                      [EvVar],      -- ... and these constraints
                      TcEvBinds)    -- ... binding these evidence variables
210 211 212 213 214 215
simplifyInfer top_lvl apply_mr name_taus wanteds
  | isEmptyWC wanteds
  = do { gbl_tvs     <- tcGetGlobalTyVars            -- Already zonked
       ; zonked_taus <- zonkTcTypes (map snd name_taus)
       ; let tvs_to_quantify = get_tau_tvs zonked_taus `minusVarSet` gbl_tvs
       ; qtvs <- zonkQuantifiedTyVars (varSetElems tvs_to_quantify)
216
       ; return (qtvs, [], emptyTcEvBinds) }
217

218
  | otherwise
219 220 221 222
  = do { zonked_wanteds <- zonkWC wanteds
       ; zonked_taus    <- zonkTcTypes (map snd name_taus)
       ; gbl_tvs        <- tcGetGlobalTyVars

223 224
       ; traceTc "simplifyInfer {"  $ vcat
             [ ptext (sLit "apply_mr =") <+> ppr apply_mr
225 226
             , ptext (sLit "zonked_taus =") <+> ppr zonked_taus
             , ptext (sLit "wanted =") <+> ppr zonked_wanteds
227 228
             ]

229 230
             -- Step 1
             -- Make a guess at the quantified type variables
231 232 233
	     -- Then split the constraints on the baisis of those tyvars
	     -- to avoid unnecessarily simplifying a class constraint
	     -- See Note [Avoid unecessary constraint simplification]
234 235
       ; let zonked_tau_tvs = get_tau_tvs zonked_taus
             proto_qtvs = growWanteds gbl_tvs zonked_wanteds $
236
                          zonked_tau_tvs `minusVarSet` gbl_tvs
237 238 239 240 241 242 243 244 245 246
             (perhaps_bound, surely_free)
                        = partitionBag (quantifyMe proto_qtvs) (wc_flat zonked_wanteds)

       ; traceTc "simplifyInfer proto"  $ vcat
             [ ptext (sLit "zonked_tau_tvs =") <+> ppr zonked_tau_tvs
             , ptext (sLit "proto_qtvs =") <+> ppr proto_qtvs
             , ptext (sLit "surely_fref =") <+> ppr surely_free
             ]

       ; emitFlats surely_free
247 248 249 250
       ; traceTc "sinf"  $ vcat
             [ ptext (sLit "perhaps_bound =") <+> ppr perhaps_bound
             , ptext (sLit "surely_free   =") <+> ppr surely_free
             ]
251

252 253 254
            -- Step 2 
       	    -- Now simplify the possibly-bound constraints
       ; (simpl_results, tc_binds0)
255
           <- runTcS (SimplInfer (ppr (map fst name_taus))) NoUntouchables $
256 257 258 259 260 261 262 263 264 265 266
              simplifyWithApprox (zonked_wanteds { wc_flat = perhaps_bound })

       ; when (insolubleWC simpl_results)  -- Fail fast if there is an insoluble constraint
              (do { reportUnsolved simpl_results; failM })

            -- Step 3 
            -- Split again simplified_perhaps_bound, because some unifications 
            -- may have happened, and emit the free constraints. 
       ; gbl_tvs        <- tcGetGlobalTyVars
       ; zonked_tau_tvs <- zonkTcTyVarsAndFV zonked_tau_tvs
       ; zonked_simples <- zonkWantedEvVars (wc_flat simpl_results)
267 268
       ; let init_tvs 	     = zonked_tau_tvs `minusVarSet` gbl_tvs
             mr_qtvs  	     = init_tvs `minusVarSet` constrained_tvs
269
             constrained_tvs = tyVarsOfEvVarXs zonked_simples
270 271 272 273
             qtvs            = growWantedEVs gbl_tvs zonked_simples init_tvs
             (final_qtvs, (bound, free))
                | apply_mr  = (mr_qtvs, (emptyBag, zonked_simples))
                | otherwise = (qtvs,    partitionBag (quantifyMe qtvs) zonked_simples)
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
       ; emitFlats free

       ; if isEmptyVarSet final_qtvs && isEmptyBag bound
         then ASSERT( isEmptyBag (wc_insol simpl_results) )
              do { traceTc "} simplifyInfer/no quantification" empty
                 ; emitImplications (wc_impl simpl_results)
                 ; return ([], [], EvBinds tc_binds0) }
         else do

            -- Step 4, zonk quantified variables 
       { let minimal_flat_preds = mkMinimalBySCs $ map evVarOfPred $ bagToList bound
       ; let poly_ids = [ (name, mkSigmaTy [] minimal_flat_preds ty)
                        | (name, ty) <- name_taus ]
                        -- Don't add the quantified variables here, because
                        -- they are also bound in ic_skols and we want them to be
                        -- tidied uniformly
             skol_info = InferSkol poly_ids

       ; gloc <- getCtLoc skol_info
       ; qtvs_to_return <- zonkQuantifiedTyVars (varSetElems final_qtvs)

            -- Step 5
            -- Minimize `bound' and emit an implication
       ; minimal_bound_ev_vars <- mapM TcMType.newEvVar minimal_flat_preds
       ; ev_binds_var <- newTcEvBinds
       ; mapBagM_ (\(EvBind evar etrm) -> addTcEvBind ev_binds_var evar etrm) tc_binds0
       ; lcl_env <- getLclTypeEnv
       ; let implic = Implic { ic_untch    = NoUntouchables
                             , ic_env      = lcl_env
                             , ic_skols    = mkVarSet qtvs_to_return
                             , ic_given    = minimal_bound_ev_vars
                             , ic_wanted   = simpl_results { wc_flat = bound }
                             , ic_insol    = False
                             , ic_binds    = ev_binds_var
                             , ic_loc      = gloc }
       ; emitImplication implic
       ; traceTc "} simplifyInfer/produced residual implication for quantification" $
             vcat [ ptext (sLit "implic =") <+> ppr implic
                       -- ic_skols, ic_given give rest of result
                  , ptext (sLit "qtvs =") <+> ppr final_qtvs
                  , ptext (sLit "spb =") <+> ppr zonked_simples
                  , ptext (sLit "bound =") <+> ppr bound ]



       ; return (qtvs_to_return, minimal_bound_ev_vars, TcEvBinds ev_binds_var) } }
  where
    get_tau_tvs | isTopLevel top_lvl = tyVarsOfTypes
                | otherwise          = exactTyVarsOfTypes
     -- See Note [Silly type synonym] in TcType
\end{code}
325 326


327 328
Note [Minimize by Superclasses]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
329

330 331 332 333 334 335 336
When we quantify over a constraint, in simplifyInfer we need to
quantify over a constraint that is minimal in some sense: For
instance, if the final wanted constraint is (Eq alpha, Ord alpha),
we'd like to quantify over Ord alpha, because we can just get Eq alpha
from superclass selection from Ord alpha. This minimization is what
mkMinimalBySCs does. Then, simplifyInfer uses the minimal constraint
to check the original wanted.
337

338 339 340 341
\begin{code}
simplifyWithApprox :: WantedConstraints -> TcS WantedConstraints
simplifyWithApprox wanted
 = do { traceTcS "simplifyApproxLoop" (ppr wanted)
342

343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
      ; results <- solveWanteds emptyInert wanted

      ; let (residual_implics, floats) = approximateImplications (wc_impl results)

        -- If no new work was produced then we are done with simplifyApproxLoop
      ; if insolubleWC results || isEmptyBag floats
        then return results

        else solveWanteds emptyInert
                (WC { wc_flat = floats `unionBags` wc_flat results
                    , wc_impl = residual_implics
                    , wc_insol = emptyBag }) }

approximateImplications :: Bag Implication -> (Bag Implication, Bag WantedEvVar)
-- Extracts any nested constraints that don't mention the skolems
approximateImplications impls
  = do_bag (float_implic emptyVarSet) impls
360
  where 
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
    do_bag :: forall a b c. (a -> (Bag b, Bag c)) -> Bag a -> (Bag b, Bag c)
    do_bag f = foldrBag (plus . f) (emptyBag, emptyBag)
    plus :: forall b c. (Bag b, Bag c) -> (Bag b, Bag c) -> (Bag b, Bag c)
    plus (a1,b1) (a2,b2) = (a1 `unionBags` a2, b1 `unionBags` b2)

    float_implic :: TyVarSet -> Implication -> (Bag Implication, Bag WantedEvVar)
    float_implic skols imp
      = (unitBag (imp { ic_wanted = wanted' }), floats)
      where
        (wanted', floats) = float_wc (skols `unionVarSet` ic_skols imp) (ic_wanted imp)

    float_wc skols wc@(WC { wc_flat = flat, wc_impl = implic })
      = (wc { wc_flat = flat', wc_impl = implic' }, floats1 `unionBags` floats2)
      where
        (flat',   floats1) = do_bag (float_flat   skols) flat
        (implic', floats2) = do_bag (float_implic skols) implic

    float_flat :: TcTyVarSet -> WantedEvVar -> (Bag WantedEvVar, Bag WantedEvVar)
    float_flat skols wev
      | tyVarsOfEvVarX wev `disjointVarSet` skols = (emptyBag, unitBag wev)
      | otherwise                                 = (unitBag wev, emptyBag)
382
\end{code}
383

384
\begin{code}
385 386
-- (growX gbls wanted tvs) grows a seed 'tvs' against the 
-- X-constraint 'wanted', nuking the 'gbls' at each stage
387 388
-- It's conservative in that if the seed could *possibly*
-- grow to include a type variable, then it does
389

390 391 392 393 394 395 396
growWanteds :: TyVarSet -> WantedConstraints -> TyVarSet -> TyVarSet
growWanteds gbl_tvs wc = fixVarSet (growWC gbl_tvs wc)

growWantedEVs :: TyVarSet -> Bag WantedEvVar -> TyVarSet -> TyVarSet
growWantedEVs gbl_tvs ws tvs
  | isEmptyBag ws = tvs
  | otherwise     = fixVarSet (growPreds gbl_tvs evVarOfPred ws) tvs
397

398 399 400 401 402
--------  Helper functions, do not do fixpoint ------------------------
growWC :: TyVarSet -> WantedConstraints -> TyVarSet -> TyVarSet
growWC gbl_tvs wc = growImplics gbl_tvs             (wc_impl wc) .
                    growPreds   gbl_tvs evVarOfPred (wc_flat wc) .
                    growPreds   gbl_tvs evVarOfPred (wc_insol wc)
403

404 405 406 407 408 409 410 411 412 413 414 415 416 417
growImplics :: TyVarSet -> Bag Implication -> TyVarSet -> TyVarSet
growImplics gbl_tvs implics tvs
  = foldrBag grow_implic tvs implics
  where
    grow_implic implic tvs
      = grow tvs `minusVarSet` ic_skols implic
      where
        grow = growWC gbl_tvs (ic_wanted implic) .
               growPreds gbl_tvs evVarPred (listToBag (ic_given implic))
               -- We must grow from givens too; see test IPRun

growPreds :: TyVarSet -> (a -> PredType) -> Bag a -> TyVarSet -> TyVarSet
growPreds gbl_tvs get_pred items tvs
  = foldrBag extend tvs items
418
  where
419 420
    extend item tvs = tvs `unionVarSet`
                      (growPredTyVars (get_pred item) tvs `minusVarSet` gbl_tvs)
421 422 423 424 425 426 427 428 429

--------------------
quantifyMe :: TyVarSet      -- Quantifying over these
	   -> WantedEvVar
	   -> Bool	    -- True <=> quantify over this wanted
quantifyMe qtvs wev
  | isIPPred pred = True  -- Note [Inheriting implicit parameters]
  | otherwise	  = tyVarsOfPred pred `intersectsVarSet` qtvs
  where
430
    pred = evVarOfPred wev
431
\end{code}
432

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
Note [Avoid unecessary constraint simplification]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When inferring the type of a let-binding, with simplifyInfer,
try to avoid unnecessariliy simplifying class constraints.
Doing so aids sharing, but it also helps with delicate 
situations like
   instance C t => C [t] where ..
   f :: C [t] => ....
   f x = let g y = ...(constraint C [t])... 
         in ...
When inferring a type for 'g', we don't want to apply the
instance decl, because then we can't satisfy (C t).  So we
just notice that g isn't quantified over 't' and partition
the contraints before simplifying.

This only half-works, but then let-generalisation only half-works.


451 452
Note [Inheriting implicit parameters]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
453 454 455
Consider this:

	f x = (x::Int) + ?y
456

457 458 459
where f is *not* a top-level binding.
From the RHS of f we'll get the constraint (?y::Int).
There are two types we might infer for f:
460

461 462 463
	f :: Int -> Int

(so we get ?y from the context of f's definition), or
464 465 466

	f :: (?y::Int) => Int -> Int

467 468 469 470 471 472
At first you might think the first was better, becuase then
?y behaves like a free variable of the definition, rather than
having to be passed at each call site.  But of course, the WHOLE
IDEA is that ?y should be passed at each call site (that's what
dynamic binding means) so we'd better infer the second.

473 474
BOTTOM LINE: when *inferring types* you *must* quantify 
over implicit parameters. See the predicate isFreeWhenInferring.
475

476

477 478 479 480 481
*********************************************************************************
*                                                                                 * 
*                             RULES                                               *
*                                                                                 *
***********************************************************************************
482

483 484
Note [Simplifying RULE lhs constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
485
On the LHS of transformation rules we only simplify only equalities,
486 487 488 489
but not dictionaries.  We want to keep dictionaries unsimplified, to
serve as the available stuff for the RHS of the rule.  We *do* want to
simplify equalities, however, to detect ill-typed rules that cannot be
applied.
490

491 492 493
Implementation: the TcSFlags carried by the TcSMonad controls the
amount of simplification, so simplifyRuleLhs just sets the flag
appropriately.
494

495 496 497 498 499 500 501 502 503 504
Example.  Consider the following left-hand side of a rule
	f (x == y) (y > z) = ...
If we typecheck this expression we get constraints
	d1 :: Ord a, d2 :: Eq a
We do NOT want to "simplify" to the LHS
	forall x::a, y::a, z::a, d1::Ord a.
	  f ((==) (eqFromOrd d1) x y) ((>) d1 y z) = ...
Instead we want	
	forall x::a, y::a, z::a, d1::Ord a, d2::Eq a.
	  f ((==) d2 x y) ((>) d1 y z) = ...
505

506
Here is another example:
507 508
	fromIntegral :: (Integral a, Num b) => a -> b
	{-# RULES "foo"  fromIntegral = id :: Int -> Int #-}
509 510
In the rule, a=b=Int, and Num Int is a superclass of Integral Int. But
we *dont* want to get
511
	forall dIntegralInt.
512
	   fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int
513
because the scsel will mess up RULE matching.  Instead we want
514
	forall dIntegralInt, dNumInt.
515
	  fromIntegral Int Int dIntegralInt dNumInt = id Int
516

517 518 519 520 521 522 523
Even if we have 
	g (x == y) (y == z) = ..
where the two dictionaries are *identical*, we do NOT WANT
	forall x::a, y::a, z::a, d1::Eq a
	  f ((==) d1 x y) ((>) d1 y z) = ...
because that will only match if the dict args are (visibly) equal.
Instead we want to quantify over the dictionaries separately.
524

525 526
In short, simplifyRuleLhs must *only* squash equalities, leaving
all dicts unchanged, with absolutely no sharing.  
527

528 529 530 531 532 533 534 535 536
HOWEVER, under a nested implication things are different
Consider
  f :: (forall a. Eq a => a->a) -> Bool -> ...
  {-# RULES "foo" forall (v::forall b. Eq b => b->b).
       f b True = ...
    #=}
Here we *must* solve the wanted (Eq a) from the given (Eq a)
resulting from skolemising the agument type of g.  So we 
revert to SimplCheck when going under an implication.  
537 538

\begin{code}
539 540 541 542 543 544 545 546 547
simplifyRule :: RuleName 
             -> [TcTyVar]		-- Explicit skolems
             -> WantedConstraints	-- Constraints from LHS
             -> WantedConstraints	-- Constraints from RHS
             -> TcM ([EvVar], 		-- LHS dicts
                     TcEvBinds,		-- Evidence for LHS
                     TcEvBinds)		-- Evidence for RHS
-- See Note [Simplifying RULE lhs constraints]
simplifyRule name tv_bndrs lhs_wanted rhs_wanted
548 549 550 551 552 553 554
  = do { loc        <- getCtLoc (RuleSkol name)
       ; zonked_lhs <- zonkWC lhs_wanted
       ; let untch = NoUntouchables
	     	 -- We allow ourselves to unify environment 
		 -- variables; hence *no untouchables*

       ; (lhs_results, lhs_binds)
555
              <- runTcS (SimplRuleLhs name) untch $
556
                 solveWanteds emptyInert zonked_lhs
557 558 559 560 561 562 563

       ; traceTc "simplifyRule" $
         vcat [ text "zonked_lhs"   <+> ppr zonked_lhs 
              , text "lhs_results" <+> ppr lhs_results
              , text "lhs_binds"    <+> ppr lhs_binds 
              , text "rhs_wanted"   <+> ppr rhs_wanted ]

564 565

       -- Don't quantify over equalities (judgement call here)
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
       ; let (eqs, dicts) = partitionBag (isEqPred . evVarOfPred)
                                         (wc_flat lhs_results)
             lhs_dicts    = map evVarOf (bagToList dicts)
                                 -- Dicts and implicit parameters

           -- Fail if we have not got down to unsolved flats
       ; ev_binds_var <- newTcEvBinds
       ; emitImplication $ Implic { ic_untch  = untch
                                  , ic_env    = emptyNameEnv
                                  , ic_skols  = mkVarSet tv_bndrs
                                  , ic_given  = lhs_dicts
                                  , ic_wanted = lhs_results { wc_flat = eqs }
                                  , ic_insol  = insolubleWC lhs_results
                                  , ic_binds  = ev_binds_var
                                  , ic_loc    = loc }
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596

	     -- Notice that we simplify the RHS with only the explicitly
	     -- introduced skolems, allowing the RHS to constrain any 
	     -- unification variables.
	     -- Then, and only then, we call zonkQuantifiedTypeVariables
	     -- Example   foo :: Ord a => a -> a
	     --		  foo_spec :: Int -> Int
	     --		  {-# RULE "foo"  foo = foo_spec #-}
	     --	    Here, it's the RHS that fixes the type variable

	     -- So we don't want to make untouchable the type
	     -- variables in the envt of the RHS, because they include
	     -- the template variables of the RULE

	     -- Hence the rather painful ad-hoc treatement here
       ; rhs_binds_var@(EvBindsVar evb_ref _)  <- newTcEvBinds
597 598
       ; let doc = ptext (sLit "rhs of rule") <+> doubleQuotes (ftext name)
       ; rhs_binds1 <- simplifyCheck (SimplCheck doc) $
599 600 601 602 603 604 605 606 607 608 609
            WC { wc_flat = emptyBag
               , wc_insol = emptyBag
               , wc_impl = unitBag $
                    Implic { ic_untch   = NoUntouchables
                            , ic_env    = emptyNameEnv
                            , ic_skols  = mkVarSet tv_bndrs
                            , ic_given  = lhs_dicts
                            , ic_wanted = rhs_wanted
                            , ic_insol  = insolubleWC rhs_wanted
                            , ic_binds  = rhs_binds_var
                            , ic_loc    = loc } }
610 611 612 613 614
       ; rhs_binds2 <- readTcRef evb_ref

       ; return ( lhs_dicts
                , EvBinds lhs_binds 
                , EvBinds (rhs_binds1 `unionBags` evBindMapBinds rhs_binds2)) }
615 616 617
\end{code}


618 619 620 621 622
*********************************************************************************
*                                                                                 * 
*                                 Main Simplifier                                 *
*                                                                                 *
***********************************************************************************
623 624

\begin{code}
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
simplifyCheck :: SimplContext
	      -> WantedConstraints	-- Wanted
              -> TcM (Bag EvBind)
-- Solve a single, top-level implication constraint
-- e.g. typically one created from a top-level type signature
-- 	    f :: forall a. [a] -> [a]
--          f x = rhs
-- We do this even if the function has no polymorphism:
--    	    g :: Int -> Int

--          g y = rhs
-- (whereas for *nested* bindings we would not create
--  an implication constraint for g at all.)
--
-- Fails if can't solve something in the input wanteds
simplifyCheck ctxt wanteds
641
  = do { wanteds <- zonkWC wanteds
642 643 644 645

       ; traceTc "simplifyCheck {" (vcat
             [ ptext (sLit "wanted =") <+> ppr wanteds ])

646 647
       ; (unsolved, ev_binds) <- runTcS ctxt NoUntouchables $
                                 solveWanteds emptyInert wanteds
648 649

       ; traceTc "simplifyCheck }" $
650
         ptext (sLit "unsolved =") <+> ppr unsolved
651

652
       ; reportUnsolved unsolved
653 654 655 656

       ; return ev_binds }

----------------
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
solveWanteds :: InertSet                            -- Given
             -> WantedConstraints
             -> TcS WantedConstraints
solveWanteds inert wanted
  = do { (unsolved_flats, unsolved_implics, insols)
             <- solve_wanteds inert wanted
       ; return (WC { wc_flat = keepWanted unsolved_flats   -- Discard Derived
                    , wc_impl = unsolved_implics
                    , wc_insol = insols }) }

solve_wanteds :: InertSet                            -- Given
              -> WantedConstraints
              -> TcS (Bag FlavoredEvVar, Bag Implication, Bag FlavoredEvVar)
-- solve_wanteds iterates when it is able to float equalities
-- out of one or more of the implications
solve_wanteds inert wanted@(WC { wc_flat = flats, wc_impl = implics, wc_insol = insols })
  = do { traceTcS "solveWanteds {" (ppr wanted)

                 -- Try the flat bit
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
676 677 678 679 680
                 -- Discard from insols all the derived/given constraints
                 -- because they will show up again when we try to solve
                 -- everything else.  Solving them a second time is a bit
                 -- of a waste, but the code is simple, and the program is
                 -- wrong anyway!
681 682 683 684 685
       ; let all_flats = flats `unionBags` keepWanted insols
       ; inert1 <- solveInteractWanted inert (bagToList all_flats)

       ; (unsolved_flats, unsolved_implics) <- simpl_loop 1 inert1 implics

686 687
       ; bb <- getTcEvBindsBag
       ; tb <- getTcSTyBindsMap
688
       ; traceTcS "solveWanteds }" $
689
                 vcat [ text "unsolved_flats   =" <+> ppr unsolved_flats
690
                      , text "unsolved_implics =" <+> ppr unsolved_implics
691 692 693 694
                      , text "current evbinds  =" <+> vcat (map ppr (varEnvElts bb))
                      , text "current tybinds  =" <+> vcat (map ppr (varEnvElts tb))
                      ]

695
       ; (subst, remaining_flats) <- solveCTyFunEqs unsolved_flats
696
                -- See Note [Solving Family Equations]
697 698 699 700 701 702 703 704
                -- NB: remaining_flats has already had subst applied

       ; let (insoluble_flats, unsolved_flats) = partitionBag isCFrozenErr remaining_flats

       ; return ( mapBag (substFlavoredEvVar subst . deCanonicalise) unsolved_flats
                , mapBag (substImplication subst) unsolved_implics
                , mapBag (substFlavoredEvVar subst . deCanonicalise) insoluble_flats ) }

705
  where
706 707
    simpl_loop :: Int
               -> InertSet
708
               -> Bag Implication
709 710
               -> TcS (CanonicalCts, Bag Implication) -- CanonicalCts are Wanted or Derived
    simpl_loop n inert implics
711
      | n>10
712
      = trace "solveWanteds: loop" $	                -- Always bleat
713
        do { traceTcS "solveWanteds: loop" (ppr inert)  -- Bleat more informatively
714
           ; let (_, unsolved_cans) = extractUnsolved inert
715
           ; return (unsolved_cans, implics) }
716 717

      | otherwise
718 719 720
      = do { traceTcS "solveWanteds: simpl_loop start {" $
                 vcat [ text "n =" <+> ppr n
                      , text "implics =" <+> ppr implics
721 722 723
                      , text "inert   =" <+> ppr inert ]
           
           ; let (just_given_inert, unsolved_cans) = extractUnsolved inert
724
                     -- unsolved_cans contains either Wanted or Derived!
725

726
           ; (implic_eqs, unsolved_implics) 
727
                  <- solveNestedImplications just_given_inert unsolved_cans implics
728 729

                -- Apply defaulting rules if and only if there
730 731
		-- no floated equalities.  If there are, they may
		-- solve the remaining wanteds, so don't do defaulting.
732 733 734
           ; improve_eqs <- if not (isEmptyBag implic_eqs)
			    then return implic_eqs
                            else applyDefaultingRules just_given_inert unsolved_cans
735

736
           ; traceTcS "solveWanteds: simpl_loop end }" $
737 738
                 vcat [ text "improve_eqs      =" <+> ppr improve_eqs
                      , text "unsolved_flats   =" <+> ppr unsolved_cans
739 740
                      , text "unsolved_implics =" <+> ppr unsolved_implics ]

741 742 743 744
           ; (improve_eqs_already_in_inert, inert_with_improvement)
               <- solveInteract inert improve_eqs 

           ; if improve_eqs_already_in_inert then
745
                 return (unsolved_cans, unsolved_implics)
746
             else 
747 748 749
                 simpl_loop (n+1) inert_with_improvement 
                                         -- Contain unsolved_cans and the improve_eqs
                                  unsolved_implics
750 751
           }

dimitris's avatar
dimitris committed
752 753 754 755
givensFromWanteds :: SimplContext -> CanonicalCts -> Bag FlavoredEvVar
-- Extract the Wanted ones from CanonicalCts and conver to
-- Givens; not Given/Solved, see Note [Preparing inert set for implications]
givensFromWanteds _ctxt = foldrBag getWanted emptyBag
756 757 758
  where
    getWanted :: CanonicalCt -> Bag FlavoredEvVar -> Bag FlavoredEvVar
    getWanted cc givens
dimitris's avatar
dimitris committed
759 760 761 762 763 764 765 766 767 768 769 770 771
      | pushable_wanted cc
      = let given = mkEvVarX (cc_id cc) (mkGivenFlavor (cc_flavor cc) UnkSkol)
        in given `consBag` givens     -- and not mkSolvedFlavor,
                                      -- see Note [Preparing inert set for implications]
      | otherwise = givens

    pushable_wanted :: CanonicalCt -> Bool 
    pushable_wanted cc 
      | not (isCFrozenErr cc) 
      , isWantedCt cc 
      = isEqPred (evVarPred (cc_id cc)) -- see Note [Preparing inert set for implications]
      | otherwise = False 
 
772 773
solveNestedImplications :: InertSet -> CanonicalCts
                        -> Bag Implication
774
                        -> TcS (Bag FlavoredEvVar, Bag Implication)
775
solveNestedImplications just_given_inert unsolved_cans implics
776 777 778
  | isEmptyBag implics
  = return (emptyBag, emptyBag)
  | otherwise 
779 780
  = do {  -- See Note [Preparing inert set for implications]
	  -- Push the unsolved wanteds inwards, but as givens
dimitris's avatar
dimitris committed
781 782 783 784
             
       ; simpl_ctx <- getTcSContext 

       ; let pushed_givens    = givensFromWanteds simpl_ctx unsolved_cans
785 786 787
             tcs_untouchables = filterVarSet isFlexiTcsTv $
                                tyVarsOfEvVarXs pushed_givens
             -- See Note [Extra TcsTv untouchables]
788

789 790
       ; traceTcS "solveWanteds: preparing inerts for implications {"  
                  (vcat [ppr tcs_untouchables, ppr pushed_givens])
dimitris's avatar
dimitris committed
791 792

       ; (_, inert_for_implics) <- solveInteract just_given_inert pushed_givens 
793

794
       ; traceTcS "solveWanteds: } now doing nested implications {" $
795 796 797 798 799 800 801 802 803 804 805 806
         vcat [ text "inerts_for_implics =" <+> ppr inert_for_implics
              , text "implics =" <+> ppr implics ]

       ; (implic_eqs, unsolved_implics)
           <- flatMapBagPairM (solveImplication tcs_untouchables inert_for_implics) implics

       ; traceTcS "solveWanteds: done nested implications }" $
                  vcat [ text "implic_eqs ="       <+> ppr implic_eqs
                       , text "unsolved_implics =" <+> ppr unsolved_implics ]

       ; return (implic_eqs, unsolved_implics) }

807 808 809 810 811
solveImplication :: TcTyVarSet                -- Untouchable TcS unification variables
                 -> InertSet                  -- Given
                 -> Implication               -- Wanted
                 -> TcS (Bag FlavoredEvVar, -- All wanted or derived unifications: var = type
                         Bag Implication)     -- Unsolved rest (always empty or singleton)
812 813 814 815 816 817 818
-- Returns: 
--  1. A bag of floatable wanted constraints, not mentioning any skolems, 
--     that are of the form unification var = type
-- 
--  2. Maybe a unsolved implication, empty if entirely solved! 
-- 
-- Precondition: everything is zonked by now
819
solveImplication tcs_untouchables inert
820 821 822 823
     imp@(Implic { ic_untch  = untch 
                 , ic_binds  = ev_binds
                 , ic_skols  = skols 
                 , ic_given  = givens
824
                 , ic_wanted = wanteds
825
                 , ic_loc    = loc })
826
  = nestImplicTcS ev_binds (untch, tcs_untouchables) $
827 828 829 830
    recoverTcS (return (emptyBag, emptyBag)) $
       -- Recover from nested failures.  Even the top level is
       -- just a bunch of implications, so failing at the first
       -- one is bad
831 832 833
    do { traceTcS "solveImplication {" (ppr imp) 

         -- Solve flat givens
834
       ; given_inert <- solveInteractGiven inert loc givens 
835 836

         -- Simplify the wanteds
837 838 839 840 841 842
       ; (unsolved_flats, unsolved_implics, insols)
             <- solve_wanteds given_inert wanteds

       ; let (res_flat_free, res_flat_bound)
                 = floatEqualities skols givens unsolved_flats
             final_flat = keepWanted res_flat_bound
843

844 845 846 847 848 849
       ; let res_wanted = WC { wc_flat = final_flat
                             , wc_impl = unsolved_implics
                             , wc_insol = insols }
             res_implic = unitImplication $
                          imp { ic_wanted = res_wanted
                              , ic_insol  = insolubleWC res_wanted }
850 851 852

       ; traceTcS "solveImplication end }" $ vcat
             [ text "res_flat_free =" <+> ppr res_flat_free
853
             , text "res_implic =" <+> ppr res_implic ]
854

855
       ; return (res_flat_free, res_implic) }
856 857


858 859 860 861 862 863
floatEqualities :: TcTyVarSet -> [EvVar]
                -> Bag FlavoredEvVar -> (Bag FlavoredEvVar, Bag FlavoredEvVar)
-- Post: The returned FlavoredEvVar's are only Wanted or Derived
-- and come from the input wanted ev vars or deriveds 
floatEqualities skols can_given wantders
  | hasEqualities can_given = (emptyBag, wantders)
864
          -- Note [Float Equalities out of Implications]
865 866 867 868 869
  | otherwise = partitionBag is_floatable wantders
  

  where is_floatable :: FlavoredEvVar -> Bool
        is_floatable (EvVarX cv _fl)
870
          | isCoVar cv = skols `disjointVarSet` predTvs_under_fsks (coVarPred cv)
871
        is_floatable _flev = False
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894

        tvs_under_fsks :: Type -> TyVarSet
        -- ^ NB: for type synonyms tvs_under_fsks does /not/ expand the synonym
        tvs_under_fsks (TyVarTy tv)     
          | not (isTcTyVar tv)               = unitVarSet tv
          | FlatSkol ty <- tcTyVarDetails tv = tvs_under_fsks ty
          | otherwise                        = unitVarSet tv
        tvs_under_fsks (TyConApp _ tys) = unionVarSets (map tvs_under_fsks tys)
        tvs_under_fsks (PredTy sty)     = predTvs_under_fsks sty
        tvs_under_fsks (FunTy arg res)  = tvs_under_fsks arg `unionVarSet` tvs_under_fsks res
        tvs_under_fsks (AppTy fun arg)  = tvs_under_fsks fun `unionVarSet` tvs_under_fsks arg
        tvs_under_fsks (ForAllTy tv ty) -- The kind of a coercion binder 
        	     	       	      -- can mention type variables!
          | isTyVar tv		      = inner_tvs `delVarSet` tv
          | otherwise  {- Coercion -} = -- ASSERT( not (tv `elemVarSet` inner_tvs) )
                                        inner_tvs `unionVarSet` tvs_under_fsks (tyVarKind tv)
          where
            inner_tvs = tvs_under_fsks ty

        predTvs_under_fsks :: PredType -> TyVarSet
        predTvs_under_fsks (IParam _ ty)    = tvs_under_fsks ty
        predTvs_under_fsks (ClassP _ tys)   = unionVarSets (map tvs_under_fsks tys)
        predTvs_under_fsks (EqPred ty1 ty2) = tvs_under_fsks ty1 `unionVarSet` tvs_under_fsks ty2
895
\end{code}
896

897 898 899 900
Note [Preparing inert set for implications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Before solving the nested implications, we convert any unsolved flat wanteds
to givens, and add them to the inert set.  Reasons:
901 902

  a) In checking mode, suppresses unnecessary errors.  We already have
903
     on unsolved-wanted error; adding it to the givens prevents any 
904
     consequential errors from showing up
905

906 907 908 909
  b) More importantly, in inference mode, we are going to quantify over this
     constraint, and we *don't* want to quantify over any constraints that
     are deducible from it.

910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
  c) Flattened type-family equalities must be exposed to the nested
     constraints.  Consider
	F b ~ alpha, (forall c.  F b ~ alpha)
     Obviously this is soluble with [alpha := F b].  But the
     unification is only done by solveCTyFunEqs, right at the end of
     solveWanteds, and if we aren't careful we'll end up with an
     unsolved goal inside the implication.  We need to "push" the
     as-yes-unsolved (F b ~ alpha) inwards, as a *given*, so that it
     can be used to solve the inner (F b
     ~ alpha).  See Trac #4935.

  d) There are other cases where interactions between wanteds that can help
     to solve a constraint. For example

  	class C a b | a -> b

  	(C Int alpha), (forall d. C d blah => C Int a)

     If we push the (C Int alpha) inwards, as a given, it can produce
     a fundep (alpha~a) and this can float out again and be used to
     fix alpha.  (In general we can't float class constraints out just
     in case (C d blah) might help to solve (C Int a).)

933 934 935 936 937 938 939 940
The unsolved wanteds are *canonical* but they may not be *inert*,
because when made into a given they might interact with other givens.
Hence the call to solveInteract.  Example:

 Original inert set = (d :_g D a) /\ (co :_w  a ~ [beta]) 

We were not able to solve (a ~w [beta]) but we can't just assume it as
given because the resulting set is not inert. Hence we have to do a
941 942
'solveInteract' step first. 

dimitris's avatar
dimitris committed
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
Finally, note that we convert them to [Given] and NOT [Given/Solved].
The reason is that Given/Solved are weaker than Givens and may be discarded.
As an example consider the inference case, where we may have, the following 
original constraints: 
     [Wanted] F Int ~ Int
             (F Int ~ a => F Int ~ a)
If we convert F Int ~ Int to [Given/Solved] instead of Given, then the next 
given (F Int ~ a) is going to cause the Given/Solved to be ignored, casting 
the (F Int ~ a) insoluble. Hence we should really convert the residual 
wanteds to plain old Given. 

We need only push in unsolved equalities both in checking mode and inference mode: 

  (1) In checking mode we should not push given dictionaries in because of
example LongWayOverlapping.hs, where we might get strange overlap
errors between far-away constraints in the program.  But even in
checking mode, we must still push type family equations. Consider:

   type instance F True a b = a 
   type instance F False a b = b

   [w] F c a b ~ gamma 
   (c ~ True) => a ~ gamma 
   (c ~ False) => b ~ gamma

Since solveCTyFunEqs happens at the very end of solving, the only way to solve
the two implications is temporarily consider (F c a b ~ gamma) as Given (NB: not 
merely Given/Solved because it has to interact with the top-level instance 
environment) and push it inside the implications. Now, when we come out again at
the end, having solved the implications solveCTyFunEqs will solve this equality.

  (2) In inference mode, we recheck the final constraint in checking mode and
hence we will be able to solve inner implications from top-level quantified
constraints nonetheless.


979 980
Note [Extra TcsTv untouchables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
981 982 983 984 985
Furthemore, we record the inert set simplifier-generated unification
variables of the TcsTv kind (such as variables from instance that have
been applied, or unification flattens). These variables must be passed
to the implications as extra untouchable variables. Otherwise we have
the danger of double unifications. Example (from trac ticket #4494):
986 987 988

   (F Int ~ uf)  /\  (forall a. C a => F Int ~ beta) 

989 990 991
In this example, beta is touchable inside the implication. The first
solveInteract step leaves 'uf' ununified. Then we move inside the
implication where a new constraint
992
       uf  ~  beta  
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
emerges. We may spontaneously solve it to get uf := beta, so the whole
implication disappears but when we pop out again we are left with (F
Int ~ uf) which will be unified by our final solveCTyFunEqs stage and
uf will get unified *once more* to (F Int).

The solution is to record the TcsTvs (i.e. the simplifier-generated
unification variables) that are generated when solving the flats, and
make them untouchables for the nested implication. In the example
above uf would become untouchable, so beta would be forced to be
unified as beta := uf.

NB: A consequence is that every simplifier-generated TcsTv variable
    that gets floated out of an implication becomes now untouchable
    next time we go inside that implication to solve any residual
    constraints. In effect, by floating an equality out of the
    implication we are committing to have it solved in the outside.
1009

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
1010 1011 1012 1013
Note [Float Equalities out of Implications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
We want to float equalities out of vanilla existentials, but *not* out 
of GADT pattern matches. 
1014

1015

1016 1017
\begin{code}

1018
solveCTyFunEqs :: CanonicalCts -> TcS (TvSubst, CanonicalCts)
1019 1020 1021 1022
-- Default equalities (F xi ~ alpha) by setting (alpha := F xi), whenever possible
-- See Note [Solving Family Equations]
-- Returns: a bunch of unsolved constraints from the original CanonicalCts and implications
--          where the newly generated equalities (alpha := F xi) have been substituted through.
1023
solveCTyFunEqs cts
1024
 = do { untch   <- getUntouchables 
1025 1026
      ; let (unsolved_can_cts, (ni_subst, cv_binds))
                = getSolvableCTyFunEqs untch cts
1027
      ; traceTcS "defaultCTyFunEqs" (vcat [text "Trying to default family equations:"
1028
                                          , ppr ni_subst, ppr cv_binds
1029
                                          ])
1030 1031 1032 1033
      ; mapM_ solve_one cv_binds

      ; return (niFixTvSubst ni_subst, unsolved_can_cts) }
  where
1034 1035
    solve_one (cv,tv,ty) = do { setWantedTyBind tv ty
                              ; setCoBind cv (mkReflCo ty) }
1036

1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
------------
type FunEqBinds = (TvSubstEnv, [(CoVar, TcTyVar, TcType)])
  -- The TvSubstEnv is not idempotent, but is loop-free
  -- See Note [Non-idempotent substitution] in Unify
emptyFunEqBinds :: FunEqBinds
emptyFunEqBinds = (emptyVarEnv, [])

extendFunEqBinds :: FunEqBinds -> CoVar -> TcTyVar -> TcType -> FunEqBinds
extendFunEqBinds (tv_subst, cv_binds) cv tv ty
  = (extendVarEnv tv_subst tv ty, (cv, tv, ty):cv_binds)

------------
1049
getSolvableCTyFunEqs :: TcsUntouchables
1050
                     -> CanonicalCts                -- Precondition: all Wanteds or Derived!
1051 1052
                     -> (CanonicalCts, FunEqBinds)  -- Postcondition: returns the unsolvables
getSolvableCTyFunEqs untch cts
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
  = Bag.foldlBag dflt_funeq (emptyCCan, emptyFunEqBinds) cts
  where
    dflt_funeq :: (CanonicalCts, FunEqBinds) -> CanonicalCt
               -> (CanonicalCts, FunEqBinds)
    dflt_funeq (cts_in, feb@(tv_subst, _))
               (CFunEqCan { cc_id = cv
                          , cc_flavor = fl
                          , cc_fun = tc
                          , cc_tyargs = xis
                          , cc_rhs = xi })
      | Just tv <- tcGetTyVar_maybe xi      -- RHS is a type variable

      , isTouchableMetaTyVar_InRange untch tv
           -- And it's a *touchable* unification variable

      , typeKind xi `isSubKind` tyVarKind tv
         -- Must do a small kind check since TcCanonical invariants 
         -- on family equations only impose compatibility, not subkinding

      , not (tv `elemVarEnv` tv_subst)
           -- Check not in extra_binds
           -- See Note [Solving Family Equations], Point 1

      , not (tv `elemVarSet` niSubstTvSet tv_subst (tyVarsOfTypes xis))
           -- Occurs check: see Note [Solving Family Equations], Point 2
dimitris's avatar
dimitris committed
1078
      = ASSERT ( not (isGivenOrSolved fl) )
1079 1080 1081 1082
        (cts_in, extendFunEqBinds feb cv tv (mkTyConApp tc xis))

    dflt_funeq (cts_in, fun_eq_binds) ct
      = (cts_in `extendCCans` ct, fun_eq_binds)
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
\end{code}

Note [Solving Family Equations] 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
After we are done with simplification we may be left with constraints of the form:
     [Wanted] F xis ~ beta 
If 'beta' is a touchable unification variable not already bound in the TyBinds 
then we'd like to create a binding for it, effectively "defaulting" it to be 'F xis'.

When is it ok to do so? 
    1) 'beta' must not already be defaulted to something. Example: 

           [Wanted] F Int  ~ beta   <~ Will default [beta := F Int]
           [Wanted] F Char ~ beta   <~ Already defaulted, can't default again. We 
                                       have to report this as unsolved.

    2) However, we must still do an occurs check when defaulting (F xis ~ beta), to 
       set [beta := F xis] only if beta is not among the free variables of xis.

    3) Notice that 'beta' can't be bound in ty binds already because we rewrite RHS 
       of type family equations. See Inert Set invariants in TcInteract. 


1106 1107 1108 1109 1110 1111 1112
*********************************************************************************
*                                                                               * 
*                          Defaulting and disamgiguation                        *
*                                                                               *
*********************************************************************************

Basic plan behind applyDefaulting rules: 
1113
 
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
 Step 1:  
    Split wanteds into defaultable groups, `groups' and the rest `rest_wanted' 
    For each defaultable group, do: 
      For each possible substitution for [alpha |-> tau] where `alpha' is the 
      group's variable, do: 
        1) Make up new TcEvBinds
        2) Extend TcS with (groupVariable 
        3) given_inert <- solveOne inert (given : a ~ tau) 
        4) (final_inert,unsolved) <- solveWanted (given_inert) (group_constraints)
        5) if unsolved == empty then 
                 sneakyUnify a |-> tau 
                 write the evidence bins
                 return (final_inert ++ group_constraints,[]) 
                      -- will contain the info (alpha |-> tau)!!
                 goto next defaultable group 
           if unsolved <> empty then 
                 throw away evidence binds
                 try next substitution 
     If you've run out of substitutions for this group, too bad, you failed 
                 return (inert,group) 
                 goto next defaultable group
 
 Step 2: 
   Collect all the (canonical-cts, wanteds) gathered this way. 
   - Do a solveGiven over the canonical-cts to make sure they are inert 
------------------------------------------------------------------------------------------
1140

1141 1142

\begin{code}
1143
applyDefaultingRules :: InertSet
1144 1145
                     -> CanonicalCts             -- All wanteds
                     -> TcS (Bag FlavoredEvVar)  -- All wanteds again!
1146 1147 1148 1149 1150 1151
-- Return some *extra* givens, which express the 
-- type-class-default choice

applyDefaultingRules inert wanteds
  | isEmptyBag wanteds 
  = return emptyBag
1152
  | otherwise
1153
  = do { untch <- getUntouchables
1154
       ; tv_cts <- mapM (defaultTyVar untch) $
1155
                   varSetElems (tyVarsOfCDicts wanteds) 
1156 1157 1158

       ; info@(_, default_tys, _) <- getDefaultInfo
       ; let groups = findDefaultableGroups info untch wanteds
1159
       ; deflt_cts <- mapM (disambigGroup default_tys inert) groups
1160 1161 1162 1163

       ; traceTcS "deflt2" (vcat [ text "Tyvar defaults =" <+> ppr tv_cts
                                 , text "Type defaults =" <+> ppr deflt_cts])

1164
       ; return (unionManyBags deflt_cts `unionBags` unionManyBags tv_cts) }
1165 1166

------------------
1167
defaultTyVar :: TcsUntouchables -> TcTyVar -> TcS (Bag FlavoredEvVar)
1168 1169 1170 1171 1172 1173 1174 1175
-- defaultTyVar is used on any un-instantiated meta type variables to
-- default the kind of ? and ?? etc to *.  This is important to ensure
-- that instance declarations match.  For example consider
--	instance Show (a->b)
--	foo x = show (\_ -> True)
-- Then we'll get a constraint (Show (p ->q)) where p has argTypeKind (printed ??), 
-- and that won't match the typeKind (*) in the instance decl.  
-- See test tc217.
1176
--
1177 1178 1179 1180 1181 1182
-- We look only at touchable type variables. No further constraints
-- are going to affect these type variables, so it's time to do it by
-- hand.  However we aren't ready to default them fully to () or
-- whatever, because the type-class defaulting rules have yet to run.

defaultTyVar untch the_tv 
1183
  | isTouchableMetaTyVar_InRange untch the_tv
1184
  , not (k `eqKind` default_k)
1185
  = do { ev <- TcSMonad.newKindConstraint the_tv default_k
1186
       ; let loc = CtLoc DefaultOrigin (getSrcSpan the_tv) [] -- Yuk
1187
       ; return (unitBag (mkEvVarX ev (Wanted loc))) }
1188
  | otherwise            
1189
  = return emptyBag	 -- The common case