TcSimplify.lhs 52.8 KB
Newer Older
1
\begin{code}
Ian Lynagh's avatar
Ian Lynagh committed
2 3 4 5 6 7 8
{-# OPTIONS -fno-warn-tabs #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
--     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
-- for details

9
module TcSimplify( 
10
       simplifyInfer, simplifyAmbiguityCheck,
11
       simplifyDefault, simplifyDeriv, 
12 13
       simplifyRule, simplifyTop, simplifyInteractive,
       solveWantedsTcM
14
  ) where
15

16
#include "HsVersions.h"
17

18
import TcRnTypes
19
import TcRnMonad
20
import TcErrors
21
import TcMType
22 23
import TcType 
import TcSMonad 
24
import TcInteract 
25
import Inst
26 27
import Type     ( classifyPredType, PredTree(..), getClassPredTys_maybe )
import Class    ( Class )
28
import Var
29
import Unique
30
import VarSet
31
import VarEnv 
32
import TcEvidence
33
import TypeRep
34
import Name
35
import Bag
36 37
import ListSetOps
import Util
38 39 40
import PrelInfo
import PrelNames
import Class		( classKey )
41
import BasicTypes       ( RuleName )
42
import Outputable
43
import FastString
dimitris's avatar
dimitris committed
44
import TrieMap () -- DV: for now
45 46 47
\end{code}


48 49 50 51 52
*********************************************************************************
*                                                                               * 
*                           External interface                                  *
*                                                                               *
*********************************************************************************
53

54 55 56
\begin{code}
simplifyTop :: WantedConstraints -> TcM (Bag EvBind)
-- Simplify top-level constraints
57 58 59
-- 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
60 61 62 63 64
simplifyTop wanteds
  = do { traceTc "simplifyTop {" $ text "wanted = " <+> ppr wanteds 
       ; ev_binds_var <- newTcEvBinds
       ; zonked_final_wc <- solveWantedsTcMWithEvBinds ev_binds_var wanteds simpl_top
       ; binds1 <- TcRnMonad.getTcEvBinds ev_binds_var
65 66 67
       ; traceTc "End simplifyTop }" empty

       ; traceTc "reportUnsolved {" empty
68
       ; binds2 <- reportUnsolved zonked_final_wc
69
       ; traceTc "reportUnsolved }" empty
70
         
71
       ; return (binds1 `unionBags` binds2) }
72

73 74
  where
    -- See Note [Top-level Defaulting Plan]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
75
    simpl_top :: WantedConstraints -> TcS WantedConstraints
76
    simpl_top wanteds
77
      = do { wc_first_go <- nestTcS (solve_wanteds_and_drop wanteds)
78 79
           ; applyTyVarDefaulting wc_first_go 
           ; simpl_top_loop wc_first_go }
80
    
81
    simpl_top_loop wc
82 83 84
      | isEmptyWC wc || insolubleWC wc
             -- Don't do type-class defaulting if there are insolubles
             -- Doing so is not going to solve the insolubles
85 86
      = return wc
      | otherwise
87
      = do { wc_residual <- nestTcS (solve_wanteds_and_drop wc)
88 89 90 91 92 93 94
           ; let wc_flat_approximate = approximateWC wc_residual
           ; something_happened <- applyDefaultingRules wc_flat_approximate
                                        -- See Note [Top-level Defaulting Plan]
           ; if something_happened then 
               simpl_top_loop wc_residual 
             else 
               return wc_residual }
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
\end{code}

Note [Top-level Defaulting Plan]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

We have considered two design choices for where/when to apply defaulting.   
   (i) Do it in SimplCheck mode only /whenever/ you try to solve some 
       flat constraints, maybe deep inside the context of implications.
       This used to be the case in GHC 7.4.1.
   (ii) Do it in a tight loop at simplifyTop, once all other constraint has 
        finished. This is the current story.

Option (i) had many disadvantages: 
   a) First it was deep inside the actual solver, 
   b) Second it was dependent on the context (Infer a type signature, 
      or Check a type signature, or Interactive) since we did not want 
      to always start defaulting when inferring (though there is an exception to  
      this see Note [Default while Inferring])
   c) It plainly did not work. Consider typecheck/should_compile/DfltProb2.hs:
          f :: Int -> Bool
          f x = const True (\y -> let w :: a -> a
                                      w a = const a (y+1)
                                  in w y)
      We will get an implication constraint (for beta the type of y):
               [untch=beta] forall a. 0 => Num beta
      which we really cannot default /while solving/ the implication, since beta is
      untouchable.

Instead our new defaulting story is to pull defaulting out of the solver loop and
go with option (i), implemented at SimplifyTop. Namely:
     - First have a go at solving the residual constraint of the whole program
     - Try to approximate it with a flat constraint
     - Figure out derived defaulting equations for that flat constraint
     - Go round the loop again if you did manage to get some equations

Now, that has to do with class defaulting. However there exists type variable /kind/
defaulting. Again this is done at the top-level and the plan is:
     - At the top-level, once you had a go at solving the constraint, do 
       figure out /all/ the touchable unification variables of the wanted contraints.
     - Apply defaulting to their kinds

More details in Note [DefaultTyVar].

\begin{code}
139

