TcSimplify.lhs 69.5 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
  ) where
14

15
#include "HsVersions.h"
16

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


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

55

56
\begin{code}
57 58


59 60
simplifyTop :: WantedConstraints -> TcM (Bag EvBind)
-- Simplify top-level constraints
61 62 63
-- 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
64
simplifyTop wanteds 
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 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 139 140 141 142 143 144 145
  = do { ev_binds_var <- newTcEvBinds
                         
       ; zonked_wanteds <- zonkWC wanteds
       ; wc_first_go <- runTcSWithEvBinds ev_binds_var $ solveWanteds zonked_wanteds
       ; cts <- applyTyVarDefaulting wc_first_go 
                -- See Note [Top-level Defaulting Plan]
                
       ; let wc_for_loop = wc_first_go { wc_flat = wc_flat wc_first_go `unionBags` cts }
                           
       ; traceTc "simpl_top_loop {" $ text "zonked_wc =" <+> ppr zonked_wanteds
       ; simpl_top_loop ev_binds_var wc_for_loop }
    
  where simpl_top_loop ev_binds_var wc
          | isEmptyWC wc 
          = do { traceTc "simpl_top_loop }" empty
               ; TcRnMonad.getTcEvBinds ev_binds_var }
          | otherwise
          = do { wc_residual <- runTcSWithEvBinds ev_binds_var $ solveWanteds wc
               ; let wc_flat_approximate = approximateWC wc_residual
               ; (dflt_eqs,_unused_bind) <- runTcS $
                                            applyDefaultingRules wc_flat_approximate
                                            -- See Note [Top-level Defaulting Plan]
               ; if isEmptyBag dflt_eqs then 
                   do { traceTc "simpl_top_loop }" empty
                      ; report_and_finish ev_binds_var wc_residual }
                 else
                   simpl_top_loop ev_binds_var $ 
                   wc_residual { wc_flat = wc_flat wc_residual `unionBags` dflt_eqs } }

        report_and_finish ev_binds_var wc_residual 
          = do { eb1 <- TcRnMonad.getTcEvBinds ev_binds_var
               ; traceTc "reportUnsolved {" empty
                   -- See Note [Deferring coercion errors to runtime]
               ; runtimeCoercionErrors <- doptM Opt_DeferTypeErrors
               ; eb2 <- reportUnsolved runtimeCoercionErrors wc_residual
               ; traceTc "reportUnsolved }" empty
               ; return (eb1 `unionBags` eb2) }
\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}
146

147 148 149
------------------
simplifyAmbiguityCheck :: Name -> WantedConstraints -> TcM (Bag EvBind)
simplifyAmbiguityCheck name wanteds
150 151
  = traceTc "simplifyAmbiguityCheck" (text "name =" <+> ppr name) >> 
    simplifyCheck wanteds
152
 
153 154 155
------------------
simplifyInteractive :: WantedConstraints -> TcM (Bag EvBind)
simplifyInteractive wanteds 
156 157
  = traceTc "simplifyInteractive" empty >>
    simplifyTop wanteds 
158 159 160 161 162

------------------
simplifyDefault :: ThetaType	-- Wanted; has no type variables in it
                -> TcM ()	-- Succeeds iff the constraint is soluble
simplifyDefault theta
163 164 165
  = do { traceTc "simplifyInteractive" empty
       ; wanted <- newFlatWanteds DefaultOrigin theta
       ; _ignored_ev_binds <- simplifyCheck (mkFlatWC wanted)
166 167
       ; return () }
\end{code}
168

169

170
***********************************************************************************
171
*                                                                                 * 
172
*                            Deriving                                             *
173 174
*                                                                                 *
***********************************************************************************
175

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

192
       ; let subst_skol = zipTopTvSubst tvs_skols $ map mkTyVarTy tvs
193
             skol_set   = mkVarSet tvs_skols
