TcSimplify.lhs 60.2 KB
 simonm committed Jan 08, 1998 1 \begin{code}  Ian Lynagh committed Nov 04, 2011 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  simonpj@microsoft.com committed Sep 13, 2010 9 module TcSimplify(  Simon Peyton Jones committed Aug 16, 2011 10  simplifyInfer, simplifyAmbiguityCheck,  11  simplifyDefault, simplifyDeriv,  simonpj@microsoft.com committed Sep 13, 2010 12 13  simplifyRule, simplifyTop, simplifyInteractive ) where  partain committed Jan 08, 1996 14   simonm committed Jan 08, 1998 15 #include "HsVersions.h"  partain committed Mar 19, 1996 16   simonpj committed Sep 13, 2002 17 import TcRnMonad  simonpj@microsoft.com committed Sep 13, 2010 18 import TcErrors  simonpj@microsoft.com committed Jan 02, 2007 19 import TcMType  simonpj@microsoft.com committed Sep 13, 2010 20 21 import TcType import TcSMonad  dimitris committed Nov 16, 2011 22 import TcInteract  simonpj@microsoft.com committed Sep 13, 2010 23 import Inst  24 import Unify ( niFixTvSubst, niSubstTvSet )  Simon Marlow committed Oct 11, 2006 25 import Var  simonm committed Dec 02, 1998 26 import VarSet  simonpj@microsoft.com committed Nov 12, 2010 27 import VarEnv  Simon Peyton Jones committed Dec 05, 2011 28 import TcEvidence  simonpj@microsoft.com committed Nov 12, 2010 29 import TypeRep  simonpj@microsoft.com committed Sep 13, 2010 30 31 import Name import NameEnv ( emptyNameEnv )  simonmar committed Dec 10, 2003 32 import Bag  Simon Marlow committed Oct 11, 2006 33 34 import ListSetOps import Util  simonpj@microsoft.com committed Sep 13, 2010 35 36 37 import PrelInfo import PrelNames import Class ( classKey )  Simon Peyton Jones committed Aug 16, 2011 38 import BasicTypes ( RuleName )  simonpj@microsoft.com committed Jan 12, 2011 39 import Control.Monad ( when )  simonpj@microsoft.com committed Sep 13, 2010 40 import Outputable  Ian Lynagh committed Mar 29, 2008 41 import FastString  dimitris committed Nov 16, 2011 42 import TrieMap  Simon Peyton Jones committed Jan 12, 2012 43 import DynFlags  dimitris committed Nov 16, 2011 44   partain committed Jan 08, 1996 45 46 47 \end{code}  simonpj@microsoft.com committed Sep 13, 2010 48 49 50 51 52 ********************************************************************************* * * * External interface * * * *********************************************************************************  simonpj committed Jan 25, 2001 53   simonpj@microsoft.com committed Sep 13, 2010 54 55 56 \begin{code} simplifyTop :: WantedConstraints -> TcM (Bag EvBind) -- Simplify top-level constraints  simonpj@microsoft.com committed Dec 13, 2010 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  simonpj@microsoft.com committed Sep 13, 2010 60 simplifyTop wanteds  simonpj committed Apr 19, 2011 61  = simplifyCheck (SimplCheck (ptext (sLit "top level"))) wanteds  simonpj@microsoft.com committed Sep 13, 2010 62   Simon Peyton Jones committed Aug 16, 2011 63 64 65 66 ------------------ simplifyAmbiguityCheck :: Name -> WantedConstraints -> TcM (Bag EvBind) simplifyAmbiguityCheck name wanteds = simplifyCheck (SimplCheck (ptext (sLit "ambiguity check for") <+> ppr name)) wanteds  dimitris committed Nov 16, 2011 67   simonpj@microsoft.com committed Sep 13, 2010 68 69 70 71 72 73 74 75 76 ------------------ simplifyInteractive :: WantedConstraints -> TcM (Bag EvBind) simplifyInteractive wanteds = simplifyCheck SimplInteractive wanteds ------------------ simplifyDefault :: ThetaType -- Wanted; has no type variables in it -> TcM () -- Succeeds iff the constraint is soluble simplifyDefault theta  simonpj@microsoft.com committed Jan 12, 2011 77  = do { wanted <- newFlatWanteds DefaultOrigin theta  simonpj committed Apr 19, 2011 78 79  ; _ignored_ev_binds <- simplifyCheck (SimplCheck (ptext (sLit "defaults"))) (mkFlatWC wanted)  simonpj@microsoft.com committed Sep 13, 2010 80 81  ; return () } \end{code}  simonpj committed Jan 25, 2001 82   simonpj committed May 03, 2001 83   dimitris committed Nov 16, 2011 84 ***********************************************************************************  simonpj@microsoft.com committed Sep 13, 2010 85 * *  dimitris committed Nov 16, 2011 86 * Deriving *  simonpj@microsoft.com committed Sep 13, 2010 87 88 * * ***********************************************************************************  simonpj committed May 03, 2001 89   simonpj@microsoft.com committed Sep 13, 2010 90 91 \begin{code} simplifyDeriv :: CtOrigin  simonpj committed Apr 19, 2011 92 93 94 95  -> PredType -> [TyVar] -> ThetaType -- Wanted -> TcM ThetaType -- Needed  simonpj@microsoft.com committed Sep 13, 2010 96 97 -- Given instance (wanted) => C inst_ty -- Simplify 'wanted' as much as possibles  simonpj@microsoft.com committed Jan 12, 2011 98 -- Fail if not possible  simonpj committed Apr 19, 2011 99 simplifyDeriv orig pred tvs theta  simonpj@microsoft.com committed Feb 17, 2011 100 101 102 103 104  = do { tvs_skols <- tcInstSkolTyVars tvs -- Skolemize -- The constraint solving machinery -- expects *TcTyVars* not TyVars. -- We use *non-overlappable* (vanilla) skolems -- See Note [Overlap and deriving]  simonpj@microsoft.com committed Sep 13, 2010 105 106  ; let skol_subst = zipTopTvSubst tvs $map mkTyVarTy tvs_skols  simonpj@microsoft.com committed Jan 12, 2011 107  subst_skol = zipTopTvSubst tvs_skols$ map mkTyVarTy tvs  Simon Peyton Jones committed Jul 23, 2011 108  skol_set = mkVarSet tvs_skols  simonpj committed Apr 19, 2011 109  doc = parens $ptext (sLit "deriving") <+> parens (ppr pred)  simonpj@microsoft.com committed Jan 12, 2011 110 111 112 113  ; wanted <- newFlatWanteds orig (substTheta skol_subst theta) ; traceTc "simplifyDeriv" (ppr tvs $$ppr theta$$ ppr wanted)  Simon Peyton Jones committed Jan 12, 2012 114 115 116  ; (residual_wanted, _ev_binds1) <- runTcS (SimplInfer doc) NoUntouchables emptyInert emptyWorkList$ solveWanteds $mkFlatWC wanted  simonpj@microsoft.com committed Sep 13, 2010 117   simonpj@microsoft.com committed Jan 12, 2011 118 119  ; let (good, bad) = partitionBagWith get_good (wc_flat residual_wanted) -- See Note [Exotic derived instance contexts]  dimitris committed Nov 16, 2011 120 121 122  get_good :: Ct -> Either PredType Ct get_good ct | validDerivPred skol_set p = Left p | otherwise = Right ct  dimitris committed Nov 29, 2011 123  where p = ctPred ct  simonpj@microsoft.com committed Sep 13, 2010 124   Simon Peyton Jones committed Jan 12, 2012 125 126 127  -- 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 })  simonpj@microsoft.com committed Sep 13, 2010 128   simonpj@microsoft.com committed Jan 12, 2011 129 130  ; let min_theta = mkMinimalBySCs (bagToList good) ; return (substTheta subst_skol min_theta) }  simonpj@microsoft.com committed Sep 13, 2010 131 \end{code}  simonpj committed May 03, 2001 132   simonpj@microsoft.com committed Feb 17, 2011 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 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  simonpj@microsoft.com committed Sep 13, 2010 158 159 160 161 162 163 164 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.  simonpj committed May 03, 2001 165   simonpj@microsoft.com committed Sep 13, 2010 166 167 168 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)  simonpj committed Feb 10, 2004 169   simonpj@microsoft.com committed Sep 13, 2010 170 171 Notice that this instance (just) satisfies the Paterson termination conditions. Then we *could* derive an instance decl like this:  simonpj committed Feb 10, 2004 172   simonpj@microsoft.com committed Sep 13, 2010 173 174 175 176  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.  simonpj committed Feb 10, 2004 177   simonpj@microsoft.com committed Sep 13, 2010 178 179 180 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.  simonpj committed Feb 10, 2004 181   simonpj@microsoft.com committed Sep 13, 2010 182 183 So for now we simply require that the derived instance context should have only type-variable constraints.  simonpj committed Feb 10, 2004 184   simonpj@microsoft.com committed Sep 13, 2010 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 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 * * ***********************************************************************************  simonpj committed Feb 10, 2004 214   dreixel committed Nov 11, 2011 215 216 217 218 219 220 221 222 223 224 225 226 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.  simonpj@microsoft.com committed Sep 13, 2010 227 \begin{code}  Simon Peyton Jones committed Aug 16, 2011 228 simplifyInfer :: Bool  simonpj@microsoft.com committed Jan 12, 2011 229 230 231  -> Bool -- Apply monomorphism restriction -> [(Name, TcTauType)] -- Variables to be generalised, -- and their tau-types  simonpj@microsoft.com committed Sep 13, 2010 232 233 234  -> WantedConstraints -> TcM ([TcTyVar], -- Quantify over these type variables [EvVar], -- ... and these constraints  Simon Peyton Jones committed Aug 16, 2011 235 236 237  Bool, -- The monomorphism restriction did something -- so the results type is not as general as -- it could be  simonpj@microsoft.com committed Sep 13, 2010 238  TcEvBinds) -- ... binding these evidence variables  Simon Peyton Jones committed Aug 16, 2011 239 simplifyInfer _top_lvl apply_mr name_taus wanteds  simonpj@microsoft.com committed Jan 12, 2011 240 241 242  | isEmptyWC wanteds = do { gbl_tvs <- tcGetGlobalTyVars -- Already zonked ; zonked_taus <- zonkTcTypes (map snd name_taus)  dreixel committed Nov 11, 2011 243 244 245 246  ; let tvs_to_quantify = tyVarsOfTypes zonked_taus minusVarSet gbl_tvs -- tvs_to_quantify can contain both kind and type vars -- See Note [Which variables to quantify] ; qtvs <- zonkQuantifiedTyVars tvs_to_quantify  Simon Peyton Jones committed Aug 16, 2011 247  ; return (qtvs, [], False, emptyTcEvBinds) }  simonpj committed Feb 10, 2004 248   simonpj@microsoft.com committed Sep 13, 2010 249  | otherwise  simonpj@microsoft.com committed Jan 12, 2011 250 251 252  = do { zonked_wanteds <- zonkWC wanteds ; zonked_taus <- zonkTcTypes (map snd name_taus) ; gbl_tvs <- tcGetGlobalTyVars  Simon Peyton Jones committed Jan 12, 2012 253  ; runtimeCoercionErrors <- doptM Opt_DeferTypeErrors  simonpj@microsoft.com committed Jan 12, 2011 254   simonpj@microsoft.com committed Sep 13, 2010 255  ; traceTc "simplifyInfer {"$ vcat  Simon Peyton Jones committed Aug 16, 2011 256 257 258 259 260  [ ptext (sLit "names =") <+> ppr (map fst name_taus) , ptext (sLit "taus (zonked) =") <+> ppr zonked_taus , ptext (sLit "gbl_tvs =") <+> ppr gbl_tvs , ptext (sLit "closed =") <+> ppr _top_lvl , ptext (sLit "apply_mr =") <+> ppr apply_mr  simonpj@microsoft.com committed Jan 12, 2011 261  , ptext (sLit "wanted =") <+> ppr zonked_wanteds  simonpj@microsoft.com committed Sep 13, 2010 262 263  ]  simonpj@microsoft.com committed Jan 12, 2011 264 265  -- Step 1 -- Make a guess at the quantified type variables  simonpj@microsoft.com committed Oct 08, 2010 266 267 268  -- Then split the constraints on the baisis of those tyvars -- to avoid unnecessarily simplifying a class constraint -- See Note [Avoid unecessary constraint simplification]  dreixel committed Nov 11, 2011 269  ; let zonked_tau_tvs = tyVarsOfTypes zonked_taus  simonpj@microsoft.com committed Jan 12, 2011 270  proto_qtvs = growWanteds gbl_tvs zonked_wanteds $ simonpj@microsoft.com committed Oct 08, 2010 271  zonked_tau_tvs minusVarSet gbl_tvs  simonpj@microsoft.com committed Jan 12, 2011 272 273 274 275 276 277 278 279 280  (perhaps_bound, surely_free) = partitionBag (quantifyMe proto_qtvs) (wc_flat zonked_wanteds) ; traceTc "simplifyInfer proto"$ vcat [ ptext (sLit "zonked_tau_tvs =") <+> ppr zonked_tau_tvs , ptext (sLit "proto_qtvs =") <+> ppr proto_qtvs , ptext (sLit "surely_fref =") <+> ppr surely_free ]  Simon Peyton Jones committed Jan 12, 2012 281  ; emitFlats surely_free  282 283 284 285  ; traceTc "sinf" $vcat [ ptext (sLit "perhaps_bound =") <+> ppr perhaps_bound , ptext (sLit "surely_free =") <+> ppr surely_free ]  simonpj@microsoft.com committed Oct 08, 2010 286   simonpj@microsoft.com committed Jan 12, 2011 287  -- Step 2  Simon Peyton Jones committed Jan 12, 2012 288 289 290 291 292 293 294 295 296 297 298  -- Now simplify the possibly-bound constraints ; let ctxt = SimplInfer (ppr (map fst name_taus)) ; (simpl_results, tc_binds) <- runTcS ctxt NoUntouchables emptyInert emptyWorkList$ simplifyWithApprox (zonked_wanteds { wc_flat = perhaps_bound }) -- Fail fast if there is an insoluble constraint, -- unless we are deferring errors to runtime ; when (not runtimeCoercionErrors && insolubleWC simpl_results) $do { _ev_binds <- reportUnsolved False simpl_results ; failM }  simonpj@microsoft.com committed Jan 12, 2011 299 300 301 302 303 304  -- Step 3 -- Split again simplified_perhaps_bound, because some unifications -- may have happened, and emit the free constraints. ; gbl_tvs <- tcGetGlobalTyVars ; zonked_tau_tvs <- zonkTcTyVarsAndFV zonked_tau_tvs  Simon Peyton Jones committed Jan 12, 2012 305  ; zonked_flats <- zonkCts (wc_flat simpl_results)  simonpj@microsoft.com committed Oct 08, 2010 306  ; let init_tvs = zonked_tau_tvs minusVarSet gbl_tvs  Simon Peyton Jones committed Jan 12, 2012 307 308  poly_qtvs = growWantedEVs gbl_tvs zonked_flats init_tvs (pbound, pfree) = partitionBag (quantifyMe poly_qtvs) zonked_flats  Simon Peyton Jones committed Aug 16, 2011 309 310  -- Monomorphism restriction  simonpj@microsoft.com committed Oct 08, 2010 311  mr_qtvs = init_tvs minusVarSet constrained_tvs  Simon Peyton Jones committed Jan 12, 2012 312  constrained_tvs = tyVarsOfCts zonked_flats  Simon Peyton Jones committed Aug 16, 2011 313 314 315  mr_bites = apply_mr && not (isEmptyBag pbound) (qtvs, (bound, free))  Simon Peyton Jones committed Jan 12, 2012 316  | mr_bites = (mr_qtvs, (emptyBag, zonked_flats))  Simon Peyton Jones committed Aug 16, 2011 317  | otherwise = (poly_qtvs, (pbound, pfree))  Simon Peyton Jones committed Jan 12, 2012 318  ; emitFlats free  simonpj@microsoft.com committed Jan 12, 2011 319   Simon Peyton Jones committed Aug 16, 2011 320  ; if isEmptyVarSet qtvs && isEmptyBag bound  simonpj@microsoft.com committed Jan 12, 2011 321 322 323  then ASSERT( isEmptyBag (wc_insol simpl_results) ) do { traceTc "} simplifyInfer/no quantification" empty ; emitImplications (wc_impl simpl_results)  Simon Peyton Jones committed Jan 12, 2012 324  ; return ([], [], mr_bites, EvBinds tc_binds) }  simonpj@microsoft.com committed Jan 12, 2011 325 326 327  else do -- Step 4, zonk quantified variables  dimitris committed Nov 16, 2011 328  { let minimal_flat_preds = mkMinimalBySCs$  dimitris committed Nov 29, 2011 329  map ctPred $bagToList bound  Simon Peyton Jones committed Aug 16, 2011 330 331  skol_info = InferSkol [ (name, mkSigmaTy [] minimal_flat_preds ty) | (name, ty) <- name_taus ]  simonpj@microsoft.com committed Jan 12, 2011 332 333 334 335  -- Don't add the quantified variables here, because -- they are also bound in ic_skols and we want them to be -- tidied uniformly  dreixel committed Nov 11, 2011 336  ; qtvs_to_return <- zonkQuantifiedTyVars qtvs  simonpj@microsoft.com committed Jan 12, 2011 337 338 339 340 341  -- Step 5 -- Minimize bound' and emit an implication ; minimal_bound_ev_vars <- mapM TcMType.newEvVar minimal_flat_preds ; ev_binds_var <- newTcEvBinds  Simon Peyton Jones committed Jan 12, 2012 342 343  ; mapBagM_ (\(EvBind evar etrm) -> addTcEvBind ev_binds_var evar etrm) tc_binds  simonpj@microsoft.com committed Jan 12, 2011 344  ; lcl_env <- getLclTypeEnv  dreixel committed Nov 11, 2011 345  ; gloc <- getCtLoc skol_info  simonpj@microsoft.com committed Jan 12, 2011 346 347  ; let implic = Implic { ic_untch = NoUntouchables , ic_env = lcl_env  Simon Peyton Jones committed Jan 12, 2012 348  , ic_skols = qtvs_to_return  simonpj@microsoft.com committed Jan 12, 2011 349 350 351 352 353 354 355 356 357  , ic_given = minimal_bound_ev_vars , ic_wanted = simpl_results { wc_flat = bound } , ic_insol = False , ic_binds = ev_binds_var , ic_loc = gloc } ; emitImplication implic ; traceTc "} simplifyInfer/produced residual implication for quantification"$ vcat [ ptext (sLit "implic =") <+> ppr implic -- ic_skols, ic_given give rest of result  Simon Peyton Jones committed Aug 16, 2011 358  , ptext (sLit "qtvs =") <+> ppr qtvs_to_return  Simon Peyton Jones committed Jan 12, 2012 359  , ptext (sLit "spb =") <+> ppr zonked_flats  simonpj@microsoft.com committed Jan 12, 2011 360 361 362 363  , ptext (sLit "bound =") <+> ppr bound ]  Simon Peyton Jones committed Aug 16, 2011 364 365  ; return ( qtvs_to_return, minimal_bound_ev_vars , mr_bites, TcEvBinds ev_binds_var) } }  simonpj@microsoft.com committed Jan 12, 2011 366 \end{code}  simonpj@microsoft.com committed Sep 13, 2010 367 368   simonpj@microsoft.com committed Jan 12, 2011 369 370 Note [Minimize by Superclasses] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  simonpj@microsoft.com committed Sep 13, 2010 371   simonpj@microsoft.com committed Jan 12, 2011 372 373 374 375 376 377 378 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.  simonpj@microsoft.com committed Sep 13, 2010 379   simonpj@microsoft.com committed Jan 12, 2011 380 \begin{code}  dimitris committed Nov 16, 2011 381   simonpj@microsoft.com committed Jan 12, 2011 382 simplifyWithApprox :: WantedConstraints -> TcS WantedConstraints  dimitris committed Nov 17, 2011 383 -- Post: returns only wanteds (no deriveds)  simonpj@microsoft.com committed Jan 12, 2011 384 385 simplifyWithApprox wanted = do { traceTcS "simplifyApproxLoop" (ppr wanted)  simonpj committed Feb 10, 2004 386   dimitris committed Nov 16, 2011 387 388 389 390 391 392 393 394 395  ; let all_flats = wc_flat wanted unionBags keepWanted (wc_insol wanted) ; solveInteractCts $bagToList all_flats ; unsolved_implics <- simpl_loop 1 (wc_impl wanted) ; let (residual_implics,floats) = approximateImplications unsolved_implics -- Solve extra stuff for real: notice that all the extra unsolved constraints will -- be in the inerts of the monad, so we are OK ; traceTcS "simplifyApproxLoop"$ text "Calling solve_wanteds!"  dimitris committed Nov 17, 2011 396 397 398 399 400  ; wants_or_ders <- solve_wanteds (WC { wc_flat = floats -- They are floated so they are not in the evvar cache , wc_impl = residual_implics , wc_insol = emptyBag }) ; return $wants_or_ders { wc_flat = keepWanted (wc_flat wants_or_ders) } }  simonpj@microsoft.com committed Jan 12, 2011 401   dimitris committed Nov 16, 2011 402 403  approximateImplications :: Bag Implication -> (Bag Implication, Cts)  simonpj@microsoft.com committed Jan 12, 2011 404 405 406 -- Extracts any nested constraints that don't mention the skolems approximateImplications impls = do_bag (float_implic emptyVarSet) impls  simonpj@microsoft.com committed Sep 13, 2010 407  where  simonpj@microsoft.com committed Jan 12, 2011 408 409 410 411 412  do_bag :: forall a b c. (a -> (Bag b, Bag c)) -> Bag a -> (Bag b, Bag c) do_bag f = foldrBag (plus . f) (emptyBag, emptyBag) plus :: forall b c. (Bag b, Bag c) -> (Bag b, Bag c) -> (Bag b, Bag c) plus (a1,b1) (a2,b2) = (a1 unionBags a2, b1 unionBags b2)  dimitris committed Nov 16, 2011 413  float_implic :: TyVarSet -> Implication -> (Bag Implication, Cts)  simonpj@microsoft.com committed Jan 12, 2011 414 415 416  float_implic skols imp = (unitBag (imp { ic_wanted = wanted' }), floats) where  Simon Peyton Jones committed Jan 12, 2012 417  (wanted', floats) = float_wc (skols extendVarSetList ic_skols imp) (ic_wanted imp)  simonpj@microsoft.com committed Jan 12, 2011 418 419 420 421 422 423 424  float_wc skols wc@(WC { wc_flat = flat, wc_impl = implic }) = (wc { wc_flat = flat', wc_impl = implic' }, floats1 unionBags floats2) where (flat', floats1) = do_bag (float_flat skols) flat (implic', floats2) = do_bag (float_implic skols) implic  dimitris committed Nov 16, 2011 425 426 427 428  float_flat :: TcTyVarSet -> Ct -> (Cts, Cts) float_flat skols ct | tyVarsOfCt ct disjointVarSet skols = (emptyBag, unitBag ct) | otherwise = (unitBag ct, emptyBag)  simonpj@microsoft.com committed Sep 13, 2010 429 \end{code}  simonpj committed Feb 10, 2004 430   simonpj@microsoft.com committed Sep 13, 2010 431 \begin{code}  simonpj@microsoft.com committed Oct 08, 2010 432 433 -- (growX gbls wanted tvs) grows a seed 'tvs' against the -- X-constraint 'wanted', nuking the 'gbls' at each stage  simonpj@microsoft.com committed Jan 12, 2011 434 435 -- It's conservative in that if the seed could *possibly* -- grow to include a type variable, then it does  simonpj@microsoft.com committed Oct 19, 2010 436   simonpj@microsoft.com committed Jan 12, 2011 437 438 439 growWanteds :: TyVarSet -> WantedConstraints -> TyVarSet -> TyVarSet growWanteds gbl_tvs wc = fixVarSet (growWC gbl_tvs wc)  dimitris committed Nov 16, 2011 440 growWantedEVs :: TyVarSet -> Cts -> TyVarSet -> TyVarSet  simonpj@microsoft.com committed Jan 12, 2011 441 442 growWantedEVs gbl_tvs ws tvs | isEmptyBag ws = tvs  dimitris committed Nov 29, 2011 443  | otherwise = fixVarSet (growPreds gbl_tvs ctPred ws) tvs  simonpj@microsoft.com committed Oct 19, 2010 444   simonpj@microsoft.com committed Jan 12, 2011 445 446 447 -------- Helper functions, do not do fixpoint ------------------------ growWC :: TyVarSet -> WantedConstraints -> TyVarSet -> TyVarSet growWC gbl_tvs wc = growImplics gbl_tvs (wc_impl wc) .  dimitris committed Nov 29, 2011 448 449  growPreds gbl_tvs ctPred (wc_flat wc) . growPreds gbl_tvs ctPred (wc_insol wc)  simonpj@microsoft.com committed Sep 13, 2010 450   simonpj@microsoft.com committed Jan 12, 2011 451 452 453 454 455 growImplics :: TyVarSet -> Bag Implication -> TyVarSet -> TyVarSet growImplics gbl_tvs implics tvs = foldrBag grow_implic tvs implics where grow_implic implic tvs  Simon Peyton Jones committed Jan 12, 2012 456  = grow tvs delVarSetList ic_skols implic  simonpj@microsoft.com committed Jan 12, 2011 457 458 459 460 461 462 463 464  where grow = growWC gbl_tvs (ic_wanted implic) . growPreds gbl_tvs evVarPred (listToBag (ic_given implic)) -- We must grow from givens too; see test IPRun growPreds :: TyVarSet -> (a -> PredType) -> Bag a -> TyVarSet -> TyVarSet growPreds gbl_tvs get_pred items tvs = foldrBag extend tvs items  simonpj@microsoft.com committed Oct 19, 2010 465  where  simonpj@microsoft.com committed Jan 12, 2011 466 467  extend item tvs = tvs unionVarSet (growPredTyVars (get_pred item) tvs minusVarSet gbl_tvs)  simonpj@microsoft.com committed Sep 13, 2010 468 469 470  -------------------- quantifyMe :: TyVarSet -- Quantifying over these  dimitris committed Nov 16, 2011 471  -> Ct  simonpj@microsoft.com committed Sep 13, 2010 472  -> Bool -- True <=> quantify over this wanted  dimitris committed Nov 16, 2011 473 quantifyMe qtvs ct  simonpj@microsoft.com committed Sep 13, 2010 474  | isIPPred pred = True -- Note [Inheriting implicit parameters]  batterseapower committed Sep 06, 2011 475  | otherwise = tyVarsOfType pred intersectsVarSet qtvs  simonpj@microsoft.com committed Sep 13, 2010 476  where  dimitris committed Nov 29, 2011 477  pred = ctPred ct  simonpj@microsoft.com committed Sep 13, 2010 478 \end{code}  simonpj committed Jan 25, 2001 479   simonpj@microsoft.com committed Oct 08, 2010 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 Note [Avoid unecessary constraint simplification] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When inferring the type of a let-binding, with simplifyInfer, try to avoid unnecessariliy simplifying class constraints. Doing so aids sharing, but it also helps with delicate situations like instance C t => C [t] where .. f :: C [t] => .... f x = let g y = ...(constraint C [t])... in ... When inferring a type for 'g', we don't want to apply the instance decl, because then we can't satisfy (C t). So we just notice that g isn't quantified over 't' and partition the contraints before simplifying. This only half-works, but then let-generalisation only half-works.  simonpj@microsoft.com committed Nov 24, 2006 498 499 Note [Inheriting implicit parameters] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  simonpj committed May 03, 2001 500 501 502 Consider this: f x = (x::Int) + ?y  simonpj committed Jan 25, 2001 503   simonpj committed May 03, 2001 504 505 506 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:  simonpj committed Jan 25, 2001 507   simonpj committed May 03, 2001 508 509 510  f :: Int -> Int (so we get ?y from the context of f's definition), or  simonpj committed Jan 25, 2001 511 512 513  f :: (?y::Int) => Int -> Int  simonpj committed May 03, 2001 514 515 516 517 518 519 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.  simonpj committed Oct 25, 2001 520 521 BOTTOM LINE: when *inferring types* you *must* quantify over implicit parameters. See the predicate isFreeWhenInferring.  simonpj committed Jun 25, 2001 522   simonpj committed Oct 25, 2001 523   simonpj@microsoft.com committed Sep 13, 2010 524 525 526 527 528 ********************************************************************************* * * * RULES * * * ***********************************************************************************  simonpj committed May 12, 2004 529   simonpj@microsoft.com committed Sep 13, 2010 530 531 Note [Simplifying RULE lhs constraints] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  simonpj@microsoft.com committed Dec 13, 2010 532 On the LHS of transformation rules we only simplify only equalities,  simonpj@microsoft.com committed Sep 13, 2010 533 534 535 536 but not dictionaries. We want to keep dictionaries unsimplified, to serve as the available stuff for the RHS of the rule. We *do* want to simplify equalities, however, to detect ill-typed rules that cannot be applied.  simonpj committed May 12, 2004 537   simonpj@microsoft.com committed Sep 13, 2010 538 539 540 Implementation: the TcSFlags carried by the TcSMonad controls the amount of simplification, so simplifyRuleLhs just sets the flag appropriately.  simonpj committed May 18, 1999 541   simonpj@microsoft.com committed May 19, 2006 542 543 544 545 546 547 548 549 550 551 Example. Consider the following left-hand side of a rule f (x == y) (y > z) = ... If we typecheck this expression we get constraints d1 :: Ord a, d2 :: Eq a We do NOT want to "simplify" to the LHS forall x::a, y::a, z::a, d1::Ord a. f ((==) (eqFromOrd d1) x y) ((>) d1 y z) = ... Instead we want forall x::a, y::a, z::a, d1::Ord a, d2::Eq a. f ((==) d2 x y) ((>) d1 y z) = ...  simonpj committed Jun 28, 1999 552   simonpj@microsoft.com committed May 19, 2006 553 Here is another example:  simonpj committed Feb 28, 2001 554 555  fromIntegral :: (Integral a, Num b) => a -> b {-# RULES "foo" fromIntegral = id :: Int -> Int #-}  simonpj@microsoft.com committed May 19, 2006 556 557 In the rule, a=b=Int, and Num Int is a superclass of Integral Int. But we *dont* want to get  simonpj committed Feb 28, 2001 558  forall dIntegralInt.  simonpj@microsoft.com committed May 19, 2006 559  fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int  simonpj committed Mar 09, 2005 560 because the scsel will mess up RULE matching. Instead we want  simonpj committed Feb 28, 2001 561  forall dIntegralInt, dNumInt.  simonpj@microsoft.com committed May 19, 2006 562  fromIntegral Int Int dIntegralInt dNumInt = id Int  simonpj committed Feb 28, 2001 563   simonpj@microsoft.com committed May 19, 2006 564 565 566 567 568 569 570 Even if we have g (x == y) (y == z) = .. where the two dictionaries are *identical*, we do NOT WANT forall x::a, y::a, z::a, d1::Eq a f ((==) d1 x y) ((>) d1 y z) = ... because that will only match if the dict args are (visibly) equal. Instead we want to quantify over the dictionaries separately.  simonpj committed May 18, 1999 571   simonpj@microsoft.com committed Sep 13, 2010 572 573 In short, simplifyRuleLhs must *only* squash equalities, leaving all dicts unchanged, with absolutely no sharing.  lewie committed Mar 02, 2000 574   simonpj@microsoft.com committed Sep 13, 2010 575 576 577 578 579 HOWEVER, under a nested implication things are different Consider f :: (forall a. Eq a => a->a) -> Bool -> ... {-# RULES "foo" forall (v::forall b. Eq b => b->b). f b True = ...  Simon Peyton Jones committed Jan 12, 2012 580  #-}  simonpj@microsoft.com committed Sep 13, 2010 581 582 583 Here we *must* solve the wanted (Eq a) from the given (Eq a) resulting from skolemising the agument type of g. So we revert to SimplCheck when going under an implication.  simonpj committed Sep 13, 2002 584 585  \begin{code}  simonpj@microsoft.com committed Sep 13, 2010 586 587 588 589 590 591 592 593 594 simplifyRule :: RuleName -> [TcTyVar] -- Explicit skolems -> WantedConstraints -- Constraints from LHS -> WantedConstraints -- Constraints from RHS -> TcM ([EvVar], -- LHS dicts TcEvBinds, -- Evidence for LHS TcEvBinds) -- Evidence for RHS -- See Note [Simplifying RULE lhs constraints] simplifyRule name tv_bndrs lhs_wanted rhs_wanted  simonpj@microsoft.com committed Jan 12, 2011 595 596 597 598 599 600 601  = do { loc <- getCtLoc (RuleSkol name) ; zonked_lhs <- zonkWC lhs_wanted ; let untch = NoUntouchables -- We allow ourselves to unify environment -- variables; hence *no untouchables* ; (lhs_results, lhs_binds)  Simon Peyton Jones committed Jan 12, 2012 602 603  <- runTcS (SimplRuleLhs name) untch emptyInert emptyWorkList$ solveWanteds zonked_lhs  simonpj@microsoft.com committed Jan 12, 2011 604 605 606 607 608 609 610  ; traceTc "simplifyRule" $vcat [ text "zonked_lhs" <+> ppr zonked_lhs , text "lhs_results" <+> ppr lhs_results , text "lhs_binds" <+> ppr lhs_binds , text "rhs_wanted" <+> ppr rhs_wanted ]  simonpj@microsoft.com committed Sep 13, 2010 611 612  -- Don't quantify over equalities (judgement call here)  dimitris committed Nov 29, 2011 613  ; let (eqs, dicts) = partitionBag (isEqPred . ctPred)  simonpj@microsoft.com committed Jan 12, 2011 614  (wc_flat lhs_results)  dimitris committed Nov 16, 2011 615  lhs_dicts = map cc_id (bagToList dicts)  simonpj@microsoft.com committed Jan 12, 2011 616 617 618 619 620 621  -- Dicts and implicit parameters -- Fail if we have not got down to unsolved flats ; ev_binds_var <- newTcEvBinds ; emitImplication$ Implic { ic_untch = untch , ic_env = emptyNameEnv  Simon Peyton Jones committed Jan 12, 2012 622  , ic_skols = tv_bndrs  simonpj@microsoft.com committed Jan 12, 2011 623 624 625 626 627  , ic_given = lhs_dicts , ic_wanted = lhs_results { wc_flat = eqs } , ic_insol = insolubleWC lhs_results , ic_binds = ev_binds_var , ic_loc = loc }  simonpj@microsoft.com committed Sep 13, 2010 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643  -- Notice that we simplify the RHS with only the explicitly -- introduced skolems, allowing the RHS to constrain any -- unification variables. -- Then, and only then, we call zonkQuantifiedTypeVariables -- Example foo :: Ord a => a -> a -- foo_spec :: Int -> Int -- {-# RULE "foo" foo = foo_spec #-} -- Here, it's the RHS that fixes the type variable -- So we don't want to make untouchable the type -- variables in the envt of the RHS, because they include -- the template variables of the RULE -- Hence the rather painful ad-hoc treatement here ; rhs_binds_var@(EvBindsVar evb_ref _) <- newTcEvBinds  simonpj committed Apr 19, 2011 644 645  ; let doc = ptext (sLit "rhs of rule") <+> doubleQuotes (ftext name) ; rhs_binds1 <- simplifyCheck (SimplCheck doc) $ simonpj@microsoft.com committed Jan 12, 2011 646 647 648 649 650  WC { wc_flat = emptyBag , wc_insol = emptyBag , wc_impl = unitBag$ Implic { ic_untch = NoUntouchables , ic_env = emptyNameEnv  Simon Peyton Jones committed Jan 12, 2012 651  , ic_skols = tv_bndrs  simonpj@microsoft.com committed Jan 12, 2011 652 653 654 655 656  , ic_given = lhs_dicts , ic_wanted = rhs_wanted , ic_insol = insolubleWC rhs_wanted , ic_binds = rhs_binds_var , ic_loc = loc } }  simonpj@microsoft.com committed Sep 13, 2010 657 658 659 660 661  ; rhs_binds2 <- readTcRef evb_ref ; return ( lhs_dicts , EvBinds lhs_binds , EvBinds (rhs_binds1 unionBags evBindMapBinds rhs_binds2)) }  simonpj committed Sep 13, 2002 662 663 664 \end{code}  simonpj@microsoft.com committed Sep 13, 2010 665 666 667 668 669 ********************************************************************************* * * * Main Simplifier * * * ***********************************************************************************  lewie committed Mar 02, 2000 670 671  \begin{code}  simonpj@microsoft.com committed Sep 13, 2010 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 simplifyCheck :: SimplContext -> WantedConstraints -- Wanted -> TcM (Bag EvBind) -- Solve a single, top-level implication constraint -- e.g. typically one created from a top-level type signature -- f :: forall a. [a] -> [a] -- f x = rhs -- We do this even if the function has no polymorphism: -- g :: Int -> Int -- g y = rhs -- (whereas for *nested* bindings we would not create -- an implication constraint for g at all.) -- -- Fails if can't solve something in the input wanteds simplifyCheck ctxt wanteds  simonpj@microsoft.com committed Jan 12, 2011 688  = do { wanteds <- zonkWC wanteds  simonpj@microsoft.com committed Sep 13, 2010 689 690 691 692  ; traceTc "simplifyCheck {" (vcat [ ptext (sLit "wanted =") <+> ppr wanteds ])  Simon Peyton Jones committed Jan 12, 2012 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712  ; (unsolved, eb1) <- runTcS ctxt NoUntouchables emptyInert emptyWorkList $solveWanteds wanteds ; traceTc "simplifyCheck }"$ ptext (sLit "unsolved =") <+> ppr unsolved -- See Note [Deferring coercion errors to runtime] ; runtimeCoercionErrors <- doptM Opt_DeferTypeErrors ; eb2 <- reportUnsolved runtimeCoercionErrors unsolved ; 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  simonpj@microsoft.com committed Sep 13, 2010 713   Simon Peyton Jones committed Jan 12, 2012 714 715  a :: Int a = 'a'  simonpj@microsoft.com committed Sep 13, 2010 716   Simon Peyton Jones committed Jan 12, 2012 717  main = print "b"  simonpj@microsoft.com committed Sep 13, 2010 718   Simon Peyton Jones committed Jan 12, 2012 719 720 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.  simonpj@microsoft.com committed Sep 13, 2010 721   Simon Peyton Jones committed Jan 12, 2012 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 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  dimitris committed Nov 16, 2011 746 747 -- Returns: residual constraints, plus evidence bindings -- NB: When we are called from TcM there are no inerts to pass down to TcS  Simon Peyton Jones committed Jan 12, 2012 748 749 solveWanteds wanted = do { wc_out <- solve_wanteds wanted  dimitris committed Nov 16, 2011 750 751  ; let wc_ret = wc_out { wc_flat = keepWanted (wc_flat wc_out) } -- Discard Derived  Simon Peyton Jones committed Jan 12, 2012 752  ; return wc_ret }  dimitris committed Nov 16, 2011 753 754 755 756  solve_wanteds :: WantedConstraints -> TcS WantedConstraints -- NB: wc_flats may be wanted *or* derived now solve_wanteds wanted@(WC { wc_flat = flats, wc_impl = implics, wc_insol = insols })  simonpj@microsoft.com committed Jan 12, 2011 757 758 759  = do { traceTcS "solveWanteds {" (ppr wanted) -- Try the flat bit  simonpj@microsoft.com committed Jan 13, 2011 760 761 762 763 764  -- 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!  dimitris committed Nov 16, 2011 765   simonpj@microsoft.com committed Jan 12, 2011 766  ; let all_flats = flats unionBags keepWanted insols  dimitris committed Nov 16, 2011 767  ; solveInteractCts $bagToList all_flats  simonpj@microsoft.com committed Jan 12, 2011 768   dimitris committed Nov 16, 2011 769 770 771  -- solve_wanteds iterates when it is able to float equalities -- out of one or more of the implications. ; unsolved_implics <- simpl_loop 1 implics  simonpj@microsoft.com committed Jan 12, 2011 772   dimitris committed Nov 16, 2011 773 774 775  ; (insoluble_flats,unsolved_flats) <- extractUnsolvedTcS ; bb <- getTcEvBindsMap  simonpj@microsoft.com committed Nov 12, 2010 776  ; tb <- getTcSTyBindsMap  dimitris committed Nov 16, 2011 777   simonpj@microsoft.com committed Sep 13, 2010 778  ; traceTcS "solveWanteds }"$  simonpj@microsoft.com committed Nov 12, 2010 779  vcat [ text "unsolved_flats =" <+> ppr unsolved_flats  simonpj@microsoft.com committed Jan 12, 2011 780  , text "unsolved_implics =" <+> ppr unsolved_implics  dimitris committed Nov 16, 2011 781  , text "current evbinds =" <+> ppr (evBindMapBinds bb)  simonpj@microsoft.com committed Nov 12, 2010 782 783 784  , text "current tybinds =" <+> vcat (map ppr (varEnvElts tb)) ]  dimitris committed Nov 16, 2011 785  ; (subst, remaining_unsolved_flats) <- solveCTyFunEqs unsolved_flats  simonpj@microsoft.com committed Nov 12, 2010 786  -- See Note [Solving Family Equations]  simonpj@microsoft.com committed Jan 12, 2011 787 788  -- NB: remaining_flats has already had subst applied  dimitris committed Nov 16, 2011 789 790 791 792 793 794 795 796 797 798 799 800 801 802  ; return $WC { wc_flat = mapBag (substCt subst) remaining_unsolved_flats , wc_impl = mapBag (substImplication subst) unsolved_implics , wc_insol = mapBag (substCt subst) insoluble_flats } } 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  simonpj@microsoft.com committed Jan 12, 2011 803   dimitris committed Nov 16, 2011 804 805  ; inerts <- getTcSInerts ; let ((_,unsolved_flats),_) = extractUnsolved inerts  simonpj@microsoft.com committed Jan 12, 2011 806   dimitris committed Nov 16, 2011 807 808 809  ; ecache_pre <- getTcSEvVarCacheMap ; let pr = ppr ((\k z m -> foldTM k m z) (:) [] ecache_pre) ; traceTcS "ecache_pre"$ pr  dimitris committed May 17, 2011 810   dimitris committed Nov 16, 2011 811 812 813  ; improve_eqs <- if not (isEmptyBag implic_eqs) then return implic_eqs else applyDefaultingRules unsolved_flats  simonpj@microsoft.com committed Jan 12, 2011 814   dimitris committed Nov 16, 2011 815 816 817  ; ecache_post <- getTcSEvVarCacheMap ; let po = ppr ((\k z m -> foldTM k m z) (:) [] ecache_post) ; traceTcS "ecache_po" $po  dimitris committed May 17, 2011 818   dimitris committed Nov 16, 2011 819 820 821 822  ; traceTcS "solveWanteds: simpl_loop end"$ vcat [ text "improve_eqs =" <+> ppr improve_eqs , text "unsolved_flats =" <+> ppr unsolved_flats , text "unsolved_implics =" <+> ppr unsolved_implics ]  823   dimitris committed Nov 16, 2011 824 825 826  ; if isEmptyBag improve_eqs then return unsolved_implics else do { solveInteractCts $bagToList improve_eqs ; simpl_loop (n+1) unsolved_implics } }  827   dimitris committed Nov 16, 2011 828 829 830 831 832 833 834 835 836 837 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 ; let ((_insoluble_flats, unsolved_flats),thinner_inerts) = extractUnsolved inerts  838   dimitris committed Nov 16, 2011 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854  ; (implic_eqs, unsolved_implics) <- doWithInert thinner_inerts$ do { let pushed_givens = givens_from_wanteds unsolved_flats tcs_untouchables = filterVarSet isFlexiTcsTv $tyVarsOfCts unsolved_flats -- 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] ; solveInteractCts pushed_givens ; 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.  855 856 857 858 859 860  ; traceTcS "solveWanteds: done nested implications }" $vcat [ text "implic_eqs =" <+> ppr implic_eqs , text "unsolved_implics =" <+> ppr unsolved_implics ] ; return (implic_eqs, unsolved_implics) }  dimitris committed Nov 16, 2011 861 862 863 864 865 866 867 868 869 870  where givens_from_wanteds = foldrBag get_wanted [] get_wanted cc rest_givens | pushable_wanted cc = let this_given = cc { cc_flavor = mkGivenFlavor (cc_flavor cc) UnkSkol } in this_given : rest_givens | otherwise = rest_givens pushable_wanted :: Ct -> Bool pushable_wanted cc | isWantedCt cc  dimitris committed Nov 29, 2011 871  = isEqPred (ctPred cc) -- see Note [Preparing inert set for implications]  dimitris committed Nov 16, 2011 872 873 874 875 876 877 878 879 880 881  | 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  simonpj@microsoft.com committed Oct 06, 2010 882 883 884  , ic_binds = ev_binds , ic_skols = skols , ic_given = givens  simonpj@microsoft.com committed Sep 13, 2010 885  , ic_wanted = wanteds  simonpj@microsoft.com committed Oct 06, 2010 886  , ic_loc = loc })  887  = nestImplicTcS ev_binds (untch, tcs_untouchables)$  simonpj@microsoft.com committed Oct 19, 2010 888 889  recoverTcS (return (emptyBag, emptyBag)) $-- Recover from nested failures. Even the top level is  dimitris committed Nov 16, 2011 890  -- just a bunch of implications, so failing at the first one is bad  simonpj@microsoft.com committed Sep 13, 2010 891 892 893  do { traceTcS "solveImplication {" (ppr imp) -- Solve flat givens  dimitris committed Nov 16, 2011 894  ; solveInteractGiven loc givens  simonpj@microsoft.com committed Sep 13, 2010 895 896  -- Simplify the wanteds  dimitris committed Nov 16, 2011 897 898 899  ; WC { wc_flat = unsolved_flats , wc_impl = unsolved_implics , wc_insol = insols } <- solve_wanteds wanteds  simonpj@microsoft.com committed Jan 12, 2011 900 901 902 903  ; let (res_flat_free, res_flat_bound) = floatEqualities skols givens unsolved_flats final_flat = keepWanted res_flat_bound  simonpj@microsoft.com committed Sep 13, 2010 904   dimitris committed Nov 16, 2011 905 906  ; let res_wanted = WC { wc_flat = final_flat , wc_impl = unsolved_implics  simonpj@microsoft.com committed Jan 12, 2011 907  , wc_insol = insols }  dimitris committed Nov 16, 2011 908   simonpj@microsoft.com committed Jan 12, 2011 909 910 911  res_implic = unitImplication$ imp { ic_wanted = res_wanted , ic_insol = insolubleWC res_wanted }  simonpj@microsoft.com committed Sep 13, 2010 912   dimitris committed Nov 16, 2011 913 914  ; evbinds <- getTcEvBindsMap  simonpj@microsoft.com committed Sep 13, 2010 915 916  ; traceTcS "solveImplication end }" \$ vcat [ text "res_flat_free =" <+> ppr res_flat_free  dimitris committed Nov 16, 2011 917  , text "implication evbinds = " <+> ppr (evBindMapBinds evbinds)  simonpj@microsoft.com committed Jan 12, 2011 918  , text "res_implic =" <+> ppr res_implic ]  simonpj@microsoft.com committed Sep 13, 2010 919   simonpj@microsoft.com committed Jan 12, 2011 920  ; return (res_flat_free, res_implic) }  dimitris committed Nov 16, 2011 921  -- and we are back to the original inerts  simonpj@microsoft.com committed Sep 13, 2010 922 923   Simon Peyton Jones committed Jan 12, 2012 924 floatEqualities :: [TcTyVar] -> [EvVar] -> Cts -> (Cts, Cts)  simonpj@microsoft.com committed Jan 12, 2011 925 926 927 928 -- 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)  simonpj@microsoft.com committed Nov 12, 2010 929  -- Note [Float Equalities out of Implications]  simonpj@microsoft.com committed Jan 12, 2011 930 931  | otherwise = partitionBag is_floatable wantders  Simon Peyton Jones committed Jan 12, 2012 932 933  where skol_set = mkVarSet skols is_floatable :: Ct -> Bool  dimitris committed Nov 16, 2011 934  is_floatable ct  dimitris committed Nov 29, 2011 935  | ct_predty <- ctPred ct  dimitris committed Nov 16, 2011 936  , isEqPred ct_predty  Simon Peyton Jones committed Jan 12, 2012 937  = skol_set disjointVarSet tvs_under_fsks ct_predty  dimitris committed Nov 16, 2011 938  is_floatable _ct = False  simonpj@microsoft.com committed Nov 12, 2010 939 940 941 942 943 944 945 946 947 948 949  tvs_under_fsks :: Type -> TyVarSet -- ^ NB: for type synonyms tvs_under_fsks does /not/ expand the synonym tvs_under_fsks (TyVarTy tv) | not (isTcTyVar tv) = unitVarSet tv | FlatSkol ty <- tcTyVarDetails tv = tvs_under_fsks ty | otherwise = unitVarSet tv tvs_under_fsks (TyConApp _ tys) = unionVarSets (map tvs_under_fsks tys) tvs_under_fsks (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  dimitris committed Nov 16, 2011 950  -- can mention type variables!  simonpj@microsoft.com committed Nov 12, 2010 951 952 953 954 955  | 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  lewie committed Mar 02, 2000 956 \end{code}  partain committed Jan 08, 1996 957   simonpj@microsoft.com committed Sep 13, 2010 958 959 960 961 Note [Preparing inert set for implications] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Before solving the nested implications, we convert any unsolved flat wanteds to givens, and add them to the inert set. Reasons:  962 963  a) In checking mode, suppresses unnecessary errors. We already have  simonpj@microsoft.com committed Sep 13, 2010 964  on unsolved-wanted error; adding it to the givens prevents any  simonpj@microsoft.com committed Feb 11, 2011 965  consequential errors from showing up  966   simonpj@microsoft.com committed Sep 13, 2010 967 968 969 970  b) More importantly, in inference mode, we are going to quantify over this constraint, and we *don't* want to quantify over any constraints that are deducible from it.  simonpj@microsoft.com committed Feb 11, 2011 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993  c) Flattened type-family equalities must be exposed to the nested constraints. Consider F b ~ alpha, (forall c. F b ~ alpha) Obviously this is soluble with [alpha := F b]. But the unification is only done by solveCTyFunEqs, right at the end of solveWanteds, and if we aren't careful we'll end up with an unsolved goal inside the implication. We need to "push" the as-yes-unsolved (F b ~ alpha) inwards, as a *given*, so that it can be used to solve the inner (F b ~ alpha). See Trac #4935. d) There are other cases where interactions between wanteds that can help to solve a constraint. For example class C a b | a -> b (C Int alpha), (forall d. C d blah => C Int a) If we push the (C Int alpha) inwards, as a given, it can produce a fundep (alpha~a) and this can float out again and be used to fix alpha. (In general we can't float class constraints out just in case (C d blah) might help to solve (C Int a).)  simonpj@microsoft.com committed Sep 13, 2010 994 995 996 997 998 999 1000 1001 The unsolved wanteds are *canonical* but they may not be *inert*, because when made into a given they might interact with other givens. Hence the call to solveInteract. Example: Original inert set = (d :_g D a) /\ (co :_w a ~ [beta]) We were not able to solve (a ~w [beta]) but we can't just assume it as given because the resulting set is not inert. Hence we have to do a  1002 1003 'solveInteract' step first.  dimitris committed May 17, 2011 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 Finally, note that we convert them to [Given] and NOT [Given/Solved]. The reason is that Given/Solved are weaker than Givens and may be discarded. As an example consider the inference case, where we may have, the following original constraints: [Wanted] F Int ~ Int (F Int ~ a => F Int ~ a) If we convert F Int ~ Int to [Given/Solved] instead of Given, then the next given (F Int ~ a) is going to cause the Given/Solved to be ignored, casting the (F Int ~ a) insoluble. Hence we should really convert the residual wanteds to plain old Given. We need only push in unsolved equalities both in checking mode and inference mode: (1) In checking mode we should not push given dictionaries in because of example LongWayOverlapping.hs, where we might get strange overlap errors between far-away constraints in the program. But even in checking mode, we must still push type family equations. Consider: type instance F True a b = a type instance F False a b = b [w] F c a b ~ gamma (c ~ True) => a ~ gamma (c ~ False) => b ~ gamma Since solveCTyFunEqs happens at the very end of solving, the only way to solve the two implications is temporarily consider (F c a b ~ gamma) as Given (NB: not merely Given/Solved because it has to interact with the top-level instance environment) and push it inside the implications. Now, when we come out again at the end, having solved the implications solveCTyFunEqs will solve this equality. (2) In inference mode, we recheck the final constraint in checking mode and hence we will be able to solve inner implications from top-level quantified constraints nonetheless.  1040 1041 Note [Extra TcsTv untouchables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  simonpj@microsoft.com committed Feb 11, 2011 1042 1043 1044 1045 1046 Furthemore, we record the inert set simplifier-generated unification variables of the TcsTv kind (such as variables from instance that have been applied, or unification flattens). These variables must be passed to the implications as extra untouchable variables. Otherwise we have the danger of double unifications. Example (from trac ticket #4494):  1047 1048 1049  (F Int ~ uf) /\ (forall a. C a => F Int ~ beta)  simonpj@microsoft.com committed Feb 11, 2011 1050 1051 1052 In this example, beta is touchable inside the implication. The first solveInteract step leaves 'uf' ununified. Then we move inside the implication where a new constraint  1053  uf ~ beta ` simonpj@microsoft.com committed Feb 11, 2011 1054 1055 1056 1057 1058 1059