140 141 142
------------------
simplifyAmbiguityCheck :: Name -> WantedConstraints -> TcM (Bag EvBind)
simplifyAmbiguityCheck name wanteds
143
  = traceTc "simplifyAmbiguityCheck" (text "name =" <+> ppr name) >> 
144
    simplifyTop wanteds  -- NB: must be simplifyTop so that we
145 146
                         --     do ambiguity resolution.  
                         -- See Note [Impedence matching] in TcBinds.
147
 
148 149 150
------------------
simplifyInteractive :: WantedConstraints -> TcM (Bag EvBind)
simplifyInteractive wanteds 
151 152
  = traceTc "simplifyInteractive" empty >>
    simplifyTop wanteds 
153 154 155 156 157

------------------
simplifyDefault :: ThetaType	-- Wanted; has no type variables in it
                -> TcM ()	-- Succeeds iff the constraint is soluble
simplifyDefault theta
158 159
  = do { traceTc "simplifyInteractive" empty
       ; wanted <- newFlatWanteds DefaultOrigin theta
160 161 162 163
       ; (unsolved, _binds) <- solveWantedsTcM (mkFlatWC wanted)

       ; traceTc "reportUnsolved {" empty
       -- See Note [Deferring coercion errors to runtime]
164
       ; reportAllUnsolved unsolved 
165 166 167
         -- Postcondition of solveWantedsTcM is that returned
         -- constraints are zonked. So Precondition of reportUnsolved
         -- is true.
168 169
       ; traceTc "reportUnsolved }" empty

170 171
       ; return () }
\end{code}
172

173

174
***********************************************************************************
175
*                                                                                 * 
176
*                            Deriving                                             *
177 178
*                                                                                 *
***********************************************************************************
179

180 181
\begin{code}
simplifyDeriv :: CtOrigin
182 183 184 185
              -> PredType
	      -> [TyVar]	
	      -> ThetaType		-- Wanted
	      -> TcM ThetaType	-- Needed
186 187
-- Given  instance (wanted) => C inst_ty 
-- Simplify 'wanted' as much as possibles
188
-- Fail if not possible
189
simplifyDeriv orig pred tvs theta 
190
  = do { (skol_subst, tvs_skols) <- tcInstSkolTyVars tvs -- Skolemize
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
191 192 193 194
      	 	-- The constraint solving machinery 
		-- expects *TcTyVars* not TyVars.  
		-- We use *non-overlappable* (vanilla) skolems
		-- See Note [Overlap and deriving]
195

196
       ; let subst_skol = zipTopTvSubst tvs_skols $ map mkTyVarTy tvs
197
             skol_set   = mkVarSet tvs_skols
198
	     doc = ptext (sLit "deriving") <+> parens (ppr pred)
199 200 201

       ; wanted <- newFlatWanteds orig (substTheta skol_subst theta)

202 203
       ; traceTc "simplifyDeriv" $ 
         vcat [ pprTvBndrs tvs $$ ppr theta $$ ppr wanted, doc ]
204
       ; (residual_wanted, _ev_binds1)
205
             <- solveWantedsTcM (mkFlatWC wanted)
206
                -- Post: residual_wanted are already zonked
207

208 209
       ; let (good, bad) = partitionBagWith get_good (wc_flat residual_wanted)
                         -- See Note [Exotic derived instance contexts]
210
             get_good :: Ct -> Either PredType Ct
211 212 213 214 215 216
             get_good ct | validDerivPred skol_set p 
                         , isWantedCt ct  = Left p 
                         -- NB: residual_wanted may contain unsolved
                         -- Derived and we stick them into the bad set
                         -- so that reportUnsolved may decide what to do with them
                         | otherwise = Right ct
217
                         where p = ctPred ct
218

219 220
       -- We never want to defer these errors because they are errors in the
       -- compiler! Hence the `False` below
221
       ; reportAllUnsolved (residual_wanted { wc_flat = bad })
222

223 224
       ; let min_theta = mkMinimalBySCs (bagToList good)
       ; return (substTheta subst_skol min_theta) }
225
\end{code}
226

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
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

252 253 254 255 256 257 258
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.
259

260 261 262
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)
263

264 265
Notice that this instance (just) satisfies the Paterson termination 
conditions.  Then we *could* derive an instance decl like this:
266

267 268 269 270
	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.  
271

272 273 274
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.
275

276 277
So for now we simply require that the derived instance context
should have only type-variable constraints.
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
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
*                                                                                 *
***********************************************************************************
308

dreixel's avatar
dreixel committed
309 310 311 312 313 314 315 316 317 318 319 320
Note [Which variables to quantify]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose the inferred type of a function is
   T kappa (alpha:kappa) -> Int
where alpha is a type unification variable and 
      kappa is a kind unification variable
Then we want to quantify over *both* alpha and kappa.  But notice that
kappa appears "at top level" of the type, as well as inside the kind
of alpha.  So it should be fine to just look for the "top level"
kind/type variables of the type, without looking transitively into the
kinds of those type variables.

321
\begin{code}
322
simplifyInfer :: Bool
323 324 325
              -> Bool                  -- Apply monomorphism restriction
              -> [(Name, TcTauType)]   -- Variables to be generalised,
                                       -- and their tau-types
326
              -> WantedConstraints