194
	     doc = ptext (sLit "deriving") <+> parens (ppr pred)
195 196 197

       ; wanted <- newFlatWanteds orig (substTheta skol_subst theta)

198 199
       ; traceTc "simplifyDeriv" $ 
         vcat [ pprTvBndrs tvs $$ ppr theta $$ ppr wanted, doc ]
200
       ; (residual_wanted, _ev_binds1)
201
             <- runTcS $ solveWanteds (mkFlatWC wanted)
202

203 204
       ; let (good, bad) = partitionBagWith get_good (wc_flat residual_wanted)
                         -- See Note [Exotic derived instance contexts]
205 206 207
             get_good :: Ct -> Either PredType Ct
             get_good ct | validDerivPred skol_set p = Left p
                         | otherwise                 = Right ct
208
                         where p = ctPred ct
209

210 211 212
       -- We never want to defer these errors because they are errors in the
       -- compiler! Hence the `False` below
       ; _ev_binds2 <- reportUnsolved False (residual_wanted { wc_flat = bad })
213

214 215
       ; let min_theta = mkMinimalBySCs (bagToList good)
       ; return (substTheta subst_skol min_theta) }
216
\end{code}
217

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
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

243 244 245 246 247 248 249
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.
250

251 252 253
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)
254

255 256
Notice that this instance (just) satisfies the Paterson termination 
conditions.  Then we *could* derive an instance decl like this:
257

258 259 260 261
	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.  
262

263 264 265
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.
266

267 268
So for now we simply require that the derived instance context
should have only type-variable constraints.
269

270 271 272 273 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
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
*                                                                                 *
***********************************************************************************
299

dreixel's avatar
dreixel committed
300 301 302 303 304 305 306 307 308 309 310 311
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.

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

334
  | otherwise
335 336
  = do { zonked_wanteds <- zonkWC wanteds
       ; gbl_tvs        <- tcGetGlobalTyVars
337
       ; zonked_tau_tvs <- zonkTyVarsAndFV (tyVarsOfTypes (map snd name_taus))
338
       ; runtimeCoercionErrors <- doptM Opt_DeferTypeErrors
339

340
       ; traceTc "simplifyInfer {"  $ vcat
341
             [ ptext (sLit "names =") <+> ppr (map fst name_taus)
342 343
             , ptext (sLit "taus =") <+> ppr (map snd name_taus)
             , ptext (sLit "tau_tvs (zonked) =") <+> ppr zonked_tau_tvs
344 345 346
             , ptext (sLit "gbl_tvs =") <+> ppr gbl_tvs
             , ptext (sLit "closed =") <+> ppr _top_lvl
             , ptext (sLit "apply_mr =") <+> ppr apply_mr
347
             , ptext (sLit "untch =") <+> ppr untch
348
             , ptext (sLit "wanted =") <+> ppr zonked_wanteds
349 350
             ]

351 352
             -- Step 1
             -- Make a guess at the quantified type variables
353 354 355
	     -- Then split the constraints on the baisis of those tyvars
	     -- to avoid unnecessarily simplifying a class constraint
	     -- See Note [Avoid unecessary constraint simplification]
356
       ; let proto_qtvs = growWanteds gbl_tvs zonked_wanteds $
357
                          zonked_tau_tvs `minusVarSet` gbl_tvs
358
             (perhaps_bound, surely_free)
359
                        = partitionBag (quantifyMe proto_qtvs ctPred) (wc_flat zonked_wanteds)
360 361 362 363 364 365 366

       ; 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
             ]

367 368 369 370
       ; traceTc "sinf"  $ vcat
             [ ptext (sLit "perhaps_bound =") <+> ppr perhaps_bound
             , ptext (sLit "surely_free   =") <+> ppr surely_free
             ]
371 372 373
             
       ; emitFlats surely_free      
         
374
            -- Step 2 
