TcSimplify.lhs 65.6 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 Peyton Jones committed Jun 13, 2012 25 import Type ( classifyPredType, PredTree(..), isIPPred_maybe )  Simon Marlow committed Oct 11, 2006 26 import Var  dimitris committed Jun 08, 2012 27 import Unique  simonm committed Dec 02, 1998 28 import VarSet  simonpj@microsoft.com committed Nov 12, 2010 29 import VarEnv  Simon Peyton Jones committed Dec 05, 2011 30 import TcEvidence  simonpj@microsoft.com committed Nov 12, 2010 31 import TypeRep  simonpj@microsoft.com committed Sep 13, 2010 32 import Name  simonmar committed Dec 10, 2003 33 import Bag  Simon Marlow committed Oct 11, 2006 34 35 import ListSetOps import Util  simonpj@microsoft.com committed Sep 13, 2010 36 37 38 import PrelInfo import PrelNames import Class ( classKey )  Simon Peyton Jones committed Aug 16, 2011 39 import BasicTypes ( RuleName )  simonpj@microsoft.com committed Jan 12, 2011 40 import Control.Monad ( when )  simonpj@microsoft.com committed Sep 13, 2010 41 import Outputable  Ian Lynagh committed Mar 29, 2008 42 import FastString  dimitris committed Mar 28, 2012 43 import TrieMap () -- DV: for now  Simon Peyton Jones committed Jan 12, 2012 44 import DynFlags  Simon Peyton Jones committed Jun 13, 2012 45 import Data.Maybe ( mapMaybe )  partain committed Jan 08, 1996 46 47 48 \end{code}  simonpj@microsoft.com committed Sep 13, 2010 49 50 51 52 53 ********************************************************************************* * * * External interface * * * *********************************************************************************  simonpj committed Jan 25, 2001 54   dimitris committed Jun 08, 2012 55   simonpj@microsoft.com committed Sep 13, 2010 56 \begin{code}  dimitris committed Jun 08, 2012 57 58   simonpj@microsoft.com committed Sep 13, 2010 59 60 simplifyTop :: WantedConstraints -> TcM (Bag EvBind) -- Simplify top-level constraints  simonpj@microsoft.com committed Dec 13, 2010 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  simonpj@microsoft.com committed Sep 13, 2010 64 simplifyTop wanteds  dimitris committed Jun 08, 2012 65 66 67  = do { ev_binds_var <- newTcEvBinds ; zonked_wanteds <- zonkWC wanteds  dimitris committed Jul 19, 2012 68  ; wc_first_go <- solveWantedsWithEvBinds ev_binds_var zonked_wanteds  dimitris committed Jun 08, 2012 69 70 71 72 73 74 75 76 77 78 79 80 81  ; 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  dimitris committed Jul 19, 2012 82  = do { wc_residual <- solveWantedsWithEvBinds ev_binds_var wc  dimitris committed Jun 08, 2012 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  ; 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}  simonpj@microsoft.com committed Sep 13, 2010 146   Simon Peyton Jones committed Aug 16, 2011 147 148 149 ------------------ simplifyAmbiguityCheck :: Name -> WantedConstraints -> TcM (Bag EvBind) simplifyAmbiguityCheck name wanteds  dimitris committed Jun 08, 2012 150  = traceTc "simplifyAmbiguityCheck" (text "name =" <+> ppr name) >>  151 152 153  simplifyTop wanteds -- NB: must be simplifyTop not simplifyCheck, so that we -- do ambiguity resolution. -- See Note [Impedence matching] in TcBinds.  dimitris committed Nov 16, 2011 154   simonpj@microsoft.com committed Sep 13, 2010 155 156 157 ------------------ simplifyInteractive :: WantedConstraints -> TcM (Bag EvBind) simplifyInteractive wanteds  dimitris committed Jun 08, 2012 158 159  = traceTc "simplifyInteractive" empty >> simplifyTop wanteds  simonpj@microsoft.com committed Sep 13, 2010 160 161 162 163 164  ------------------ simplifyDefault :: ThetaType -- Wanted; has no type variables in it -> TcM () -- Succeeds iff the constraint is soluble simplifyDefault theta  dimitris committed Jun 08, 2012 165 166 167  = do { traceTc "simplifyInteractive" empty ; wanted <- newFlatWanteds DefaultOrigin theta ; _ignored_ev_binds <- simplifyCheck (mkFlatWC wanted)  simonpj@microsoft.com committed Sep 13, 2010 168 169  ; return () } \end{code}  simonpj committed Jan 25, 2001 170   simonpj committed May 03, 2001 171   dimitris committed Nov 16, 2011 172 ***********************************************************************************  simonpj@microsoft.com committed Sep 13, 2010 173 * *  dimitris committed Nov 16, 2011 174 * Deriving *  simonpj@microsoft.com committed Sep 13, 2010 175 176 * * ***********************************************************************************  simonpj committed May 03, 2001 177   simonpj@microsoft.com committed Sep 13, 2010 178 179 \begin{code} simplifyDeriv :: CtOrigin  simonpj committed Apr 19, 2011 180 181 182 183  -> PredType -> [TyVar] -> ThetaType -- Wanted -> TcM ThetaType -- Needed  simonpj@microsoft.com committed Sep 13, 2010 184 185 -- Given instance (wanted) => C inst_ty -- Simplify 'wanted' as much as possibles  simonpj@microsoft.com committed Jan 12, 2011 186 -- Fail if not possible  simonpj committed Apr 19, 2011 187 simplifyDeriv orig pred tvs theta  Simon Peyton Jones committed Mar 02, 2012 188  = do { (skol_subst, tvs_skols) <- tcInstSkolTyVars tvs -- Skolemize  simonpj@microsoft.com committed Feb 17, 2011 189 190 191 192  -- 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 193   Simon Peyton Jones committed Mar 02, 2012 194  ; let subst_skol = zipTopTvSubst tvs_skols$ map mkTyVarTy tvs  Simon Peyton Jones committed Jul 23, 2011 195  skol_set = mkVarSet tvs_skols  dimitris committed Jun 08, 2012 196  doc = ptext (sLit "deriving") <+> parens (ppr pred)  simonpj@microsoft.com committed Jan 12, 2011 197 198 199  ; wanted <- newFlatWanteds orig (substTheta skol_subst theta)  dimitris committed Jun 08, 2012 200 201  ; traceTc "simplifyDeriv" $vcat [ pprTvBndrs tvs $$ppr theta$$ ppr wanted, doc ]  Simon Peyton Jones committed Jan 12, 2012 202  ; (residual_wanted, _ev_binds1)  dimitris committed Jul 19, 2012 203  <- solveWanteds (mkFlatWC wanted)  simonpj@microsoft.com committed Sep 13, 2010 204   simonpj@microsoft.com committed Jan 12, 2011 205 206  ; let (good, bad) = partitionBagWith get_good (wc_flat residual_wanted) -- See Note [Exotic derived instance contexts]  dimitris committed Nov 16, 2011 207  get_good :: Ct -> Either PredType Ct  dimitris committed Jul 19, 2012 208 209 210 211 212 213  get_good ct | validDerivPred skol_set p , isWantedCt ct = Left p -- NB: residual_wanted may contain unsolved -- Derived and we stick them into the bad set -- so that reportUnsolved may decide what to do with them | otherwise = Right ct  dimitris committed Nov 29, 2011 214  where p = ctPred ct  simonpj@microsoft.com committed Sep 13, 2010 215   Simon Peyton Jones committed Jan 12, 2012 216 217 218  -- 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 219   simonpj@microsoft.com committed Jan 12, 2011 220 221  ; let min_theta = mkMinimalBySCs (bagToList good) ; return (substTheta subst_skol min_theta) }  simonpj@microsoft.com committed Sep 13, 2010 222 \end{code}  simonpj committed May 03, 2001 223   simonpj@microsoft.com committed Feb 17, 2011 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 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 249 250 251 252 253 254 255 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 256   simonpj@microsoft.com committed Sep 13, 2010 257 258 259 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 260   simonpj@microsoft.com committed Sep 13, 2010 261 262 Notice that this instance (just) satisfies the Paterson termination conditions. Then we *could* derive an instance decl like this:  simonpj committed Feb 10, 2004 263   simonpj@microsoft.com committed Sep 13, 2010 264 265 266 267  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 268   simonpj@microsoft.com committed Sep 13, 2010 269 270 271 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 272   simonpj@microsoft.com committed Sep 13, 2010 273 274 So for now we simply require that the derived instance context should have only type-variable constraints.  simonpj committed Feb 10, 2004 275   simonpj@microsoft.com committed Sep 13, 2010 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 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 305   dreixel committed Nov 11, 2011 306 307 308 309 310 311 312 313 314 315 316 317 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 318 \begin{code}  Simon Peyton Jones committed Aug 16, 2011 319 simplifyInfer :: Bool  simonpj@microsoft.com committed Jan 12, 2011 320 321 322  -> Bool -- Apply monomorphism restriction -> [(Name, TcTauType)] -- Variables to be generalised, -- and their tau-types  dimitris committed Jun 08, 2012 323  -> (Untouchables, WantedConstraints)  simonpj@microsoft.com committed Sep 13, 2010 324 325  -> TcM ([TcTyVar], -- Quantify over these type variables [EvVar], -- ... and these constraints  Simon Peyton Jones committed Aug 16, 2011 326 327 328  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 329  TcEvBinds) -- ... binding these evidence variables  dimitris committed Jun 08, 2012 330 simplifyInfer _top_lvl apply_mr name_taus (untch,wanteds)  simonpj@microsoft.com committed Jan 12, 2011 331 332 333  | isEmptyWC wanteds = do { gbl_tvs <- tcGetGlobalTyVars -- Already zonked ; zonked_taus <- zonkTcTypes (map snd name_taus)  Simon Peyton Jones committed Feb 16, 2012 334  ; let tvs_to_quantify = varSetElems (tyVarsOfTypes zonked_taus minusVarSet gbl_tvs)  dreixel committed Nov 11, 2011 335 336 337  -- 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 338  ; return (qtvs, [], False, emptyTcEvBinds) }  simonpj committed Feb 10, 2004 339   simonpj@microsoft.com committed Sep 13, 2010 340  | otherwise  Simon Peyton Jones committed Jun 21, 2012 341  = do { runtimeCoercionErrors <- doptM Opt_DeferTypeErrors  simonpj@microsoft.com committed Jan 12, 2011 342  ; gbl_tvs <- tcGetGlobalTyVars  Simon Peyton Jones committed Mar 02, 2012 343  ; zonked_tau_tvs <- zonkTyVarsAndFV (tyVarsOfTypes (map snd name_taus))  Simon Peyton Jones committed Jun 21, 2012 344  ; zonked_wanteds <- zonkWC wanteds  simonpj@microsoft.com committed Jan 12, 2011 345   simonpj@microsoft.com committed Sep 13, 2010 346  ; traceTc "simplifyInfer {"$ vcat  Simon Peyton Jones committed Aug 16, 2011 347  [ ptext (sLit "names =") <+> ppr (map fst name_taus)  Simon Peyton Jones committed Mar 02, 2012 348 349  , ptext (sLit "taus =") <+> ppr (map snd name_taus) , ptext (sLit "tau_tvs (zonked) =") <+> ppr zonked_tau_tvs  Simon Peyton Jones committed Aug 16, 2011 350 351 352  , ptext (sLit "gbl_tvs =") <+> ppr gbl_tvs , ptext (sLit "closed =") <+> ppr _top_lvl , ptext (sLit "apply_mr =") <+> ppr apply_mr  dimitris committed Jun 08, 2012 353  , ptext (sLit "untch =") <+> ppr untch  simonpj@microsoft.com committed Jan 12, 2011 354  , ptext (sLit "wanted =") <+> ppr zonked_wanteds  simonpj@microsoft.com committed Sep 13, 2010 355 356  ]  Simon Peyton Jones committed Jun 21, 2012 357 358 359 360 361  -- Historical note: Before step 2 we used to have a -- HORRIBLE HACK described in Note [Avoid unecessary -- constraint simplification] but, as described in Trac -- #4361, we have taken in out now. That's why we start -- with step 2!  simonpj@microsoft.com committed Jan 12, 2011 362   Simon Peyton Jones committed Jun 21, 2012 363 364 365 366 367 368 369 370  -- Step 2) First try full-blown solving -- NB: we must gather up all the bindings from doing -- this solving; hence (runTcSWithEvBinds ev_binds_var). -- And note that since there are nested implications, -- calling solveWanteds will side-effect their evidence -- bindings, so we can't just revert to the input -- constraint.  dimitris committed Jun 08, 2012 371  ; ev_binds_var <- newTcEvBinds  dimitris committed Jul 19, 2012 372  ; wanted_transformed <- solveWantedsWithEvBinds ev_binds_var zonked_wanteds  Simon Peyton Jones committed Jun 21, 2012 373 374  -- Step 3) Fail fast if there is an insoluble constraint,  dimitris committed Jun 08, 2012 375 376 377  -- unless we are deferring errors to runtime ; when (not runtimeCoercionErrors && insolubleWC wanted_transformed) $do { _ev_binds <- reportUnsolved False wanted_transformed; failM }  Simon Peyton Jones committed Jun 21, 2012 378 379  -- Step 4) Candidates for quantification are an approximation of wanted_transformed  dimitris committed Jun 08, 2012 380 381 382 383  ; 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]  dimitris committed Jul 19, 2012 384 385  -- NB: quant_candidates here are wanted or derived, we filter the wanteds later, anyway  Simon Peyton Jones committed Jun 21, 2012 386  -- Step 5) Minimize the quantification candidates  dimitris committed Jun 08, 2012 387  ; (quant_candidates_transformed, _extra_binds)  dimitris committed Jul 19, 2012 388 389 390  <- solveWanteds$ WC { wc_flat = quant_candidates , wc_impl = emptyBag , wc_insol = emptyBag }  Simon Peyton Jones committed Jun 21, 2012 391 392  -- Step 6) Final candidates for quantification  393 394  ; let final_quant_candidates :: [PredType] final_quant_candidates = map ctPred $bagToList$  dimitris committed Jun 08, 2012 395 396 397 398  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?  Simon Peyton Jones committed Mar 02, 2012 399  ; zonked_tau_tvs <- zonkTyVarsAndFV zonked_tau_tvs  dimitris committed Jun 08, 2012 400 401 402 403 404 405  ; 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 ]  406 407 408  ; let init_tvs = zonked_tau_tvs minusVarSet gbl_tvs poly_qtvs = growThetaTyVars final_quant_candidates init_tvs minusVarSet gbl_tvs  409  pbound = filter (quantifyPred poly_qtvs) final_quant_candidates  dimitris committed Jun 08, 2012 410 411  ; traceTc "simplifyWithApprox"$  412 413 414  vcat [ ptext (sLit "pbound =") <+> ppr pbound , ptext (sLit "init_qtvs =") <+> ppr init_tvs , ptext (sLit "poly_qtvs =") <+> ppr poly_qtvs ]  dimitris committed Jun 08, 2012 415   Simon Peyton Jones committed Aug 16, 2011 416  -- Monomorphism restriction  dimitris committed Jun 08, 2012 417  ; let mr_qtvs = init_tvs minusVarSet constrained_tvs  418 419  constrained_tvs = tyVarsOfTypes final_quant_candidates mr_bites = apply_mr && not (null pbound)  Simon Peyton Jones committed Aug 16, 2011 420   dimitris committed Jun 08, 2012 421  (qtvs, bound)  422  | mr_bites = (mr_qtvs, [])  dimitris committed Jun 08, 2012 423 424  | otherwise = (poly_qtvs, pbound)  simonpj@microsoft.com committed Jan 12, 2011 425   426  ; if isEmptyVarSet qtvs && null bound  Simon Peyton Jones committed Jul 14, 2012 427 428 429 430  then do { traceTc "} simplifyInfer/no quantification" empty ; emitConstraints wanted_transformed -- Includes insolubles (if -fdefer-type-errors) -- as well as flats and implications  dimitris committed Jun 08, 2012 431  ; return ([], [], mr_bites, TcEvBinds ev_binds_var) }  simonpj@microsoft.com committed Jan 12, 2011 432 433  else do  dimitris committed Jun 08, 2012 434 435 436  { traceTc "simplifyApprox" $ptext (sLit "bound are =") <+> ppr bound  simonpj@microsoft.com committed Jan 12, 2011 437  -- Step 4, zonk quantified variables  438  ; let minimal_flat_preds = mkMinimalBySCs bound  Simon Peyton Jones committed Aug 16, 2011 439 440  skol_info = InferSkol [ (name, mkSigmaTy [] minimal_flat_preds ty) | (name, ty) <- name_taus ]  simonpj@microsoft.com committed Jan 12, 2011 441 442 443 444  -- 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 committed Feb 16, 2012 445  ; qtvs_to_return <- zonkQuantifiedTyVars (varSetElems qtvs)  simonpj@microsoft.com committed Jan 12, 2011 446   Simon Peyton Jones committed Jun 21, 2012 447  -- Step 7) Emit an implication  simonpj@microsoft.com committed Jan 12, 2011 448 449  ; minimal_bound_ev_vars <- mapM TcMType.newEvVar minimal_flat_preds ; lcl_env <- getLclTypeEnv  dreixel committed Nov 11, 2011 450  ; gloc <- getCtLoc skol_info  dimitris committed Jun 08, 2012 451  ; let implic = Implic { ic_untch = untch  simonpj@microsoft.com committed Jan 12, 2011 452  , ic_env = lcl_env  Simon Peyton Jones committed Jan 12, 2012 453  , ic_skols = qtvs_to_return  simonpj@microsoft.com committed Jan 12, 2011 454  , ic_given = minimal_bound_ev_vars  dimitris committed Jun 08, 2012 455  , ic_wanted = wanted_transformed  simonpj@microsoft.com committed Jan 12, 2011 456 457 458 459  , ic_insol = False , ic_binds = ev_binds_var , ic_loc = gloc } ; emitImplication implic  dimitris committed Jun 08, 2012 460   simonpj@microsoft.com committed Jan 12, 2011 461 462 463  ; 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 464  , ptext (sLit "qtvs =") <+> ppr qtvs_to_return  dimitris committed Jun 08, 2012 465  , ptext (sLit "spb =") <+> ppr final_quant_candidates  simonpj@microsoft.com committed Jan 12, 2011 466 467  , ptext (sLit "bound =") <+> ppr bound ]  Simon Peyton Jones committed Aug 16, 2011 468 469  ; return ( qtvs_to_return, minimal_bound_ev_vars , mr_bites, TcEvBinds ev_binds_var) } }  dimitris committed Jun 08, 2012 470  where  simonpj@microsoft.com committed Jan 12, 2011 471 \end{code}  simonpj@microsoft.com committed Sep 13, 2010 472 473   474 475 Note [Default while Inferring] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  dimitris committed Jun 08, 2012 476 477 478 479 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 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.  simonpj@microsoft.com committed Jan 12, 2011 510 511 Note [Minimize by Superclasses] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  simonpj@microsoft.com committed Sep 13, 2010 512   simonpj@microsoft.com committed Jan 12, 2011 513 514 515 516 517 518 519 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 520   dimitris committed Jun 08, 2012 521 522 \begin{code} approximateWC :: WantedConstraints -> Cts  dimitris committed Jul 19, 2012 523 -- Postcondition: Wanted or Derived Cts  dimitris committed Jun 08, 2012 524 approximateWC wc = float_wc emptyVarSet wc  simonpj@microsoft.com committed Sep 13, 2010 525  where  dimitris committed Jun 08, 2012 526 527 528 529 530 531  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  simonpj@microsoft.com committed Jan 12, 2011 532  float_implic skols imp  dimitris committed Jun 08, 2012 533 534 535 536 537  = float_wc (skols extendVarSetList ic_skols imp) (ic_wanted imp) float_flat :: TcTyVarSet -> Ct -> Cts float_flat skols ct | tyVarsOfCt ct disjointVarSet skols  dimitris committed Jul 19, 2012 538  = singleCt ct  dimitris committed Jun 08, 2012 539 540 541 542  | otherwise = emptyCts do_bag :: (a -> Bag c) -> Bag a -> Bag c do_bag f = foldrBag (unionBags.f) emptyBag  simonpj@microsoft.com committed Sep 13, 2010 543 \end{code}  simonpj committed Jan 25, 2001 544   simonpj@microsoft.com committed Oct 08, 2010 545 546 Note [Avoid unecessary constraint simplification] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  Simon Peyton Jones committed Jun 21, 2012 547 548 549 550  -------- NB NB NB (Jun 12) ------------- This note not longer applies; see the notes with Trac #4361. But I'm leaving it in here so we remember the issue.) ----------------------------------------  simonpj@microsoft.com committed Oct 08, 2010 551 When inferring the type of a let-binding, with simplifyInfer,  Simon Peyton Jones committed Jun 21, 2012 552 try to avoid unnecessarily simplifying class constraints.  simonpj@microsoft.com committed Oct 08, 2010 553 554 Doing so aids sharing, but it also helps with delicate situations like  dimitris committed Jun 08, 2012 555   simonpj@microsoft.com committed Oct 08, 2010 556  instance C t => C [t] where ..  dimitris committed Jun 08, 2012 557   simonpj@microsoft.com committed Oct 08, 2010 558 559 560 561 562 563 564 565 566 567 568  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 Sep 13, 2010 569 570 571 572 573 ********************************************************************************* * * * RULES * * * ***********************************************************************************  simonpj committed May 12, 2004 574   Simon Peyton Jones committed Apr 16, 2012 575 See note [Simplifying RULE consraints] in TcRule  simonpj committed Jun 28, 1999 576   Simon Peyton Jones committed Apr 16, 2012 577 578 579 580 581 582 583 584 585 586 587 588 589 590 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.  simonpj committed Sep 13, 2002 591 592  \begin{code}  simonpj@microsoft.com committed Sep 13, 2010 593 594 595 simplifyRule :: RuleName -> WantedConstraints -- Constraints from LHS -> WantedConstraints -- Constraints from RHS  Simon Peyton Jones committed Apr 16, 2012 596 597 598 599 600  -> 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)  dimitris committed Jun 08, 2012 601   Simon Peyton Jones committed Apr 16, 2012 602  -- We allow ourselves to unify environment  dimitris committed Jun 08, 2012 603  -- variables: runTcS runs with NoUntouchables  dimitris committed Jul 19, 2012 604  ; (resid_wanted, _) <- solveWanteds zonked_all  Simon Peyton Jones committed Apr 16, 2012 605   simonpj@microsoft.com committed Jan 12, 2011 606 607  ; zonked_lhs <- zonkWC lhs_wanted  Simon Peyton Jones committed Apr 16, 2012 608 609 610 611 612 613 614 615 616 617 618 619 620  ; 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  simonpj@microsoft.com committed Jan 12, 2011 621  ; traceTc "simplifyRule" $ dimitris committed Jun 08, 2012 622 623  vcat [ doc , text "zonked_lhs" <+> ppr zonked_lhs  Simon Peyton Jones committed Apr 16, 2012 624 625  , text "q_cts" <+> ppr q_cts ]  Simon Peyton Jones committed May 07, 2012 626 627  ; return ( map (ctEvId . ctEvidence) (bagToList q_cts) , zonked_lhs { wc_flat = non_q_cts }) }  simonpj committed Sep 13, 2002 628 629 630 \end{code}  simonpj@microsoft.com committed Sep 13, 2010 631 632 633 634 635 ********************************************************************************* * * * Main Simplifier * * * ***********************************************************************************  lewie committed Mar 02, 2000 636 637  \begin{code}  dimitris committed Jun 08, 2012 638 simplifyCheck :: WantedConstraints -- Wanted  simonpj@microsoft.com committed Sep 13, 2010 639 640 641 642 643 644 645 646 647 648 649 650 651  -> 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  dimitris committed Jun 08, 2012 652 simplifyCheck wanteds  simonpj@microsoft.com committed Jan 12, 2011 653  = do { wanteds <- zonkWC wanteds  simonpj@microsoft.com committed Sep 13, 2010 654 655 656 657  ; traceTc "simplifyCheck {" (vcat [ ptext (sLit "wanted =") <+> ppr wanteds ])  dimitris committed Jul 19, 2012 658  ; (unsolved, eb1) <- solveWanteds wanteds  Simon Peyton Jones committed Jan 12, 2012 659 660 661  ; traceTc "simplifyCheck }"$ ptext (sLit "unsolved =") <+> ppr unsolved  dimitris committed Mar 30, 2012 662  ; traceTc "reportUnsolved {" empty  Simon Peyton Jones committed Jan 12, 2012 663 664 665  -- See Note [Deferring coercion errors to runtime] ; runtimeCoercionErrors <- doptM Opt_DeferTypeErrors ; eb2 <- reportUnsolved runtimeCoercionErrors unsolved  dimitris committed Mar 30, 2012 666 667  ; traceTc "reportUnsolved }" empty  Simon Peyton Jones committed Jan 12, 2012 668 669 670 671 672 673 674 675 676 677  ; 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 678   Simon Peyton Jones committed Jan 12, 2012 679 680  a :: Int a = 'a'  simonpj@microsoft.com committed Sep 13, 2010 681   Simon Peyton Jones committed Jan 12, 2012 682  main = print "b"  simonpj@microsoft.com committed Sep 13, 2010 683   Simon Peyton Jones committed Jan 12, 2012 684 685 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 686   Simon Peyton Jones committed Jan 12, 2012 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 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}  dimitris committed Jul 19, 2012 710 711 712 713 714 715 716 717 718 719 720 721 722  solveWanteds :: WantedConstraints -> TcM (WantedConstraints, Bag EvBind) -- Return the evidence binds in the BagEvBinds result solveWanteds wanted = runTcS $solve_wanteds wanted solveWantedsWithEvBinds :: EvBindsVar -> WantedConstraints -> TcM WantedConstraints -- Side-effect the EvBindsVar argument to add new bindings from solving solveWantedsWithEvBinds ev_binds_var wanted = runTcSWithEvBinds ev_binds_var$ solve_wanteds wanted solve_wanteds :: WantedConstraints -> TcS WantedConstraints -- NB: wc_flats may be wanted /or/ derived now  dimitris committed Nov 16, 2011 723 solve_wanteds wanted@(WC { wc_flat = flats, wc_impl = implics, wc_insol = insols })  simonpj@microsoft.com committed Jan 12, 2011 724 725  = do { traceTcS "solveWanteds {" (ppr wanted)  dimitris committed Jul 19, 2012 726 727  -- Try the flat bit, including insolubles. Solving insolubles a -- second time round is a bit of a waste but the code is simple  Simon Peyton Jones committed Jul 23, 2012 728 729 730 731  -- and the program is wrong anyway, and we don't run the danger -- of adding Derived insolubles twice; see -- TcSMonad Note [Do not add duplicate derived insolubles] ; let all_flats = flats unionBags insols  dimitris committed Jun 08, 2012 732   dimitris committed Apr 10, 2012 733  ; impls_from_flats <- solveInteractCts $bagToList all_flats  simonpj@microsoft.com committed Jan 12, 2011 734   dimitris committed Nov 16, 2011 735 736  -- solve_wanteds iterates when it is able to float equalities -- out of one or more of the implications.  dimitris committed Apr 10, 2012 737  ; unsolved_implics <- simpl_loop 1 (implics unionBags impls_from_flats)  simonpj@microsoft.com committed Jan 12, 2011 738   dimitris committed Jul 19, 2012 739 740 741  ; is <- getTcSInerts ; let insoluble_flats = getInertInsols is unsolved_flats = getInertUnsolved is  dimitris committed Nov 16, 2011 742 743  ; bb <- getTcEvBindsMap  simonpj@microsoft.com committed Nov 12, 2010 744  ; tb <- getTcSTyBindsMap  dimitris committed Nov 16, 2011 745   simonpj@microsoft.com committed Sep 13, 2010 746  ; traceTcS "solveWanteds }"$  simonpj@microsoft.com committed Nov 12, 2010 747  vcat [ text "unsolved_flats =" <+> ppr unsolved_flats  simonpj@microsoft.com committed Jan 12, 2011 748  , text "unsolved_implics =" <+> ppr unsolved_implics  dimitris committed Nov 16, 2011 749  , text "current evbinds =" <+> ppr (evBindMapBinds bb)  simonpj@microsoft.com committed Nov 12, 2010 750 751 752  , text "current tybinds =" <+> vcat (map ppr (varEnvElts tb)) ]  dimitris committed Jul 19, 2012 753 754 755 756  ; let wc = WC { wc_flat = unsolved_flats , wc_impl = unsolved_implics , wc_insol = insoluble_flats }  simonpj@microsoft.com committed Jan 12, 2011 757   Simon Peyton Jones committed Mar 02, 2012 758  ; traceTcS "solveWanteds finished with" $ dimitris committed Jul 19, 2012 759 760 761 762  vcat [ text "wc (unflattened) =" <+> ppr wc ] ; unFlattenWC wc }  Simon Peyton Jones committed Mar 02, 2012 763   dimitris committed Nov 16, 2011 764 765 766 767 768 769 770 771 772  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 773   dimitris committed Jun 08, 2012 774 775 776 777  ; 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]  dimitris committed Jul 19, 2012 778 779  ; unsolved_flats <- getTcSInerts >>= (return . getInertUnsolved)  dimitris committed Nov 16, 2011 780 781 782 783  ; traceTcS "solveWanteds: simpl_loop end"$ vcat [ text "improve_eqs =" <+> ppr improve_eqs , text "unsolved_flats =" <+> ppr unsolved_flats , text "unsolved_implics =" <+> ppr unsolved_implics ]  784   dimitris committed Jul 19, 2012 785   dimitris committed Nov 16, 2011 786  ; if isEmptyBag improve_eqs then return unsolved_implics  dimitris committed Apr 10, 2012 787 788 789  else do { impls_from_eqs <- solveInteractCts $bagToList improve_eqs ; simpl_loop (n+1) (unsolved_implics unionBags impls_from_eqs)} }  790   dimitris committed Jul 19, 2012 791   dimitris committed Nov 16, 2011 792 793 794 795 796 797 798 799 800 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  dimitris committed Jul 19, 2012 801 802 803  ; traceTcS "solveNestedImplications starting, inerts are:"$ ppr inerts ; let (pushed_givens, thinner_inerts) = splitInertsForImplications inerts  dimitris committed Jun 08, 2012 804  ; traceTcS "solveNestedImplications starting, more info:" $ dimitris committed Jul 19, 2012 805 806  vcat [ text "original inerts = " <+> ppr inerts , text "pushed_givens = " <+> ppr pushed_givens  dimitris committed Jun 08, 2012 807 808  , text "thinner_inerts = " <+> ppr thinner_inerts ]  dimitris committed Nov 16, 2011 809 810  ; (implic_eqs, unsolved_implics) <- doWithInert thinner_inerts$  dimitris committed Jul 19, 2012 811  do { let tcs_untouchables  dimitris committed Jun 08, 2012 812 813 814 815 816 817  = foldr (unionVarSet . tyVarsOfCt) emptyVarSet pushed_givens -- Typically pushed_givens is very small, consists -- only of unsolved equalities, so no inefficiency -- danger.  dimitris committed Nov 16, 2011 818 819 820 821  -- 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]  dimitris committed Jun 08, 2012 822 823  ; impls_from_givens <- solveInteractCts pushed_givens  dimitris committed Apr 10, 2012 824  ; MASSERT (isEmptyBag impls_from_givens)  dimitris committed Jun 08, 2012 825 826 827 828  -- 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)  dimitris committed Apr 10, 2012 829   dimitris committed Nov 16, 2011 830 831 832 833 834 835  ; 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.  836 837 838 839 840 841  ; 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 842 843 844 845 846 847 848 849 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 850 851 852  , ic_binds = ev_binds , ic_skols = skols , ic_given = givens  simonpj@microsoft.com committed Sep 13, 2010 853  , ic_wanted = wanteds  simonpj@microsoft.com committed Oct 06, 2010 854  , ic_loc = loc })  Simon Peyton Jones committed Jun 13, 2012 855 856  = shadowIPs givens $-- See Note [Shadowing of Implicit Parameters] nestImplicTcS ev_binds (untch, tcs_untouchables)$  simonpj@microsoft.com committed Oct 19, 2010 857 858  recoverTcS (return (emptyBag, emptyBag)) $-- Recover from nested failures. Even the top level is  dimitris committed Nov 16, 2011 859  -- just a bunch of implications, so failing at the first one is bad  simonpj@microsoft.com committed Sep 13, 2010 860 861 862  do { traceTcS "solveImplication {" (ppr imp) -- Solve flat givens  dimitris committed Apr 10, 2012 863 864 865  ; impls_from_givens <- solveInteractGiven loc givens ; MASSERT (isEmptyBag impls_from_givens)  simonpj@microsoft.com committed Sep 13, 2010 866  -- Simplify the wanteds  dimitris committed Jul 19, 2012 867 868 869  ; WC { wc_flat = unsolved_flats , wc_impl = unsolved_implics , wc_insol = insols } <- solve_wanteds wanteds  simonpj@microsoft.com committed Jan 12, 2011 870 871 872  ; let (res_flat_free, res_flat_bound) = floatEqualities skols givens unsolved_flats  simonpj@microsoft.com committed Sep 13, 2010 873   Simon Peyton Jones committed Jul 23, 2012 874  ; let res_wanted = WC { wc_flat = res_flat_bound  dimitris committed Nov 16, 2011 875  , wc_impl = unsolved_implics  simonpj@microsoft.com committed Jan 12, 2011 876  , wc_insol = insols }  dimitris committed Nov 16, 2011 877   simonpj@microsoft.com committed Jan 12, 2011 878 879 880  res_implic = unitImplication$ imp { ic_wanted = res_wanted , ic_insol = insolubleWC res_wanted }  simonpj@microsoft.com committed Sep 13, 2010 881   dimitris committed Nov 16, 2011 882 883  ; evbinds <- getTcEvBindsMap  simonpj@microsoft.com committed Sep 13, 2010 884 885  ; traceTcS "solveImplication end }" \$ vcat [ text "res_flat_free =" <+> ppr res_flat_free  dimitris committed Nov 16, 2011 886  , text "implication evbinds = " <+> ppr (evBindMapBinds evbinds)  simonpj@microsoft.com committed Jan 12, 2011 887  , text "res_implic =" <+> ppr res_implic ]  simonpj@microsoft.com committed Sep 13, 2010 888   simonpj@microsoft.com committed Jan 12, 2011 889  ; return (res_flat_free, res_implic) }  dimitris committed Nov 16, 2011 890  -- and we are back to the original inerts  simonpj@microsoft.com committed Sep 13, 2010 891   dimitris committed Jul 19, 2012 892 893 894 895 \end{code} \begin{code}  Simon Peyton Jones committed Jan 12, 2012 896 floatEqualities :: [TcTyVar] -> [EvVar] -> Cts -> (Cts, Cts)  simonpj@microsoft.com committed Jan 12, 2011 897 898 899 900 -- 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 901  -- Note [Float Equalities out of Implications]  simonpj@microsoft.com committed Jan 12, 2011 902  | otherwise = partitionBag is_floatable wantders  Simon Peyton Jones committed Jan 12, 2012 903 904  where skol_set = mkVarSet skols is_floatable :: Ct -> Bool  dimitris committed Nov 16, 2011 905  is_floatable ct  dimitris committed Nov 29, 2011 906  | ct_predty <- ctPred ct  dimitris committed Nov 16, 2011 907  , isEqPred ct_predty  Simon Peyton Jones committed Jan 12, 2012 908  = skol_set disjointVarSet tvs_under_fsks ct_predty  dimitris committed Nov 16, 2011 909  is_floatable _ct = False  simonpj@microsoft.com committed Nov 12, 2010 910 911 912 913 914 915 916 917  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)  Simon Peyton Jones committed Jan 13, 2012 918  tvs_under_fsks (LitTy {}) = emptyVarSet  simonpj@microsoft.com committed Nov 12, 2010 919 920 921  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 922  -- can mention type variables!  simonpj@microsoft.com committed Nov 12, 2010 923 924 925 926 927  | 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  Simon Peyton Jones committed Jun 13, 2012 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952  shadowIPs :: [EvVar] -> TcS a -> TcS a shadowIPs gs m | null shadowed = m | otherwise = do is <- getTcSInerts doWithInert (purgeShadowed is) m where shadowed = mapMaybe isIP gs isIP g = do p <- evVarPred_maybe g (x,_) <- isIPPred_maybe p return x isShadowedCt ct = isShadowedEv (ctEvidence ct) isShadowedEv ev = case isIPPred_maybe (ctEvPred ev) of Just (x,_) -> x elem shadowed _ -> False purgeShadowed is = is { inert_cans = purgeCans (inert_cans is) , inert_solved = purgeSolved (inert_solved is) } purgeDicts = snd . partitionCCanMap isShadowedCt purgeCans ics = ics { inert_dicts = purgeDicts (inert_dicts ics) } purgeSolved = filterSolved (not . isShadowedEv)  lewie committed Mar 02, 2000 953 \end{code}  partain committed Jan 08, 1996 954   simonpj@microsoft.com committed Sep 13, 2010 955 956 957 958 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:  959 960  a) In checking mode, suppresses unnecessary errors. We already have  simonpj@microsoft.com committed Sep 13, 2010 961  on unsolved-wanted error; adding it to the givens prevents any  simonpj@microsoft.com committed Feb 11, 2011 962  consequential errors from showing up  963   simonpj@microsoft.com committed Sep 13, 2010 964 965 966 967  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 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990  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 991 992 993 994 995 996 997 998 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  999 1000 'solveInteract' step first.  dimitris committed May 17, 2011 1001 1002 1003 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 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.  1037 1038 1039 Note [Extra TcsTv untouchables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  dimitris committed Jun 08, 2012 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 Whenever we are solving a bunch of flat constraints, they may contain the following sorts of 'touchable' unification variables: (i) Born-touchables in that scope (ii) Simplifier-generated unification variables, such as unification flatten variables (iii) Touchables that have been floated out from some nested implications, see Note [Float Equalities out of Implications]. Now, once we are done with solving these flats and have to move inwards to the nested implications (perhaps for a second time), we must consider all the extra variables (categories (ii) and (iii) above) as untouchables for the implication. Otherwise we have the danger or double unifications, as well as the danger of not seing'' some unification. Example (from Trac #4494):  1056   dimitris committed Jun 08, 2012 1057 1058 1059 1060 1061  (F Int ~ uf) /\ [untch=beta](forall a. C a => F Int ~ beta) 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  1062  uf ~ beta  simonpj@microsoft.com committed Feb 11, 2011 1063 1064 1065 1066 1067 emerges. We may spontaneously solve it to get uf := beta, so the whole implication disappears but when we pop out again we are left with (F Int ~ uf) which will be unified by our final solveCTyFunEqs stage and uf w