327 328
              -> TcM ([TcTyVar],    -- Quantify over these type variables
                      [EvVar],      -- ... and these constraints
329 330 331
		      Bool,	    -- The monomorphism restriction did something
		      		    --   so the results type is not as general as
				    --   it could be
332
                      TcEvBinds)    -- ... binding these evidence variables
333
simplifyInfer _top_lvl apply_mr name_taus wanteds
334 335 336
  | isEmptyWC wanteds
  = do { gbl_tvs     <- tcGetGlobalTyVars            -- Already zonked
       ; zonked_taus <- zonkTcTypes (map snd name_taus)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
337
       ; let tvs_to_quantify = varSetElems (tyVarsOfTypes zonked_taus `minusVarSet` gbl_tvs)
dreixel's avatar
dreixel committed
338 339 340
       	     		       -- tvs_to_quantify can contain both kind and type vars
       	                       -- See Note [Which variables to quantify]
       ; qtvs <- zonkQuantifiedTyVars tvs_to_quantify
341
       ; return (qtvs, [], False, emptyTcEvBinds) }
342

343
  | otherwise
344
  = do { zonked_tau_tvs <- zonkTyVarsAndFV (tyVarsOfTypes (map snd name_taus))
345

346
       ; ev_binds_var <- newTcEvBinds
347
       ; traceTc "simplifyInfer {"  $ vcat
348
             [ ptext (sLit "names =") <+> ppr (map fst name_taus)
349 350
             , ptext (sLit "taus =") <+> ppr (map snd name_taus)
             , ptext (sLit "tau_tvs (zonked) =") <+> ppr zonked_tau_tvs
351 352
             , ptext (sLit "closed =") <+> ppr _top_lvl
             , ptext (sLit "apply_mr =") <+> ppr apply_mr
353
             , ptext (sLit "(unzonked) wanted =") <+> ppr wanteds
354 355
             ]

356 357 358 359 360
              -- Historical note: Before step 2 we used to have a
              -- HORRIBLE HACK described in Note [Avoid unecessary
              -- constraint simplification] but, as described in Trac
              -- #4361, we have taken in out now.  That's why we start
              -- with step 2!
361

362 363 364 365 366 367 368 369
              -- Step 2) First try full-blown solving 

              -- NB: we must gather up all the bindings from doing
              -- this solving; hence (runTcSWithEvBinds ev_binds_var).
              -- And note that since there are nested implications,
              -- calling solveWanteds will side-effect their evidence
              -- bindings, so we can't just revert to the input
              -- constraint.
370 371 372
       ; wanted_transformed <- solveWantedsTcMWithEvBinds ev_binds_var wanteds $
                               solve_wanteds_and_drop
                               -- Post: wanted_transformed are zonked
373 374

              -- Step 4) Candidates for quantification are an approximation of wanted_transformed
375 376 377
              -- NB: Already the fixpoint of any unifications that may have happened                                
              -- NB: We do not do any defaulting when inferring a type, this can lead
              -- to less polymorphic types, see Note [Default while Inferring]
378
 
379 380
              -- Step 5) Minimize the quantification candidates                             
              -- Step 6) Final candidates for quantification                
381
              -- We discard bindings, insolubles etc, because all we are
382 383
              -- care aout it

384
       ; (quant_pred_candidates, _extra_binds)   
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
             <- if insolubleWC wanted_transformed 
                then return ([], emptyBag)   -- See Note [Quantification with errors]
                else runTcS $ 
                do { let quant_candidates = approximateWC wanted_transformed
                   ; traceTcS "simplifyWithApprox" $
                     text "quant_candidates = " <+> ppr quant_candidates
                   ; promoteTyVars quant_candidates
                   ; _implics <- solveInteract quant_candidates
                   ; (flats, _insols) <- getInertUnsolved
                   -- NB: Dimitrios is slightly worried that we will get
                   -- family equalities (F Int ~ alpha) in the quantification
                   -- candidates, as we have performed no further unflattening
                   -- at this point. Nothing bad, but inferred contexts might
                   -- look complicated.
                   ; return (map ctPred $ filter isWantedCt (bagToList flats)) }
400 401 402

             -- NB: quant_pred_candidates is already the fixpoint of any 
             --     unifications that may have happened
403 404
                  
       ; gbl_tvs        <- tcGetGlobalTyVars -- TODO: can we just use untch instead of gbl_tvs?
405
       ; zonked_tau_tvs <- zonkTyVarsAndFV zonked_tau_tvs
406
       
407
       ; let init_tvs  = zonked_tau_tvs `minusVarSet` gbl_tvs
408
             poly_qtvs = growThetaTyVars quant_pred_candidates init_tvs 
409
                         `minusVarSet` gbl_tvs
410
             pbound    = filter (quantifyPred poly_qtvs) quant_pred_candidates
411
             
412
	     -- Monomorphism restriction
413 414
             mr_qtvs  	     = init_tvs `minusVarSet` constrained_tvs
             constrained_tvs = tyVarsOfTypes quant_pred_candidates
415
	     mr_bites        = apply_mr && not (null pbound)
416

417 418
             (qtvs, bound) | mr_bites  = (mr_qtvs,   [])
                           | otherwise = (poly_qtvs, pbound)
419
             