375
            -- Now simplify the possibly-bound constraints
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
       ; let wanteds_to_approximate = zonked_wanteds { wc_flat = perhaps_bound }
             
       ; traceTc "simplifyWithApprox" $
         ptext (sLit "wanteds_to_approximate = ") <+> ppr wanteds_to_approximate
              -- 2.1) First try full-blown solving
       ; ev_binds_var <- newTcEvBinds
       ; wanted_transformed 
             <- runTcSWithEvBinds ev_binds_var $ solveWanteds wanteds_to_approximate
              -- 2.2) Fail fast if there is an insoluble constraint,
              -- unless we are deferring errors to runtime
       ; when (not runtimeCoercionErrors && insolubleWC wanted_transformed) $ 
         do { _ev_binds <- reportUnsolved False wanted_transformed; failM }
              -- 2.3) Candidates for quantification are an approximation of wanted_transformed
       ; let quant_candidates = approximateWC wanted_transformed               
              -- 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]
                                
              -- 2.4) Minimize the quantification candidates                             
       ; (quant_candidates_transformed, _extra_binds)   
             <- runTcS $ solveWanteds $ WC { wc_flat  = quant_candidates
                                           , wc_impl  = emptyBag
                                           , wc_insol = emptyBag }
              -- 2.5) Final candidates for quantification                
       ; let final_quant_candidates :: Bag PredType
             final_quant_candidates = mapBag ctPred $ 
                                      keepWanted (wc_flat quant_candidates_transformed)
             -- NB: Already the fixpoint of any unifications that may have happened
                  
       ; gbl_tvs        <- tcGetGlobalTyVars -- TODO: can we just use untch instead of gbl_tvs?
406
       ; zonked_tau_tvs <- zonkTyVarsAndFV zonked_tau_tvs
407 408 409 410 411 412
       
       ; traceTc "simplifyWithApprox" $
         vcat [ ptext (sLit "final_quant_candidates =") <+> ppr final_quant_candidates
              , ptext (sLit "gbl_tvs=") <+> ppr gbl_tvs
              , ptext (sLit "zonked_tau_tvs=") <+> ppr zonked_tau_tvs ]
         
413
       ; let init_tvs 	     = zonked_tau_tvs `minusVarSet` gbl_tvs
414 415 416 417 418 419 420
             poly_qtvs       = growPreds gbl_tvs id final_quant_candidates init_tvs
             
             pbound          = filterBag (quantifyMe poly_qtvs id) final_quant_candidates
             
       ; traceTc "simplifyWithApprox" $
         vcat [ ptext (sLit "pbound =") <+> ppr pbound ]
         
421
	     -- Monomorphism restriction
422 423
       ; let mr_qtvs  	     = init_tvs `minusVarSet` constrained_tvs
             constrained_tvs = tyVarsOfBag tyVarsOfType final_quant_candidates
424 425
	     mr_bites        = apply_mr && not (isEmptyBag pbound)

426 427 428 429
             (qtvs, bound)
                | mr_bites  = (mr_qtvs,   emptyBag)
                | otherwise = (poly_qtvs, pbound)
             
430

431
       ; if isEmptyVarSet qtvs && isEmptyBag bound
432 433 434 435
         then ASSERT( isEmptyBag (wc_insol wanted_transformed) )
              do { traceTc "} simplifyInfer/no quantification" empty                   
                 ; emitWC wanted_transformed
                 ; return ([], [], mr_bites, TcEvBinds ev_binds_var) }
436 437
         else do