420 421 422 423 424 425 426
       ; traceTc "simplifyWithApprox" $
         vcat [ ptext (sLit "quant_pred_candidates =") <+> ppr quant_pred_candidates
              , ptext (sLit "gbl_tvs=") <+> ppr gbl_tvs
              , ptext (sLit "zonked_tau_tvs=") <+> ppr zonked_tau_tvs
              , ptext (sLit "pbound =") <+> ppr pbound
              , ptext (sLit "init_qtvs =") <+> ppr init_tvs 
              , ptext (sLit "poly_qtvs =") <+> ppr poly_qtvs ]
427

428
       ; if isEmptyVarSet qtvs && null bound
429 430 431 432
         then do { traceTc "} simplifyInfer/no quantification" empty                   
                 ; emitConstraints wanted_transformed
                    -- Includes insolubles (if -fdefer-type-errors)
                    -- as well as flats and implications
433
                 ; return ([], [], mr_bites, TcEvBinds ev_binds_var) }
434 435
         else do

436 437 438
       { traceTc "simplifyApprox" $ 
         ptext (sLit "bound are =") <+> ppr bound 
         
439
            -- Step 4, zonk quantified variables 
440
       ; let minimal_flat_preds = mkMinimalBySCs bound
441 442
             skol_info = InferSkol [ (name, mkSigmaTy [] minimal_flat_preds ty)
                                   | (name, ty) <- name_taus ]
443 444 445 446
                        -- Don't add the quantified variables here, because
                        -- they are also bound in ic_skols and we want them to be
                        -- tidied uniformly

Simon Peyton Jones's avatar
Simon Peyton Jones committed
447
       ; qtvs_to_return <- zonkQuantifiedTyVars (varSetElems qtvs)
448

449
            -- Step 7) Emit an implication
450
       ; minimal_bound_ev_vars <- mapM TcMType.newEvVar minimal_flat_preds
451 452
       ; lcl_env <- TcRnMonad.getLclEnv
       ; let implic = Implic { ic_untch    = pushUntouchables (tcl_untch lcl_env)
453
                             , ic_skols    = qtvs_to_return
454 455
                             , ic_fsks     = []  -- wanted_tansformed arose only from solveWanteds
                                                 -- hence no flatten-skolems (which come from givens)
456
                             , ic_given    = minimal_bound_ev_vars
457
                             , ic_wanted   = wanted_transformed 
458 459
                             , ic_insol    = False
                             , ic_binds    = ev_binds_var
460 461
                             , ic_info     = skol_info
                             , ic_env      = lcl_env }
462
       ; emitImplication implic
463
         
464 465 466
       ; traceTc "} simplifyInfer/produced residual implication for quantification" $
             vcat [ ptext (sLit "implic =") <+> ppr implic
                       -- ic_skols, ic_given give rest of result
467
                  , ptext (sLit "qtvs =") <+> ppr qtvs_to_return
468
                  , ptext (sLit "spb =") <+> ppr quant_pred_candidates
469 470
                  , ptext (sLit "bound =") <+> ppr bound ]

471 472
       ; return ( qtvs_to_return, minimal_bound_ev_vars
                , mr_bites,  TcEvBinds ev_binds_var) } }
473
\end{code}
474

475 476 477 478 479 480 481 482 483
Note [Quantification with errors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we find that the RHS of the definition has some absolutely-insoluble
constraints, we abandon all attempts to find a context to quantify
over, and instead make the function fully-polymorphic in whatever
type we have found.  For two reasons
  a) Minimise downstream errors
  b) Avoid spurious errors from this function
   
484

485 486
Note [Default while Inferring]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
Our current plan is that defaulting only happens at simplifyTop and
not simplifyInfer.  This may lead to some insoluble deferred constraints
Example:

instance D g => C g Int b 

constraint inferred = (forall b. 0 => C gamma alpha b) /\ Num alpha
type inferred       = gamma -> gamma 

Now, if we try to default (alpha := Int) we will be able to refine the implication to 
  (forall b. 0 => C gamma Int b) 
which can then be simplified further to 
  (forall b. 0 => D gamma)
Finally we /can/ approximate this implication with (D gamma) and infer the quantified
type:  forall g. D g => g -> g

Instead what will currently happen is that we will get a quantified type 
(forall g. g -> g) and an implication:
       forall g. 0 => (forall b. 0 => C g alpha b) /\ Num alpha

which, even if the simplifyTop defaults (alpha := Int) we will still be left with an 
unsolvable implication:
       forall g. 0 => (forall b. 0 => D g)

The concrete example would be: 
       h :: C g a s => g -> a -> ST s a
       f (x::gamma) = (\_ -> x) (runST (h x (undefined::alpha)) + 1)

But it is quite tedious to do defaulting and resolve the implication constraints and
we have not observed code breaking because of the lack of defaulting in inference so 
we don't do it for now.



521 522 523 524 525 526 527 528 529
Note [Minimize by Superclasses]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
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.
530

531

532 533
Note [Avoid unecessary constraint simplification]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
534 535 536 537
    -------- NB NB NB (Jun 12) ------------- 
    This note not longer applies; see the notes with Trac #4361.
    But I'm leaving it in here so we remember the issue.)
    ----------------------------------------
538
When inferring the type of a let-binding, with simplifyInfer,
539
try to avoid unnecessarily simplifying class constraints.
540 541
Doing so aids sharing, but it also helps with delicate 
situations like
542

543
   instance C t => C [t] where ..
544

545 546 547 548 549 550 551 552 553 554 555
   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.


556 557 558 559 560
*********************************************************************************
*                                                                                 * 
*                             RULES                                               *
*                                                                                 *
***********************************************************************************
561

562
See note [Simplifying RULE consraints] in TcRule
563

564 565 566 567 568 569 570 571 572 573 574 575 576 577
Note [RULE quanfification over equalities]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Decideing which equalities to quantify over is tricky:
 * We do not want to quantify over insoluble equalities (Int ~ Bool)
    (a) because we prefer to report a LHS type error
    (b) because if such things end up in 'givens' we get a bogus
        "inaccessible code" error

 * But we do want to quantify over things like (a ~ F b), where
   F is a type function.

The difficulty is that it's hard to tell what is insoluble!
So we see whether the simplificaiotn step yielded any type errors,
and if so refrain from quantifying over *any* equalites.
578 579

\begin{code}
580 581 582
simplifyRule :: RuleName 
             -> WantedConstraints	-- Constraints from LHS
             -> WantedConstraints	-- Constraints from RHS
583 584 585
             -> TcM ([EvVar], WantedConstraints)   -- LHS evidence varaibles
-- See Note [Simplifying RULE constraints] in TcRule
simplifyRule name lhs_wanted rhs_wanted
586
  = do {      	 -- We allow ourselves to unify environment 
587
		 -- variables: runTcS runs with NoUntouchables
588
         (resid_wanted, _) <- solveWantedsTcM (lhs_wanted `andWC` rhs_wanted)
589
                              -- Post: these are zonked and unflattened
590

591 592
       ; zonked_lhs_flats <- zonkCts (wc_flat lhs_wanted)
       ; let (q_cts, non_q_cts) = partitionBag quantify_me zonked_lhs_flats
593 594 595 596 597 598 599 600 601 602 603 604
             quantify_me  -- Note [RULE quantification over equalities]
               | insolubleWC resid_wanted = quantify_insol
               | otherwise                = quantify_normal

             quantify_insol ct = not (isEqPred (ctPred ct))

             quantify_normal ct
               | EqPred t1 t2 <- classifyPredType (ctPred ct)
               = not (t1 `eqType` t2)
               | otherwise
               = True
             
605
       ; traceTc "simplifyRule" $
606
         vcat [ ptext (sLit "LHS of rule") <+> doubleQuotes (ftext name)
607
              , text "zonked_lhs_flats" <+> ppr zonked_lhs_flats 
608 609
              , text "q_cts"      <+> ppr q_cts ]

610
       ; return ( map (ctEvId . ctEvidence) (bagToList q_cts)
611
                , lhs_wanted { wc_flat = non_q_cts }) }
612 613 614
\end{code}


615 616 617 618 619
*********************************************************************************
*                                                                                 * 
*                                 Main Simplifier                                 *
*                                                                                 *
***********************************************************************************
620

621 622 623 624 625 626
Note [Deferring coercion errors to runtime]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
While developing, sometimes it is desirable to allow compilation to succeed even
if there are type errors in the code. Consider the following case:

  module Main where
627

628 629
  a :: Int
  a = 'a'
630

631
  main = print "b"
632

633 634
Even though `a` is ill-typed, it is not used in the end, so if all that we're
interested in is `main` it is handy to be able to ignore the problems in `a`.
635

636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
Since we treat type equalities as evidence, this is relatively simple. Whenever
we run into a type mismatch in TcUnify, we normally just emit an error. But it
is always safe to defer the mismatch to the main constraint solver. If we do
that, `a` will get transformed into

  co :: Int ~ Char
  co = ...

  a :: Int
  a = 'a' `cast` co

The constraint solver would realize that `co` is an insoluble constraint, and
emit an error with `reportUnsolved`. But we can also replace the right-hand side
of `co` with `error "Deferred type error: Int ~ Char"`. This allows the program
to compile, and it will run fine unless we evaluate `a`. This is what
`deferErrorsToRuntime` does.

It does this by keeping track of which errors correspond to which coercion
in TcErrors (with ErrEnv). TcErrors.reportTidyWanteds does not print the errors
and does not fail if -fwarn-type-errors is on, so that we can continue
compilation. The errors are turned into warnings in `reportUnsolved`.

658 659 660 661 662 663 664 665 666 667
Note [Zonk after solving]
~~~~~~~~~~~~~~~~~~~~~~~~~
We zonk the result immediately after constraint solving, for two reasons:

a) because zonkWC generates evidence, and this is the moment when we
   have a suitable evidence variable to hand.

Note that *after* solving the constraints are typically small, so the
overhead is not great.

668
\begin{code}
669 670 671 672
solveWantedsTcMWithEvBinds :: EvBindsVar
                           -> WantedConstraints
                           -> (WantedConstraints -> TcS WantedConstraints)
                           -> TcM WantedConstraints
673 674 675 676 677 678
-- Returns a *zonked* result
-- We zonk when we finish primarily to un-flatten out any
-- flatten-skolems etc introduced by canonicalisation of
-- types involving type funuctions.  Happily the result 
-- is typically much smaller than the input, indeed it is 
-- often empty.
679
solveWantedsTcMWithEvBinds ev_binds_var wc tcs_action
680 681
  = do { traceTc "solveWantedsTcMWithEvBinds" $ text "wanted=" <+> ppr wc
       ; wc2 <- runTcSWithEvBinds ev_binds_var (tcs_action wc)
682
       ; zonkWC ev_binds_var wc2 }