438 439 440
       { traceTc "simplifyApprox" $ 
         ptext (sLit "bound are =") <+> ppr bound 
         
441
            -- Step 4, zonk quantified variables 
442
       ; let minimal_flat_preds = mkMinimalBySCs $ bagToList bound
443 444
             skol_info = InferSkol [ (name, mkSigmaTy [] minimal_flat_preds ty)
                                   | (name, ty) <- name_taus ]
445 446 447 448
                        -- 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
449
       ; qtvs_to_return <- zonkQuantifiedTyVars (varSetElems qtvs)
450 451 452 453

            -- Step 5
            -- Minimize `bound' and emit an implication
       ; minimal_bound_ev_vars <- mapM TcMType.newEvVar minimal_flat_preds
454
                                           
455
       ; lcl_env <- getLclTypeEnv
dreixel's avatar
dreixel committed
456
       ; gloc <- getCtLoc skol_info
457 458
                 
       ; let implic = Implic { ic_untch    = untch 
459
                             , ic_env      = lcl_env
460
                             , ic_skols    = qtvs_to_return
461
                             , ic_given    = minimal_bound_ev_vars
462
                             , ic_wanted   = wanted_transformed 
463 464 465
                             , ic_insol    = False
                             , ic_binds    = ev_binds_var
                             , ic_loc      = gloc }
466
                      
467
       ; emitImplication implic
468
         
469 470 471
       ; traceTc "} simplifyInfer/produced residual implication for quantification" $
             vcat [ ptext (sLit "implic =") <+> ppr implic
                       -- ic_skols, ic_given give rest of result
472
                  , ptext (sLit "qtvs =") <+> ppr qtvs_to_return
473
                  , ptext (sLit "spb =") <+> ppr final_quant_candidates
474 475
                  , ptext (sLit "bound =") <+> ppr bound ]

476 477
       ; return ( qtvs_to_return, minimal_bound_ev_vars
                , mr_bites,  TcEvBinds ev_binds_var) } }
478
    where 
479
\end{code}
480 481


482 483 484 485 486 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
Note [Note [Default while Inferring]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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.



518 519
Note [Minimize by Superclasses]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
520

521 522 523 524 525 526 527
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.
528

529

530
\begin{code}
531

532

533 534
approximateWC :: WantedConstraints -> Cts
approximateWC wc = float_wc emptyVarSet wc
535
  where 
536 537 538 539 540 541
    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
542
    float_implic skols imp
543 544 545 546 547 548 549 550 551 552
      = float_wc (skols `extendVarSetList` ic_skols imp) (ic_wanted imp)
            
    float_flat :: TcTyVarSet -> Ct -> Cts
    float_flat skols ct
      | tyVarsOfCt ct `disjointVarSet` skols 
      , isWantedCt ct = singleCt ct
      | otherwise = emptyCts
        
    do_bag :: (a -> Bag c) -> Bag a -> Bag c
    do_bag f = foldrBag (unionBags.f) emptyBag
553 554


555
\end{code}
556

557
\begin{code}
558 559
-- (growX gbls wanted tvs) grows a seed 'tvs' against the 
-- X-constraint 'wanted', nuking the 'gbls' at each stage
560 561
-- It's conservative in that if the seed could *possibly*
-- grow to include a type variable, then it does
562

563

564 565 566
growWanteds :: TyVarSet -> WantedConstraints -> TyVarSet -> TyVarSet
growWanteds gbl_tvs wc = fixVarSet (growWC gbl_tvs wc)

567

568 569 570
--------  Helper functions, do not do fixpoint ------------------------
growWC :: TyVarSet -> WantedConstraints -> TyVarSet -> TyVarSet
growWC gbl_tvs wc = growImplics gbl_tvs             (wc_impl wc) .
571 572
                    growPreds   gbl_tvs ctPred (wc_flat wc) .
                    growPreds   gbl_tvs ctPred (wc_insol wc)
573

574 575 576 577 578
growImplics :: TyVarSet -> Bag Implication -> TyVarSet -> TyVarSet
growImplics gbl_tvs implics tvs
  = foldrBag grow_implic tvs implics
  where
    grow_implic implic tvs
579
      = grow tvs `delVarSetList` ic_skols implic
580 581 582 583 584
      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

585

586 587 588
growPreds :: TyVarSet -> (a -> PredType) -> Bag a -> TyVarSet -> TyVarSet
growPreds gbl_tvs get_pred items tvs
  = foldrBag extend tvs items
589
  where
590 591
    extend item tvs = tvs `unionVarSet`
                      (growPredTyVars (get_pred item) tvs `minusVarSet` gbl_tvs)
592 593 594

--------------------
quantifyMe :: TyVarSet      -- Quantifying over these
595 596 597
	   -> (a -> PredType)
	   -> a -> Bool	    -- True <=> quantify over this wanted
quantifyMe qtvs toPred ct
598
  | isIPPred pred = True  -- Note [Inheriting implicit parameters]
batterseapower's avatar
batterseapower committed
599
  | otherwise	  = tyVarsOfType pred `intersectsVarSet` qtvs
600
  where
601
    pred = toPred ct
602
\end{code}
603

604 605 606 607 608 609
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
610

611
   instance C t => C [t] where ..
612

613 614 615 616 617 618 619 620 621
   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.
622 623 624
The example that needs this is:

   typecheck/should_compile/T4361.hs
625 626


627 628
Note [Inheriting implicit parameters]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
629 630 631
Consider this:

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

633 634 635
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:
636

637 638 639
	f :: Int -> Int

(so we get ?y from the context of f's definition), or
640 641 642

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

643 644 645 646 647 648
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.

649 650
BOTTOM LINE: when *inferring types* you *must* quantify 
over implicit parameters. See the predicate isFreeWhenInferring.
651

652

653 654 655 656 657
*********************************************************************************
*                                                                                 * 
*                             RULES                                               *
*                                                                                 *
***********************************************************************************
658

659
See note [Simplifying RULE consraints] in TcRule
660

661 662 663 664 665 666 667 668 669 670 671 672 673 674
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.
675 676

\begin{code}
677 678 679
simplifyRule :: RuleName 
             -> WantedConstraints	-- Constraints from LHS
             -> WantedConstraints	-- Constraints from RHS
680 681 682 683 684
             -> TcM ([EvVar], WantedConstraints)   -- LHS evidence varaibles
-- See Note [Simplifying RULE constraints] in TcRule
simplifyRule name lhs_wanted rhs_wanted
  = do { zonked_all <- zonkWC (lhs_wanted `andWC` rhs_wanted)
       ; let doc = ptext (sLit "LHS of rule") <+> doubleQuotes (ftext name)
685
             
686
             	 -- We allow ourselves to unify environment 
687 688
		 -- variables: runTcS runs with NoUntouchables
       ; (resid_wanted, _) <- runTcS (solveWanteds zonked_all)
689

690 691
       ; zonked_lhs <- zonkWC lhs_wanted

692 693 694 695 696 697 698 699 700 701 702 703 704
       ; let (q_cts, non_q_cts) = partitionBag quantify_me (wc_flat zonked_lhs)
             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
             
705
       ; traceTc "simplifyRule" $
706 707
         vcat [ doc
              , text "zonked_lhs" <+> ppr zonked_lhs 
708 709
              , text "q_cts"      <+> ppr q_cts ]

710 711
       ; return ( map (ctEvId . ctEvidence) (bagToList q_cts)
                , zonked_lhs { wc_flat = non_q_cts }) }
712 713 714
\end{code}


715 716 717 718 719
*********************************************************************************
*                                                                                 * 
*                                 Main Simplifier                                 *
*                                                                                 *
***********************************************************************************
720 721

\begin{code}
722
simplifyCheck :: WantedConstraints	-- Wanted
723 724 725 726 727 728 729 730 731 732 733 734 735
              -> 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
736
simplifyCheck wanteds
737
  = do { wanteds <- zonkWC wanteds
738 739 740 741

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

742
       ; (unsolved, eb1) <- runTcS (solveWanteds wanteds)
743 744 745

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

dimitris's avatar
dimitris committed
746
       ; traceTc "reportUnsolved {" empty
747 748 749
       -- See Note [Deferring coercion errors to runtime]
       ; runtimeCoercionErrors <- doptM Opt_DeferTypeErrors
       ; eb2 <- reportUnsolved runtimeCoercionErrors unsolved 
dimitris's avatar
dimitris committed
750 751
       ; traceTc "reportUnsolved }" empty

752 753 754 755 756 757 758 759 760 761
       ; return (eb1 `unionBags` eb2) }
\end{code}

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
762

763 764
  a :: Int
  a = 'a'
765

766
  main = print "b"
767

768 769
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`.
770

771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
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`.

\begin{code}
solveWanteds :: WantedConstraints -> TcS WantedConstraints
795 796
-- Returns: residual constraints, plus evidence bindings 
-- NB: When we are called from TcM there are no inerts to pass down to TcS
797
solveWanteds wanted
798
  = do { (_,wc_out) <- solve_wanteds wanted
799 800
       ; let wc_ret = wc_out { wc_flat = keepWanted (wc_flat wc_out) } 
                      -- Discard Derived
801
       ; return wc_ret }
802 803

solve_wanteds :: WantedConstraints
804 805 806
              -> TcS (TvSubst, WantedConstraints) 
              -- NB: wc_flats may be wanted *or* derived now
              -- Returns the flattening substitution as well in case we need to apply it
807
solve_wanteds wanted@(WC { wc_flat = flats, wc_impl = implics, wc_insol = insols }) 
808 809 810
  = do { traceTcS "solveWanteds {" (ppr wanted)

                 -- Try the flat bit
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
811 812 813 814 815
                 -- 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!
816

817 818 819 820 821 822 823
                 -- DV: why only keepWanted? We make sure that we never float out
                 -- whatever constraints can yield equalities, including class 
                 -- constraints with functional dependencies and hence all the derived
                 -- that were potentially insoluble will be re-generated.
                 -- (It would not hurt though to just keep the wanted and the derived)
                 -- See Note [The HasEqualities Predicate] in Inst.lhs
         
824
       ; let all_flats = flats `unionBags` keepWanted insols
825
                         
826
       ; impls_from_flats <- solveInteractCts $ bagToList all_flats
827

828 829
       -- solve_wanteds iterates when it is able to float equalities 
       -- out of one or more of the implications. 
830
       ; unsolved_implics <- simpl_loop 1 (implics `unionBags` impls_from_flats)
831

832 833 834
       ; (insoluble_flats,unsolved_flats) <- extractUnsolvedTcS 

       ; bb <- getTcEvBindsMap
835
       ; tb <- getTcSTyBindsMap
836

837
       ; traceTcS "solveWanteds }" $
838
                 vcat [ text "unsolved_flats   =" <+> ppr unsolved_flats
839
                      , text "unsolved_implics =" <+> ppr unsolved_implics
840
                      , text "current evbinds  =" <+> ppr (evBindMapBinds bb)
841 842 843
                      , text "current tybinds  =" <+> vcat (map ppr (varEnvElts tb))
                      ]

844
       ; (subst, remaining_unsolved_flats) <- solveCTyFunEqs unsolved_flats
845
                -- See Note [Solving Family Equations]
846 847
                -- NB: remaining_flats has already had subst applied

848 849 850 851 852
       ; traceTcS "solveWanteds finished with" $
                 vcat [ text "remaining_unsolved_flats =" <+> ppr remaining_unsolved_flats
                      , text "subst =" <+> ppr subst
                      ]

853
       ; return $ 
854 855 856
         (subst, WC { wc_flat  = mapBag (substCt subst) remaining_unsolved_flats
                    , wc_impl  = mapBag (substImplication subst) unsolved_implics
                    , wc_insol = mapBag (substCt subst) insoluble_flats })
857 858 859 860 861 862 863 864 865 866
       }

simpl_loop :: Int
           -> Bag Implication
           -> TcS (Bag Implication)
simpl_loop n implics
  | n > 10 
  = traceTcS "solveWanteds: loop!" empty >> return implics
  | otherwise 
  = do { (implic_eqs, unsolved_implics) <- solveNestedImplications implics
867

868 869
       ; inerts <- getTcSInerts
       ; let ((_,unsolved_flats),_) = extractUnsolved inerts
dimitris's avatar
dimitris committed
870
                                      
871 872 873 874 875
       ; let improve_eqs = implic_eqs
             -- NB: improve_eqs used to contain defaulting equations HERE but 
             -- defaulting now happens only at simplifyTop and not deep inside 
             -- simpl_loop! See Note [Top-level Defaulting Plan]
             
876 877 878 879
       ; traceTcS "solveWanteds: simpl_loop end" $
             vcat [ text "improve_eqs      =" <+> ppr improve_eqs
                  , text "unsolved_flats   =" <+> ppr unsolved_flats
                  , text "unsolved_implics =" <+> ppr unsolved_implics ]
880

881
       ; if isEmptyBag improve_eqs then return unsolved_implics 
882 883 884
         else do { impls_from_eqs <- solveInteractCts $ bagToList improve_eqs
                 ; simpl_loop (n+1) (unsolved_implics `unionBags` 
                                                 impls_from_eqs)} }
885

886 887 888 889 890 891 892 893 894
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
895 896
       ; traceTcS "solveNestedImplications starting, inerts are:" $ ppr inerts
         
897
       ; let ((_insoluble_flats, unsolved_flats),thinner_inerts) = extractUnsolved inerts 
898 899 900 901 902 903
       ; traceTcS "solveNestedImplications starting, more info:" $ 
         vcat [ text "inerts          = " <+> ppr inerts
              , text "insoluble_flats = " <+> ppr _insoluble_flats
              , text "unsolved_flats  = " <+> ppr unsolved_flats
              , text "thinner_inerts  = " <+> ppr thinner_inerts ]
         
904 905 906
       ; (implic_eqs, unsolved_implics)
           <- doWithInert thinner_inerts $ 
              do { let pushed_givens = givens_from_wanteds unsolved_flats
907 908 909 910 911 912 913
                       tcs_untouchables 
                         = foldr (unionVarSet . tyVarsOfCt) emptyVarSet pushed_givens
                                          -- Typically pushed_givens is very small, consists
                                          -- only of unsolved equalities, so no inefficiency 
                                          -- danger.
                                                                                    
                                          
914 915 916 917
                 -- See Note [Preparing inert set for implications]
	         -- Push the unsolved wanteds inwards, but as givens
                 ; traceTcS "solveWanteds: preparing inerts for implications {" $ 
                   vcat [ppr tcs_untouchables, ppr pushed_givens]
918 919
                 ; impls_from_givens <- solveInteractCts pushed_givens
                                        
920
                 ; MASSERT (isEmptyBag impls_from_givens)
921 922 923 924
                       -- impls_from_givens must be empty, since we are reacting givens
                       -- with givens, and they can never generate extra implications 
                       -- from decomposition of ForAll types. (Whereas wanteds can, see
                       -- TcCanonical, canEq ForAll-ForAll case)
925
                   
926 927 928 929 930 931
                 ; traceTcS "solveWanteds: } now doing nested implications {" empty
                 ; flatMapBagPairM (solveImplication tcs_untouchables) implics }

       -- ... 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.
932 933 934 935 936 937
       ; traceTcS "solveWanteds: done nested implications }" $
                  vcat [ text "implic_eqs ="       <+> ppr implic_eqs
                       , text "unsolved_implics =" <+> ppr unsolved_implics ]

       ; return (implic_eqs, unsolved_implics) }

938 939 940
  where givens_from_wanteds = foldrBag get_wanted []
        get_wanted cc rest_givens
            | pushable_wanted cc
941 942 943 944 945
            = let fl   = ctEvidence cc
                  gfl  = Given { ctev_gloc = setCtLocOrigin (ctev_wloc fl) UnkSkol
                               , ctev_evtm = EvId (ctev_evar fl)
                               , ctev_pred = ctev_pred fl }
                  this_given = cc { cc_ev = gfl }
946 947 948 949 950 951
              in this_given : rest_givens
            | otherwise = rest_givens 

        pushable_wanted :: Ct -> Bool 
        pushable_wanted cc 
         | isWantedCt cc 
952
         = isEqPred (ctPred cc) -- see Note [Preparing inert set for implications]
953 954 955 956 957 958 959 960 961 962
         | otherwise = False 

solveImplication :: TcTyVarSet     -- Untouchable TcS unification variables
                 -> 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
solveImplication tcs_untouchables
     imp@(Implic { ic_untch  = untch
963 964 965
                 , ic_binds  = ev_binds
                 , ic_skols  = skols 
                 , ic_given  = givens
966
                 , ic_wanted = wanteds
967
                 , ic_loc    = loc })
968 969
  = shadowIPs givens $    -- See Note [Shadowing of Implicit Parameters]
    nestImplicTcS ev_binds (untch, tcs_untouchables) $
970 971
    recoverTcS (return (emptyBag, emptyBag)) $
       -- Recover from nested failures.  Even the top level is
972
       -- just a bunch of implications, so failing at the first one is bad
973 974 975
    do { traceTcS "solveImplication {" (ppr imp) 

         -- Solve flat givens
976 977 978
       ; impls_from_givens <- solveInteractGiven loc givens 
       ; MASSERT (isEmptyBag impls_from_givens)
         
979
         -- Simplify the wanteds
980 981 982 983 984 985 986
       ; (_flat_subst, 
           WC { wc_flat = unsolved_flats
              , wc_impl = unsolved_implics
              , wc_insol = insols }) <- solve_wanteds wanteds
          -- NB: Not solveWanteds because we need the derived equalities,            
          -- which may not be solvable (due to touchability) in this implication
          -- but may become solvable by spontantenous unification outside. 
987 988 989 990

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

992 993
       ; let res_wanted = WC { wc_flat  = final_flat
                             , wc_impl  = unsolved_implics
994
                             , wc_insol = insols }
995

996 997 998
             res_implic = unitImplication $
                          imp { ic_wanted = res_wanted
                              , ic_insol  = insolubleWC res_wanted }
999

1000 1001
       ; evbinds <- getTcEvBindsMap

1002 1003
       ; traceTcS "solveImplication end }" $ vcat
             [ text "res_flat_free =" <+> ppr res_flat_free
1004
             , text "implication evbinds = " <+> ppr (evBindMapBinds evbinds)
1005
             , text "res_implic =" <+> ppr res_implic ]
1006

1007
       ; return (res_flat_free, res_implic) }
1008
    -- and we are back to the original inerts
1009 1010


1011
floatEqualities :: [TcTyVar] -> [EvVar] -> Cts -> (Cts, Cts)
1012 1013 1014 1015
-- 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)
1016
          -- Note [Float Equalities out of Implications]
1017
  | otherwise = partitionBag is_floatable wantders
1018 1019
  where skol_set = mkVarSet skols
        is_floatable :: Ct -> Bool
1020
        is_floatable ct
1021
          | ct_predty <- ctPred ct
1022
          , isEqPred ct_predty
1023
          = skol_set `disjointVarSet` tvs_under_fsks ct_predty
1024
        is_floatable _ct = False
1025 1026 1027 1028 1029 1030 1031 1032

        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)
1033
        tvs_under_fsks (LitTy {})       = emptyVarSet
1034 1035 1036
        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 
1037
        	     	       	        -- can mention type variables!
1038 1039 1040 1041 1042
          | 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
1043 1044 1045 1046