683
         -- See Note [Zonk after solving]
684

685
solveWantedsTcM :: WantedConstraints -> TcM (WantedConstraints, Bag EvBind)
686
-- Zonk the input constraints, and simplify them
687
-- Return the evidence binds in the BagEvBinds result
688
-- Discards all Derived stuff in result
689
-- Postcondition: fully zonked and unflattened constraints
690
solveWantedsTcM wanted 
691 692 693
  = do { ev_binds_var <- newTcEvBinds
       ; wanteds' <- solveWantedsTcMWithEvBinds ev_binds_var wanted solve_wanteds_and_drop
       ; binds <- TcRnMonad.getTcEvBinds ev_binds_var
694
       ; return (wanteds', binds) }
695

696 697 698 699 700
solve_wanteds_and_drop :: WantedConstraints -> TcS (WantedConstraints)
-- Since solve_wanteds returns the residual WantedConstraints,
-- it should alway be called within a runTcS or something similar,
solve_wanteds_and_drop wanted = do { wc <- solve_wanteds wanted 
                                   ; return (dropDerivedWC wc) }
701 702

solve_wanteds :: WantedConstraints -> TcS WantedConstraints 
703
-- so that the inert set doesn't mindlessly propagate.
704
-- NB: wc_flats may be wanted /or/ derived now
705
solve_wanteds wanted@(WC { wc_flat = flats, wc_impl = implics, wc_insol = insols }) 
706 707
  = do { traceTcS "solveWanteds {" (ppr wanted)

708
         -- Try the flat bit, including insolubles. Solving insolubles a 
Simon Peyton Jones's avatar
Simon Peyton Jones committed
709
         -- second time round is a bit of a waste; but the code is simple 
710 711 712
         -- and the program is wrong anyway, and we don't run the danger 
         -- of adding Derived insolubles twice; see 
         -- TcSMonad Note [Do not add duplicate derived insolubles] 
713
       ; traceTcS "solveFlats {" empty
714
       ; let all_flats = flats `unionBags` insols
715 716
       ; impls_from_flats <- solveInteract all_flats
       ; traceTcS "solveFlats end }" (ppr impls_from_flats)
717

718 719
       -- solve_wanteds iterates when it is able to float equalities 
       -- out of one or more of the implications. 
720
       ; unsolved_implics <- simpl_loop 1 (implics `unionBags` impls_from_flats)
721

722 723
       ; (unsolved_flats, insoluble_flats) <- getInertUnsolved

724 725 726 727 728 729
        -- We used to unflatten here but now we only do it once at top-level
        -- during zonking -- see Note [Unflattening while zonking] in TcMType
       ; let wc = WC { wc_flat  = unsolved_flats   
                     , wc_impl  = unsolved_implics 
                     , wc_insol = insoluble_flats }
                  
730
       ; bb <- getTcEvBindsMap
731
       ; tb <- getTcSTyBindsMap
732
       ; traceTcS "solveWanteds }" $
733
                 vcat [ text "unsolved_flats   =" <+> ppr unsolved_flats
734
                      , text "unsolved_implics =" <+> ppr unsolved_implics
735
                      , text "current evbinds  =" <+> ppr (evBindMapBinds bb)
736
                      , text "current tybinds  =" <+> vcat (map ppr (varEnvElts tb))
737
                      , text "final wc =" <+> ppr wc ]
738

739
       ; return wc }
740 741 742 743 744 745 746 747

simpl_loop :: Int
           -> Bag Implication
           -> TcS (Bag Implication)
simpl_loop n implics
  | n > 10 
  = traceTcS "solveWanteds: loop!" empty >> return implics
  | otherwise 
748 749 750 751 752 753 754
  = do { (floated_eqs, unsolved_implics) <- solveNestedImplications implics
       ; if isEmptyBag floated_eqs 
         then return unsolved_implics 
         else 
    do {   -- Put floated_eqs into the current inert set before looping
         impls_from_eqs <- solveInteract floated_eqs
       ; simpl_loop (n+1) (unsolved_implics `unionBags` impls_from_eqs)} }
755

756

757 758 759 760 761 762 763 764 765
solveNestedImplications :: Bag Implication
                        -> TcS (Cts, Bag Implication)
-- Precondition: the TcS inerts may contain unsolved flats which have 
-- to be converted to givens before we go inside a nested implication.
solveNestedImplications implics
  | isEmptyBag implics
  = return (emptyBag, emptyBag)
  | otherwise 
  = do { inerts <- getTcSInerts
766 767
       ; let thinner_inerts = prepareInertsForImplications inerts
                 -- See Note [Preparing inert set for implications]
768
  
769
       ; traceTcS "solveNestedImplications starting {" $ 
770
         vcat [ text "original inerts = " <+> ppr inerts
771 772
              , text "thinner_inerts  = " <+> ppr thinner_inerts ]
         
773
       ; (floated_eqs, unsolved_implics)
774
           <- flatMapBagPairM (solveImplication thinner_inerts) implics
775 776 777 778

       -- ... and we are back in the original TcS inerts 
       -- Notice that the original includes the _insoluble_flats so it was safe to ignore
       -- them in the beginning of this function.
779
       ; traceTcS "solveNestedImplications end }" $
780
                  vcat [ text "all floated_eqs ="  <+> ppr floated_eqs
781 782
                       , text "unsolved_implics =" <+> ppr unsolved_implics ]

783
       ; return (floated_eqs, unsolved_implics) }
784

785
solveImplication :: InertSet
786 787 788 789 790
                 -> Implication    -- Wanted
                 -> TcS (Cts,      -- All wanted or derived floated equalities: var = type
                         Bag Implication) -- Unsolved rest (always empty or singleton)
-- Precondition: The TcS monad contains an empty worklist and given-only inerts 
-- which after trying to solve this implication we must restore to their original value
791
solveImplication inerts
792
     imp@(Implic { ic_untch  = untch
793 794
                 , ic_binds  = ev_binds
                 , ic_skols  = skols 
795
                 , ic_fsks   = old_fsks
796
                 , ic_given  = givens
797
                 , ic_wanted = wanteds
798 799
                 , ic_info   = info
                 , ic_env    = env })
800
  = 
801 802
    do { traceTcS "solveImplication {" (ppr imp) 

803
         -- Solve the nested constraints
804 805 806
         -- NB: 'inerts' has empty inert_fsks
       ; (new_fsks, residual_wanted) 
            <- nestImplicTcS ev_binds untch inerts $
807
               do { solveInteractGiven (mkGivenLoc info env) old_fsks givens 
808
                  ; residual_wanted <- solve_wanteds wanteds
809 810 811
                        -- solve_wanteds, *not* solve_wanteds_and_drop, because
                        -- we want to retain derived equalities so we can float
                        -- them out in floatEqualities
812 813 814 815 816 817 818
                  ; more_fsks <- getFlattenSkols
                  ; return (more_fsks ++ old_fsks, residual_wanted) }

       ; (floated_eqs, final_wanted)
             <- floatEqualities (skols ++ new_fsks) givens residual_wanted

       ; let res_implic | isEmptyWC final_wanted 
819 820
                        = emptyBag
                        | otherwise
821 822 823
                        = unitBag (imp { ic_fsks   = new_fsks
                                       , ic_wanted = dropDerivedWC final_wanted
                                       , ic_insol  = insolubleWC final_wanted })
824

825
       ; evbinds <- getTcEvBindsMap
826
       ; traceTcS "solveImplication end }" $ vcat
827
             [ text "floated_eqs =" <+> ppr floated_eqs
828
             , text "new_fsks =" <+> ppr new_fsks
829 830
             , text "res_implic =" <+> ppr res_implic
             , text "implication evbinds = " <+> ppr (evBindMapBinds evbinds) ]
831

832
       ; return (floated_eqs, res_implic) }
833 834 835 836
\end{code}


\begin{code}
837 838
floatEqualities :: [TcTyVar] -> [EvVar] -> WantedConstraints 
                -> TcS (Cts, WantedConstraints)
839 840
-- Post: The returned FlavoredEvVar's are only Wanted or Derived
-- and come from the input wanted ev vars or deriveds 
841 842
-- Also performs some unifications, adding to monadically-carried ty_binds
-- These will be used when processing floated_eqs later
843 844
floatEqualities skols can_given wanteds@(WC { wc_flat = flats })
  | hasEqualities can_given 
845
  = return (emptyBag, wanteds)   -- Note [Float Equalities out of Implications]
846
  | otherwise 
847 848
  = do { let (float_eqs, remaining_flats) = partitionBag is_floatable flats
       ; promoteTyVars float_eqs
849
       ; ty_binds <- getTcSTyBindsMap
850
       ; traceTcS "floatEqualities" (vcat [ text "Floated eqs =" <+> ppr float_eqs
851 852
                                          , text "Ty binds =" <+> ppr ty_binds])
       ; return (float_eqs, wanteds { wc_flat = remaining_flats }) }
853 854 855 856 857 858 859 860 861
  where 
    skol_set = growSkols wanteds (mkVarSet skols)

    is_floatable :: Ct -> Bool
    is_floatable ct
       = isEqPred pred && skol_set `disjointVarSet` tyVarsOfType pred
       where
         pred = ctPred ct

862
promoteTyVars :: Cts -> TcS ()
863 864 865
-- When we float a constraint out of an implication we
-- must restore (MetaTvInv) in Note [Untouchable type variables]
-- in TcType
866 867 868 869
promoteTyVars cts
  = do { untch <- TcSMonad.getUntouchables
       ; mapM_ (promote_tv untch) (varSetElems (tyVarsOfCts cts)) }
  where
870 871 872 873 874 875 876 877
    promote_tv untch tv 
      | isFloatedTouchableMetaTyVar untch tv
      = do { cloned_tv <- TcSMonad.cloneMetaTyVar tv
           ; let rhs_tv = setMetaTyVarUntouchables cloned_tv untch
           ; setWantedTyBind tv (mkTyVarTy rhs_tv) }
      | otherwise
      = return ()

878 879 880 881 882 883 884 885 886
growSkols :: WantedConstraints -> VarSet -> VarSet
-- Find all the type variables that might possibly be unified
-- with a type that mentions a skolem.  This test is very conservative.
-- I don't *think* we need look inside the implications, because any 
-- relevant unification variables in there are untouchable.
growSkols (WC { wc_flat = flats }) skols
  = growThetaTyVars theta skols
  where
    theta = foldrBag ((:) . ctPred) [] flats
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911

approximateWC :: WantedConstraints -> Cts
-- Postcondition: Wanted or Derived Cts 
approximateWC wc = float_wc emptyVarSet wc
  where 
    float_wc :: TcTyVarSet -> WantedConstraints -> Cts
    float_wc skols (WC { wc_flat = flat, wc_impl = implic }) = floats1 `unionBags` floats2
      where floats1 = do_bag (float_flat skols) flat
            floats2 = do_bag (float_implic skols) implic
                                 
    float_implic :: TcTyVarSet -> Implication -> Cts
    float_implic skols imp
      = float_wc skols' (ic_wanted imp)
      where
        skols' = skols `extendVarSetList` ic_skols imp `extendVarSetList` ic_fsks imp
            
    float_flat :: TcTyVarSet -> Ct -> Cts
    float_flat skols ct
      | tyVarsOfCt ct `disjointVarSet` skols 
      = singleCt ct
      | otherwise = emptyCts
        
    do_bag :: (a -> Bag c) -> Bag a -> Bag c
    do_bag f = foldrBag (unionBags.f) emptyBag
\end{code}
912

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
913 914
Note [Float Equalities out of Implications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
For ordinary pattern matches (including existentials) we float 
equalities out of implications, for instance: 
     data T where 
       MkT :: Eq a => a -> T 
     f x y = case x of MkT _ -> (y::Int)
We get the implication constraint (x::T) (y::alpha): 
     forall a. [untouchable=alpha] Eq a => alpha ~ Int
We want to float out the equality into a scope where alpha is no
longer untouchable, to solve the implication!  

But we cannot float equalities out of implications whose givens may
yield or contain equalities:

      data T a where 
        T1 :: T Int
        T2 :: T Bool
        T3 :: T a 
        
      h :: T a -> a -> Int
      
      f x y = case x of 
                T1 -> y::Int
                T2 -> y::Bool
                T3 -> h x y

We generate constraint, for (x::T alpha) and (y :: beta): 
   [untouchables = beta] (alpha ~ Int => beta ~ Int)   -- From 1st branch
   [untouchables = beta] (alpha ~ Bool => beta ~ Bool) -- From 2nd branch
   (alpha ~ beta)                                      -- From 3rd branch 

If we float the equality (beta ~ Int) outside of the first implication and 
the equality (beta ~ Bool) out of the second we get an insoluble constraint.
But if we just leave them inside the implications we unify alpha := beta and
solve everything.

Principle: 
    We do not want to float equalities out which may need the given *evidence*
    to become soluble.

Consequence: classes with functional dependencies don't matter (since there is 
no evidence for a fundep equality), but equality superclasses do matter (since 
they carry evidence).

958 959 960 961 962 963 964 965 966
Note [Promoting unification variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we float an equality out of an implication we must "promote" free
unification variables of the equality, in order to maintain Invariant
(MetaTvInv) from Note [Untouchable type variables] in TcType.  for the
leftover implication.

This is absolutely necessary. Consider the following example. We start
with two implications and a class with a functional dependency.
967

968 969 970 971 972
    class C x y | x -> y
    instance C [a] [a]
          
    (I1)      [untch=beta]forall b. 0 => F Int ~ [beta]
    (I2)      [untch=beta]forall c. 0 => F Int ~ [[alpha]] /\ C beta [c]
973 974 975 976 977 978 979

We float (F Int ~ [beta]) out of I1, and we float (F Int ~ [[alpha]]) out of I2. 
They may react to yield that (beta := [alpha]) which can then be pushed inwards 
the leftover of I2 to get (C [alpha] [a]) which, using the FunDep, will mean that
(alpha := a). In the end we will have the skolem 'b' escaping in the untouchable
beta! Concrete example is in indexed_types/should_fail/ExtraTcsUntch.hs:

980 981 982 983 984 985 986 987 988 989 990 991 992
    class C x y | x -> y where 
     op :: x -> y -> ()

    instance C [a] [a]

    type family F a :: *

    h :: F Int -> ()
    h = undefined

    data TEx where 
      TEx :: a -> TEx 

993

994 995 996 997 998 999
    f (x::beta) = 
        let g1 :: forall b. b -> ()
            g1 _ = h [x]
            g2 z = case z of TEx y -> (h [[undefined]], op x [y])
        in (g1 '3', g2 undefined)

1000

1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019

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 
1020 1021
       of type family equations. See Inert Set invariants in TcInteract.

1022
This solving is now happening during zonking, see Note [Unflattening while zonking]
1023
in TcMType.
1024 1025


1026 1027 1028 1029 1030
*********************************************************************************
*                                                                               * 
*                          Defaulting and disamgiguation                        *
*                                                                               *
*********************************************************************************
1031
\begin{code}
1032 1033 1034
applyDefaultingRules :: Cts -> TcS Bool
  -- True <=> I did some defaulting, reflected in ty_binds
                 
1035 1036
-- Return some extra derived equalities, which express the
-- type-class default choice.