TcSimplify.lhs 56 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,  Simon Peyton Jones committed Sep 03, 2012 12 13  simplifyRule, simplifyTop, simplifyInteractive, solveWantedsTcM  simonpj@microsoft.com committed Sep 13, 2010 14  ) where  partain committed Jan 08, 1996 15   simonm committed Jan 08, 1998 16 #include "HsVersions.h"  partain committed Mar 19, 1996 17   Simon Peyton Jones committed Aug 28, 2012 18 import TcRnTypes  simonpj committed Sep 13, 2002 19 import TcRnMonad  simonpj@microsoft.com committed Sep 13, 2010 20 import TcErrors  simonpj@microsoft.com committed Jan 02, 2007 21 import TcMType  simonpj@microsoft.com committed Sep 13, 2010 22 23 import TcType import TcSMonad  dimitris committed Nov 16, 2011 24 import TcInteract  simonpj@microsoft.com committed Sep 13, 2010 25 import Inst  26 import Unify ( niFixTvSubst, niSubstTvSet )  Simon Peyton Jones committed Aug 28, 2012 27 28 import Type ( classifyPredType, PredTree(..), getClassPredTys_maybe ) import Class ( Class )  Simon Marlow committed Oct 11, 2006 29 import Var  dimitris committed Jun 08, 2012 30 import Unique  simonm committed Dec 02, 1998 31 import VarSet  simonpj@microsoft.com committed Nov 12, 2010 32 import VarEnv  Simon Peyton Jones committed Dec 05, 2011 33 import TcEvidence  simonpj@microsoft.com committed Nov 12, 2010 34 import TypeRep  simonpj@microsoft.com committed Sep 13, 2010 35 import Name  simonmar committed Dec 10, 2003 36 import Bag  Simon Marlow committed Oct 11, 2006 37 38 import ListSetOps import Util  simonpj@microsoft.com committed Sep 13, 2010 39 40 41 import PrelInfo import PrelNames import Class ( classKey )  Simon Peyton Jones committed Aug 16, 2011 42 import BasicTypes ( RuleName )  simonpj@microsoft.com committed Jan 12, 2011 43 import Control.Monad ( when )  simonpj@microsoft.com committed Sep 13, 2010 44 import Outputable  Ian Lynagh committed Mar 29, 2008 45 import FastString  dimitris committed Mar 28, 2012 46 import TrieMap () -- DV: for now  Simon Peyton Jones committed Jan 12, 2012 47 import DynFlags  partain committed Jan 08, 1996 48 49 50 \end{code}  simonpj@microsoft.com committed Sep 13, 2010 51 52 53 54 55 ********************************************************************************* * * * External interface * * * *********************************************************************************  simonpj committed Jan 25, 2001 56   dimitris committed Jun 08, 2012 57   simonpj@microsoft.com committed Sep 13, 2010 58 59 60 \begin{code} 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  Simon Peyton Jones committed Sep 01, 2012 65  = do { zonked_wanteds <- zonkWC wanteds  Simon Peyton Jones committed Aug 28, 2012 66 67  ; traceTc "simplifyTop {" $text "zonked_wc =" <+> ppr zonked_wanteds  Simon Peyton Jones committed Sep 01, 2012 68 69 70 71 72 73 74 75 76  ; (final_wc, binds1) <- runTcS (simpl_top zonked_wanteds) ; traceTc "End simplifyTop }" empty ; traceTc "reportUnsolved {" empty -- See Note [Deferring coercion errors to runtime] ; runtimeCoercionErrors <- doptM Opt_DeferTypeErrors ; binds2 <- reportUnsolved runtimeCoercionErrors final_wc ; traceTc "reportUnsolved }" empty ; return (binds1 unionBags binds2) }  Simon Peyton Jones committed Aug 28, 2012 77   Simon Peyton Jones committed Sep 01, 2012 78 79 80 81 82 83  where -- See Note [Top-level Defaulting Plan] simpl_top wanteds = do { wc_first_go <- solveWantedsTcS wanteds ; applyTyVarDefaulting wc_first_go ; simpl_top_loop wc_first_go }  dimitris committed Jun 08, 2012 84   Simon Peyton Jones committed Sep 01, 2012 85 86 87 88 89 90 91 92 93 94 95 96  simpl_top_loop wc | isEmptyWC wc = return wc | otherwise = do { wc_residual <- solveWantedsTcS wc ; let wc_flat_approximate = approximateWC wc_residual ; something_happened <- applyDefaultingRules wc_flat_approximate -- See Note [Top-level Defaulting Plan] ; if something_happened then simpl_top_loop wc_residual else return wc_residual }  dimitris committed Jun 08, 2012 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 \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 141   Simon Peyton Jones committed Aug 16, 2011 142 143 144 ------------------ simplifyAmbiguityCheck :: Name -> WantedConstraints -> TcM (Bag EvBind) simplifyAmbiguityCheck name wanteds  dimitris committed Jun 08, 2012 145  = traceTc "simplifyAmbiguityCheck" (text "name =" <+> ppr name) >>  Simon Peyton Jones committed Sep 03, 2012 146  simplifyTop wanteds -- NB: must be simplifyTop so that we  147 148  -- do ambiguity resolution. -- See Note [Impedence matching] in TcBinds.  dimitris committed Nov 16, 2011 149   simonpj@microsoft.com committed Sep 13, 2010 150 151 152 ------------------ simplifyInteractive :: WantedConstraints -> TcM (Bag EvBind) simplifyInteractive wanteds  dimitris committed Jun 08, 2012 153 154  = traceTc "simplifyInteractive" empty >> simplifyTop wanteds  simonpj@microsoft.com committed Sep 13, 2010 155 156 157 158 159  ------------------ simplifyDefault :: ThetaType -- Wanted; has no type variables in it -> TcM () -- Succeeds iff the constraint is soluble simplifyDefault theta  dimitris committed Jun 08, 2012 160 161  = do { traceTc "simplifyInteractive" empty ; wanted <- newFlatWanteds DefaultOrigin theta  Simon Peyton Jones committed Sep 03, 2012 162 163 164 165 166 167 168 169  ; (unsolved, _binds) <- solveWantedsTcM (mkFlatWC wanted) ; traceTc "reportUnsolved {" empty -- See Note [Deferring coercion errors to runtime] ; runtimeCoercionErrors <- doptM Opt_DeferTypeErrors ; _ <- reportUnsolved runtimeCoercionErrors unsolved ; traceTc "reportUnsolved }" empty  simonpj@microsoft.com committed Sep 13, 2010 170 171  ; return () } \end{code}  simonpj committed Jan 25, 2001 172   simonpj committed May 03, 2001 173   dimitris committed Nov 16, 2011 174 ***********************************************************************************  simonpj@microsoft.com committed Sep 13, 2010 175 * *  dimitris committed Nov 16, 2011 176 * Deriving *  simonpj@microsoft.com committed Sep 13, 2010 177 178 * * ***********************************************************************************  simonpj committed May 03, 2001 179   simonpj@microsoft.com committed Sep 13, 2010 180 181 \begin{code} simplifyDeriv :: CtOrigin  simonpj committed Apr 19, 2011 182 183 184 185  -> PredType -> [TyVar] -> ThetaType -- Wanted -> TcM ThetaType -- Needed  simonpj@microsoft.com committed Sep 13, 2010 186 187 -- Given instance (wanted) => C inst_ty -- Simplify 'wanted' as much as possibles  simonpj@microsoft.com committed Jan 12, 2011 188 -- Fail if not possible  simonpj committed Apr 19, 2011 189 simplifyDeriv orig pred tvs theta  Simon Peyton Jones committed Mar 02, 2012 190  = do { (skol_subst, tvs_skols) <- tcInstSkolTyVars tvs -- Skolemize  simonpj@microsoft.com committed Feb 17, 2011 191 192 193 194  -- 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 195   Simon Peyton Jones committed Mar 02, 2012 196  ; let subst_skol = zipTopTvSubst tvs_skols$ map mkTyVarTy tvs  Simon Peyton Jones committed Jul 23, 2011 197  skol_set = mkVarSet tvs_skols  dimitris committed Jun 08, 2012 198  doc = ptext (sLit "deriving") <+> parens (ppr pred)  simonpj@microsoft.com committed Jan 12, 2011 199 200 201  ; wanted <- newFlatWanteds orig (substTheta skol_subst theta)  dimitris committed Jun 08, 2012 202 203  ; traceTc "simplifyDeriv" $vcat [ pprTvBndrs tvs $$ppr theta$$ ppr wanted, doc ]  Simon Peyton Jones committed Jan 12, 2012 204  ; (residual_wanted, _ev_binds1)  Simon Peyton Jones committed Sep 01, 2012 205  <- solveWantedsTcM (mkFlatWC wanted)  simonpj@microsoft.com committed Sep 13, 2010 206   simonpj@microsoft.com committed Jan 12, 2011 207 208  ; let (good, bad) = partitionBagWith get_good (wc_flat residual_wanted) -- See Note [Exotic derived instance contexts]  dimitris committed Nov 16, 2011 209  get_good :: Ct -> Either PredType Ct  dimitris committed Jul 19, 2012 210 211 212 213 214 215  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 216  where p = ctPred ct  simonpj@microsoft.com committed Sep 13, 2010 217   Simon Peyton Jones committed Jan 12, 2012 218 219 220  -- 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 221   simonpj@microsoft.com committed Jan 12, 2011 222 223  ; let min_theta = mkMinimalBySCs (bagToList good) ; return (substTheta subst_skol min_theta) }  simonpj@microsoft.com committed Sep 13, 2010 224 \end{code}  simonpj committed May 03, 2001 225   simonpj@microsoft.com committed Feb 17, 2011 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 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 251 252 253 254 255 256 257 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 258   simonpj@microsoft.com committed Sep 13, 2010 259 260 261 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 262   simonpj@microsoft.com committed Sep 13, 2010 263 264 Notice that this instance (just) satisfies the Paterson termination conditions. Then we *could* derive an instance decl like this:  simonpj committed Feb 10, 2004 265   simonpj@microsoft.com committed Sep 13, 2010 266 267 268 269  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 270   simonpj@microsoft.com committed Sep 13, 2010 271 272 273 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 274   simonpj@microsoft.com committed Sep 13, 2010 275 276 So for now we simply require that the derived instance context should have only type-variable constraints.  simonpj committed Feb 10, 2004 277   simonpj@microsoft.com committed Sep 13, 2010 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 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 307   dreixel committed Nov 11, 2011 308 309 310 311 312 313 314 315 316 317 318 319 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 320 \begin{code}  Simon Peyton Jones committed Aug 16, 2011 321 simplifyInfer :: Bool  simonpj@microsoft.com committed Jan 12, 2011 322 323 324  -> Bool -- Apply monomorphism restriction -> [(Name, TcTauType)] -- Variables to be generalised, -- and their tau-types  Simon Peyton Jones committed Aug 29, 2012 325  -> WantedConstraints  simonpj@microsoft.com committed Sep 13, 2010 326 327  -> TcM ([TcTyVar], -- Quantify over these type variables [EvVar], -- ... and these constraints  Simon Peyton Jones committed Aug 16, 2011 328 329 330  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 331  TcEvBinds) -- ... binding these evidence variables  Simon Peyton Jones committed Aug 29, 2012 332 simplifyInfer _top_lvl apply_mr name_taus wanteds  simonpj@microsoft.com committed Jan 12, 2011 333 334 335  | isEmptyWC wanteds = do { gbl_tvs <- tcGetGlobalTyVars -- Already zonked ; zonked_taus <- zonkTcTypes (map snd name_taus)  Simon Peyton Jones committed Feb 16, 2012 336  ; let tvs_to_quantify = varSetElems (tyVarsOfTypes zonked_taus minusVarSet gbl_tvs)  dreixel committed Nov 11, 2011 337 338 339  -- 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 340  ; return (qtvs, [], False, emptyTcEvBinds) }  simonpj committed Feb 10, 2004 341   simonpj@microsoft.com committed Sep 13, 2010 342  | otherwise  Simon Peyton Jones committed Aug 29, 2012 343  = do { runtimeCoercionErrors <- doptM Opt_DeferTypeErrors  simonpj@microsoft.com committed Jan 12, 2011 344  ; gbl_tvs <- tcGetGlobalTyVars  Simon Peyton Jones committed Mar 02, 2012 345  ; zonked_tau_tvs <- zonkTyVarsAndFV (tyVarsOfTypes (map snd name_taus))  Simon Peyton Jones committed Jun 21, 2012 346  ; zonked_wanteds <- zonkWC wanteds  simonpj@microsoft.com committed Jan 12, 2011 347   simonpj@microsoft.com committed Sep 13, 2010 348  ; traceTc "simplifyInfer {"$ vcat  Simon Peyton Jones committed Aug 16, 2011 349  [ ptext (sLit "names =") <+> ppr (map fst name_taus)  Simon Peyton Jones committed Mar 02, 2012 350 351  , ptext (sLit "taus =") <+> ppr (map snd name_taus) , ptext (sLit "tau_tvs (zonked) =") <+> ppr zonked_tau_tvs  Simon Peyton Jones committed Aug 16, 2011 352 353 354  , 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 355  , ptext (sLit "wanted =") <+> ppr zonked_wanteds  simonpj@microsoft.com committed Sep 13, 2010 356 357  ]  Simon Peyton Jones committed Jun 21, 2012 358 359 360 361 362  -- 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 363   Simon Peyton Jones committed Jun 21, 2012 364 365 366 367 368 369 370 371  -- 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 372  ; ev_binds_var <- newTcEvBinds  dimitris committed Jul 19, 2012 373  ; wanted_transformed <- solveWantedsWithEvBinds ev_binds_var zonked_wanteds  Simon Peyton Jones committed Jun 21, 2012 374 375  -- Step 3) Fail fast if there is an insoluble constraint,  dimitris committed Jun 08, 2012 376 377 378  -- 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 379 380  -- Step 4) Candidates for quantification are an approximation of wanted_transformed  dimitris committed Jun 08, 2012 381 382 383  -- 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   Simon Peyton Jones committed Jun 21, 2012 385 386  -- Step 5) Minimize the quantification candidates -- Step 6) Final candidates for quantification  Simon Peyton Jones committed Sep 01, 2012 387 388 389 390 391 392 393 394 395 396 397  -- We discard bindings, insolubles etc, because all we are -- care aout it ; (quant_pred_candidates, _extra_binds) <- runTcS$ do { let quant_candidates = approximateWC wanted_transformed ; promoteTyVars quant_candidates ; _implics <- solveInteract quant_candidates ; (flats, _insols) <- getInertUnsolved ; return (map ctPred $filter isWantedCt (bagToList flats)) } -- NB: quant_pred_candidates is already the fixpoint of any -- unifications that may have happened  dimitris committed Jun 08, 2012 398 399  ; gbl_tvs <- tcGetGlobalTyVars -- TODO: can we just use untch instead of gbl_tvs?  Simon Peyton Jones committed Mar 02, 2012 400  ; zonked_tau_tvs <- zonkTyVarsAndFV zonked_tau_tvs  dimitris committed Jun 08, 2012 401   402  ; let init_tvs = zonked_tau_tvs minusVarSet gbl_tvs  Simon Peyton Jones committed Sep 01, 2012 403  poly_qtvs = growThetaTyVars quant_pred_candidates init_tvs  404  minusVarSet gbl_tvs  Simon Peyton Jones committed Sep 01, 2012 405  pbound = filter (quantifyPred poly_qtvs) quant_pred_candidates  dimitris committed Jun 08, 2012 406   Simon Peyton Jones committed Aug 16, 2011 407  -- Monomorphism restriction  Simon Peyton Jones committed Sep 01, 2012 408 409  mr_qtvs = init_tvs minusVarSet constrained_tvs constrained_tvs = tyVarsOfTypes quant_pred_candidates  410  mr_bites = apply_mr && not (null pbound)  Simon Peyton Jones committed Aug 16, 2011 411   Simon Peyton Jones committed Sep 01, 2012 412 413  (qtvs, bound) | mr_bites = (mr_qtvs, []) | otherwise = (poly_qtvs, pbound)  dimitris committed Jun 08, 2012 414   Simon Peyton Jones committed Sep 01, 2012 415 416 417 418 419 420 421  ; traceTc "simplifyWithApprox"$ vcat [ ptext (sLit "quant_pred_candidates =") <+> ppr quant_pred_candidates , ptext (sLit "gbl_tvs=") <+> ppr gbl_tvs , ptext (sLit "zonked_tau_tvs=") <+> ppr zonked_tau_tvs , ptext (sLit "pbound =") <+> ppr pbound , ptext (sLit "init_qtvs =") <+> ppr init_tvs , ptext (sLit "poly_qtvs =") <+> ppr poly_qtvs ]  simonpj@microsoft.com committed Jan 12, 2011 422   423  ; if isEmptyVarSet qtvs && null bound  Simon Peyton Jones committed Jul 14, 2012 424 425 426 427  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 428  ; return ([], [], mr_bites, TcEvBinds ev_binds_var) }  simonpj@microsoft.com committed Jan 12, 2011 429 430  else do  dimitris committed Jun 08, 2012 431 432 433  { traceTc "simplifyApprox" $ptext (sLit "bound are =") <+> ppr bound  simonpj@microsoft.com committed Jan 12, 2011 434  -- Step 4, zonk quantified variables  435  ; let minimal_flat_preds = mkMinimalBySCs bound  Simon Peyton Jones committed Aug 16, 2011 436 437  skol_info = InferSkol [ (name, mkSigmaTy [] minimal_flat_preds ty) | (name, ty) <- name_taus ]  simonpj@microsoft.com committed Jan 12, 2011 438 439 440 441  -- 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 442  ; qtvs_to_return <- zonkQuantifiedTyVars (varSetElems qtvs)  simonpj@microsoft.com committed Jan 12, 2011 443   Simon Peyton Jones committed Jun 21, 2012 444  -- Step 7) Emit an implication  simonpj@microsoft.com committed Jan 12, 2011 445 446  ; minimal_bound_ev_vars <- mapM TcMType.newEvVar minimal_flat_preds ; lcl_env <- getLclTypeEnv  dreixel committed Nov 11, 2011 447  ; gloc <- getCtLoc skol_info  Simon Peyton Jones committed Aug 29, 2012 448  ; untch <- TcRnMonad.getUntouchables  Simon Peyton Jones committed Sep 03, 2012 449  ; let implic = Implic { ic_untch = pushUntouchables untch  simonpj@microsoft.com committed Jan 12, 2011 450  , ic_env = lcl_env  Simon Peyton Jones committed Jan 12, 2012 451  , ic_skols = qtvs_to_return  Simon Peyton Jones committed Aug 28, 2012 452 453  , ic_fsks = [] -- wanted_tansformed arose only from solveWanteds -- hence no flatten-skolems (which come from givens)  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  Simon Peyton Jones committed Sep 01, 2012 465  , ptext (sLit "spb =") <+> ppr quant_pred_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) } }  simonpj@microsoft.com committed Jan 12, 2011 470 \end{code}  simonpj@microsoft.com committed Sep 13, 2010 471 472   473 474 Note [Default while Inferring] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  dimitris committed Jun 08, 2012 475 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 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 509 510 511 512 513 514 515 516 517 Note [Minimize by Superclasses] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we quantify over a constraint, in simplifyInfer we need to quantify over a constraint that is minimal in some sense: For instance, if the final wanted constraint is (Eq alpha, Ord alpha), we'd like to quantify over Ord alpha, because we can just get Eq alpha from superclass selection from Ord alpha. This minimization is what mkMinimalBySCs does. Then, simplifyInfer uses the minimal constraint to check the original wanted.  simonpj@microsoft.com committed Sep 13, 2010 518   simonpj committed Jan 25, 2001 519   simonpj@microsoft.com committed Oct 08, 2010 520 521 Note [Avoid unecessary constraint simplification] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  Simon Peyton Jones committed Jun 21, 2012 522 523 524 525  -------- 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 526 When inferring the type of a let-binding, with simplifyInfer,  Simon Peyton Jones committed Jun 21, 2012 527 try to avoid unnecessarily simplifying class constraints.  simonpj@microsoft.com committed Oct 08, 2010 528 529 Doing so aids sharing, but it also helps with delicate situations like  dimitris committed Jun 08, 2012 530   simonpj@microsoft.com committed Oct 08, 2010 531  instance C t => C [t] where ..  dimitris committed Jun 08, 2012 532   simonpj@microsoft.com committed Oct 08, 2010 533 534 535 536 537 538 539 540 541 542 543  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 544 545 546 547 548 ********************************************************************************* * * * RULES * * * ***********************************************************************************  simonpj committed May 12, 2004 549   Simon Peyton Jones committed Apr 16, 2012 550 See note [Simplifying RULE consraints] in TcRule  simonpj committed Jun 28, 1999 551   Simon Peyton Jones committed Apr 16, 2012 552 553 554 555 556 557 558 559 560 561 562 563 564 565 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 566 567  \begin{code}  simonpj@microsoft.com committed Sep 13, 2010 568 569 570 simplifyRule :: RuleName -> WantedConstraints -- Constraints from LHS -> WantedConstraints -- Constraints from RHS  Simon Peyton Jones committed Apr 16, 2012 571 572 573  -> TcM ([EvVar], WantedConstraints) -- LHS evidence varaibles -- See Note [Simplifying RULE constraints] in TcRule simplifyRule name lhs_wanted rhs_wanted  Simon Peyton Jones committed Sep 03, 2012 574  = do { -- We allow ourselves to unify environment  dimitris committed Jun 08, 2012 575  -- variables: runTcS runs with NoUntouchables  Simon Peyton Jones committed Sep 03, 2012 576  (resid_wanted, _) <- solveWantedsTcM (lhs_wanted andWC rhs_wanted)  Simon Peyton Jones committed Apr 16, 2012 577   simonpj@microsoft.com committed Jan 12, 2011 578 579  ; zonked_lhs <- zonkWC lhs_wanted  Simon Peyton Jones committed Apr 16, 2012 580 581 582 583 584 585 586 587 588 589 590 591 592  ; 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 593  ; traceTc "simplifyRule" $ Simon Peyton Jones committed Sep 03, 2012 594  vcat [ ptext (sLit "LHS of rule") <+> doubleQuotes (ftext name)  dimitris committed Jun 08, 2012 595  , text "zonked_lhs" <+> ppr zonked_lhs  Simon Peyton Jones committed Apr 16, 2012 596 597  , text "q_cts" <+> ppr q_cts ]  Simon Peyton Jones committed May 07, 2012 598 599  ; return ( map (ctEvId . ctEvidence) (bagToList q_cts) , zonked_lhs { wc_flat = non_q_cts }) }  simonpj committed Sep 13, 2002 600 601 602 \end{code}  simonpj@microsoft.com committed Sep 13, 2010 603 604 605 606 607 ********************************************************************************* * * * Main Simplifier * * * ***********************************************************************************  lewie committed Mar 02, 2000 608   Simon Peyton Jones committed Jan 12, 2012 609 610 611 612 613 614 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 615   Simon Peyton Jones committed Jan 12, 2012 616 617  a :: Int a = 'a'  simonpj@microsoft.com committed Sep 13, 2010 618   Simon Peyton Jones committed Jan 12, 2012 619  main = print "b"  simonpj@microsoft.com committed Sep 13, 2010 620   Simon Peyton Jones committed Jan 12, 2012 621 622 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 623   Simon Peyton Jones committed Jan 12, 2012 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 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 647   Simon Peyton Jones committed Sep 01, 2012 648 solveWantedsTcM :: WantedConstraints -> TcM (WantedConstraints, Bag EvBind)  Simon Peyton Jones committed Sep 03, 2012 649 -- Zonk the input constraints, and simplify them  dimitris committed Jul 19, 2012 650 -- Return the evidence binds in the BagEvBinds result  Simon Peyton Jones committed Aug 28, 2012 651 -- Discards all Derived stuff in result  Simon Peyton Jones committed Sep 03, 2012 652 653 654 655 656 657 solveWantedsTcM wanted = do { zonked_wanted <- zonkWC wanted ; traceTc "solveWantedsTcM {" (ppr zonked_wanted) ; (wanteds', binds) <- runTcS (solve_wanteds_and_drop zonked_wanted) ; traceTc "solveWantedsTcM end }" (ppr wanteds') ; return (wanteds', binds) }  dimitris committed Jul 19, 2012 658 659 660  solveWantedsWithEvBinds :: EvBindsVar -> WantedConstraints -> TcM WantedConstraints -- Side-effect the EvBindsVar argument to add new bindings from solving  Simon Peyton Jones committed Aug 28, 2012 661 -- Discards all Derived stuff in result  dimitris committed Jul 19, 2012 662 solveWantedsWithEvBinds ev_binds_var wanted  Simon Peyton Jones committed Sep 01, 2012 663 664 665 666 667 668 669 670 671 672 673 674 675 676  = runTcSWithEvBinds ev_binds_var (solve_wanteds_and_drop wanted) solveWantedsTcS :: WantedConstraints -> TcS WantedConstraints -- Solve, with current untouchables, augmenting the current -- evidence bindings, ty_binds, and solved caches -- However, revert the InertCans to the way they were at -- the beginning (since we are returning the residual) solveWantedsTcS wanted = nestTcS (solve_wanteds_and_drop wanted) solve_wanteds_and_drop :: WantedConstraints -> TcS (WantedConstraints) -- Since solve_wanteds returns the residual WantedConstraints, -- it should alway be called within a runTcS or something similar, solve_wanteds_and_drop wanted = do { wc <- solve_wanteds wanted ; return (dropDerivedWC wc) }  dimitris committed Jul 19, 2012 677 678  solve_wanteds :: WantedConstraints -> TcS WantedConstraints  Simon Peyton Jones committed Sep 01, 2012 679 -- so that the inert set doesn't mindlessly propagate.  dimitris committed Jul 19, 2012 680 -- NB: wc_flats may be wanted /or/ derived now  dimitris committed Nov 16, 2011 681 solve_wanteds wanted@(WC { wc_flat = flats, wc_impl = implics, wc_insol = insols })  simonpj@microsoft.com committed Jan 12, 2011 682 683  = do { traceTcS "solveWanteds {" (ppr wanted)  dimitris committed Jul 19, 2012 684 685  -- 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 686 687 688  -- 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]  Simon Peyton Jones committed Aug 28, 2012 689  ; traceTcS "solveFlats {" empty  Simon Peyton Jones committed Jul 23, 2012 690  ; let all_flats = flats unionBags insols  Simon Peyton Jones committed Aug 28, 2012 691 692  ; impls_from_flats <- solveInteract all_flats ; traceTcS "solveFlats end }" (ppr impls_from_flats)  simonpj@microsoft.com committed Jan 12, 2011 693   dimitris committed Nov 16, 2011 694 695  -- solve_wanteds iterates when it is able to float equalities -- out of one or more of the implications.  dimitris committed Apr 10, 2012 696  ; unsolved_implics <- simpl_loop 1 (implics unionBags impls_from_flats)  simonpj@microsoft.com committed Jan 12, 2011 697   Simon Peyton Jones committed Aug 28, 2012 698 699 700 701 702  ; (unsolved_flats, insoluble_flats) <- getInertUnsolved ; wc <- unFlattenWC (WC { wc_flat = unsolved_flats , wc_impl = unsolved_implics , wc_insol = insoluble_flats })  dimitris committed Nov 16, 2011 703 704  ; bb <- getTcEvBindsMap  simonpj@microsoft.com committed Nov 12, 2010 705  ; tb <- getTcSTyBindsMap  simonpj@microsoft.com committed Sep 13, 2010 706  ; traceTcS "solveWanteds }"$  simonpj@microsoft.com committed Nov 12, 2010 707  vcat [ text "unsolved_flats =" <+> ppr unsolved_flats  simonpj@microsoft.com committed Jan 12, 2011 708  , text "unsolved_implics =" <+> ppr unsolved_implics  dimitris committed Nov 16, 2011 709  , text "current evbinds =" <+> ppr (evBindMapBinds bb)  simonpj@microsoft.com committed Nov 12, 2010 710  , text "current tybinds =" <+> vcat (map ppr (varEnvElts tb))  Simon Peyton Jones committed Aug 28, 2012 711  , text "final wc =" <+> ppr wc ]  Simon Peyton Jones committed Mar 02, 2012 712   Simon Peyton Jones committed Aug 28, 2012 713  ; return wc }  dimitris committed Nov 16, 2011 714 715 716 717 718 719 720 721  simpl_loop :: Int -> Bag Implication -> TcS (Bag Implication) simpl_loop n implics | n > 10 = traceTcS "solveWanteds: loop!" empty >> return implics | otherwise  Simon Peyton Jones committed Aug 28, 2012 722 723 724 725 726 727 728  = do { (floated_eqs, unsolved_implics) <- solveNestedImplications implics ; if isEmptyBag floated_eqs then return unsolved_implics else do { -- Put floated_eqs into the current inert set before looping impls_from_eqs <- solveInteract floated_eqs ; simpl_loop (n+1) (unsolved_implics unionBags impls_from_eqs)} }  729   dimitris committed Jul 19, 2012 730   dimitris committed Nov 16, 2011 731 732 733 734 735 736 737 738 739 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  Simon Peyton Jones committed Aug 28, 2012 740 741  ; let thinner_inerts = prepareInertsForImplications inerts -- See Note [Preparing inert set for implications]  dimitris committed Jul 19, 2012 742   Simon Peyton Jones committed Aug 28, 2012 743  ; traceTcS "solveNestedImplications starting {" $ dimitris committed Jul 19, 2012 744  vcat [ text "original inerts = " <+> ppr inerts  dimitris committed Jun 08, 2012 745 746  , text "thinner_inerts = " <+> ppr thinner_inerts ]  Simon Peyton Jones committed Aug 28, 2012 747  ; (floated_eqs, unsolved_implics)  Simon Peyton Jones committed Aug 28, 2012 748  <- flatMapBagPairM (solveImplication thinner_inerts) implics  dimitris committed Nov 16, 2011 749 750 751 752  -- ... 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.  Simon Peyton Jones committed Aug 28, 2012 753  ; traceTcS "solveNestedImplications end }"$  Simon Peyton Jones committed Aug 28, 2012 754  vcat [ text "all floated_eqs =" <+> ppr floated_eqs  755 756  , text "unsolved_implics =" <+> ppr unsolved_implics ]  Simon Peyton Jones committed Aug 28, 2012 757  ; return (floated_eqs, unsolved_implics) }  758   Simon Peyton Jones committed Aug 28, 2012 759 solveImplication :: InertSet  dimitris committed Nov 16, 2011 760 761 762 763 764  -> 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  Simon Peyton Jones committed Aug 28, 2012 765 solveImplication inerts  dimitris committed Nov 16, 2011 766  imp@(Implic { ic_untch = untch  simonpj@microsoft.com committed Oct 06, 2010 767 768  , ic_binds = ev_binds , ic_skols = skols  Simon Peyton Jones committed Aug 28, 2012 769  , ic_fsks = old_fsks  simonpj@microsoft.com committed Oct 06, 2010 770  , ic_given = givens  simonpj@microsoft.com committed Sep 13, 2010 771  , ic_wanted = wanteds  simonpj@microsoft.com committed Oct 06, 2010 772  , ic_loc = loc })  Simon Peyton Jones committed Sep 01, 2012 773  =  simonpj@microsoft.com committed Sep 13, 2010 774 775  do { traceTcS "solveImplication {" (ppr imp)  Simon Peyton Jones committed Aug 28, 2012 776  -- Solve the nested constraints  Simon Peyton Jones committed Sep 01, 2012 777 778 779 780 781 782 783 784 785 786 787 788  -- NB: 'inerts' has empty inert_fsks ; (new_fsks, residual_wanted) <- nestImplicTcS ev_binds untch inerts $do { solveInteractGiven loc old_fsks givens ; residual_wanted <- solve_wanteds wanteds ; more_fsks <- getFlattenSkols ; return (more_fsks ++ old_fsks, residual_wanted) } ; (floated_eqs, final_wanted) <- floatEqualities (skols ++ new_fsks) givens residual_wanted ; let res_implic | isEmptyWC final_wanted  Simon Peyton Jones committed Aug 28, 2012 789 790  = emptyBag | otherwise  Simon Peyton Jones committed Sep 01, 2012 791 792 793  = unitBag (imp { ic_fsks = new_fsks , ic_wanted = dropDerivedWC final_wanted , ic_insol = insolubleWC final_wanted })  simonpj@microsoft.com committed Sep 13, 2010 794   dimitris committed Nov 16, 2011 795  ; evbinds <- getTcEvBindsMap  simonpj@microsoft.com committed Sep 13, 2010 796  ; traceTcS "solveImplication end }"$ vcat  Simon Peyton Jones committed Aug 28, 2012 797  [ text "floated_eqs =" <+> ppr floated_eqs  Simon Peyton Jones committed Sep 01, 2012 798  , text "new_fsks =" <+> ppr new_fsks  Simon Peyton Jones committed Aug 28, 2012 799 800  , text "res_implic =" <+> ppr res_implic , text "implication evbinds = " <+> ppr (evBindMapBinds evbinds) ]  simonpj@microsoft.com committed Sep 13, 2010 801   Simon Peyton Jones committed Aug 28, 2012 802  ; return (floated_eqs, res_implic) }  dimitris committed Jul 19, 2012 803 804 805 806 \end{code} \begin{code}  Simon Peyton Jones committed Sep 01, 2012 807 808 floatEqualities :: [TcTyVar] -> [EvVar] -> WantedConstraints -> TcS (Cts, WantedConstraints)  simonpj@microsoft.com committed Jan 12, 2011 809 810 -- Post: The returned FlavoredEvVar's are only Wanted or Derived -- and come from the input wanted ev vars or deriveds  Simon Peyton Jones committed Sep 01, 2012 811 812 -- Also performs some unifications, adding to monadically-carried ty_binds -- These will be used when processing floated_eqs later  Simon Peyton Jones committed Aug 28, 2012 813 814 floatEqualities skols can_given wanteds@(WC { wc_flat = flats }) | hasEqualities can_given  Simon Peyton Jones committed Sep 01, 2012 815  = return (emptyBag, wanteds) -- Note [Float Equalities out of Implications]  Simon Peyton Jones committed Aug 28, 2012 816  | otherwise  Simon Peyton Jones committed Sep 01, 2012 817 818  = do { let (float_eqs, remaining_flats) = partitionBag is_floatable flats ; promoteTyVars float_eqs  Simon Peyton Jones committed Sep 01, 2012 819  ; ty_binds <- getTcSTyBindsMap  Simon Peyton Jones committed Sep 01, 2012 820  ; traceTcS "floatEqualities" (vcat [ text "Floated eqs =" <+> ppr float_eqs  Simon Peyton Jones committed Sep 01, 2012 821 822  , text "Ty binds =" <+> ppr ty_binds]) ; return (float_eqs, wanteds { wc_flat = remaining_flats }) }  Simon Peyton Jones committed Aug 28, 2012 823 824 825 826 827 828 829 830 831  where skol_set = growSkols wanteds (mkVarSet skols) is_floatable :: Ct -> Bool is_floatable ct = isEqPred pred && skol_set disjointVarSet tyVarsOfType pred where pred = ctPred ct  Simon Peyton Jones committed Sep 01, 2012 832 833 834 835 836 promoteTyVars :: Cts -> TcS () promoteTyVars cts = do { untch <- TcSMonad.getUntouchables ; mapM_ (promote_tv untch) (varSetElems (tyVarsOfCts cts)) } where  Simon Peyton Jones committed Sep 01, 2012 837 838 839 840 841 842 843 844  promote_tv untch tv | isFloatedTouchableMetaTyVar untch tv = do { cloned_tv <- TcSMonad.cloneMetaTyVar tv ; let rhs_tv = setMetaTyVarUntouchables cloned_tv untch ; setWantedTyBind tv (mkTyVarTy rhs_tv) } | otherwise = return ()  Simon Peyton Jones committed Aug 28, 2012 845 846 847 848 849 850 851 852 853 growSkols :: WantedConstraints -> VarSet -> VarSet -- Find all the type variables that might possibly be unified -- with a type that mentions a skolem. This test is very conservative. -- I don't *think* we need look inside the implications, because any -- relevant unification variables in there are untouchable. growSkols (WC { wc_flat = flats }) skols = growThetaTyVars theta skols where theta = foldrBag ((:) . ctPred) [] flats  Simon Peyton Jones committed Sep 01, 2012 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878  approximateWC :: WantedConstraints -> Cts -- Postcondition: Wanted or Derived Cts approximateWC wc = float_wc emptyVarSet wc where float_wc :: TcTyVarSet -> WantedConstraints -> Cts float_wc skols (WC { wc_flat = flat, wc_impl = implic }) = floats1 unionBags floats2 where floats1 = do_bag (float_flat skols) flat floats2 = do_bag (float_implic skols) implic float_implic :: TcTyVarSet -> Implication -> Cts float_implic skols imp = float_wc skols' (ic_wanted imp) where skols' = skols extendVarSetList ic_skols imp extendVarSetList ic_fsks imp float_flat :: TcTyVarSet -> Ct -> Cts float_flat skols ct | tyVarsOfCt ct disjointVarSet skols = singleCt ct | otherwise = emptyCts do_bag :: (a -> Bag c) -> Bag a -> Bag c do_bag f = foldrBag (unionBags.f) emptyBag \end{code}  lewie committed Mar 02, 2000 879 \end{code}  partain committed Jan 08, 1996 880   simonpj@microsoft.com committed Feb 14, 2011 881 882 Note [Float Equalities out of Implications] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  dimitris committed Jun 08, 2012 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 For ordinary pattern matches (including existentials) we float equalities out of implications, for instance: data T where MkT :: Eq a => a -> T f x y = case x of MkT _ -> (y::Int) We get the implication constraint (x::T) (y::alpha): forall a. [untouchable=alpha] Eq a => alpha ~ Int We want to float out the equality into a scope where alpha is no longer untouchable, to solve the implication! But we cannot float equalities out of implications whose givens may yield or contain equalities: data T a where T1 :: T Int T2 :: T Bool T3 :: T a h :: T a -> a -> Int f x y = case x of T1 -> y::Int T2 -> y::Bool T3 -> h x y We generate constraint, for (x::T alpha) and (y :: beta): [untouchables = beta] (alpha ~ Int => beta ~ Int) -- From 1st branch [untouchables = beta] (alpha ~ Bool => beta ~ Bool) -- From 2nd branch (alpha ~ beta) -- From 3rd branch If we float the equality (beta ~ Int) outside of the first implication and the equality (beta ~ Bool) out of the second we get an insoluble constraint. But if we just leave them inside the implications we unify alpha := beta and solve everything. Principle: We do not want to float equalities out which may need the given *evidence* to become soluble. Consequence: classes with functional dependencies don't matter (since there is no evidence for a fundep equality), but equality superclasses do matter (since they carry evidence). Notice that, due to Note [Extra TcSTv Untouchables], the free unification variables of an equality that is floated out of an implication become effectively untouchables for the leftover implication. This is absolutely necessary. Consider the following example. We start with two implications and a class with a functional dependency.  Simon Peyton Jones committed Aug 28, 2012 931 932 933 934 935  class C x y | x -> y instance C [a] [a] (I1) [untch=beta]forall b. 0 => F Int ~ [beta] (I2) [untch=beta]forall c. 0 => F Int ~ [[alpha]] /\ C beta [c]  dimitris committed Jun 08, 2012 936 937 938 939 940 941 942  We float (F Int ~ [beta]) out of I1, and we float (F Int ~ [[alpha]]) out of I2. They may react to yield that (beta := [alpha]) which can then be pushed inwards the leftover of I2 to get (C [alpha] [a]) which, using the FunDep, will mean that (alpha := a). In the end we will have the skolem 'b' escaping in the untouchable beta! Concrete example is in indexed_types/should_fail/ExtraTcsUntch.hs:  Simon Peyton Jones committed Aug 28, 2012 943 944 945 946 947 948 949 950 951 952 953 954 955  class C x y | x -> y where op :: x -> y -> () instance C [a] [a] type family F a :: * h :: F Int -> () h = undefined data TEx where TEx :: a -> TEx  dimitris committed Jun 08, 2012 956   Simon Peyton Jones committed Aug 28, 2012 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971  f (x::beta) = let g1 :: forall b. b -> () g1 _ = h [x] g2 z = case z of TEx y -> (h [[undefined]], op x [y]) in (g1 '3', g2 undefined) Note [Extra TcsTv untouchables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 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  dimitris committed Jun 08, 2012 972   Simon Peyton Jones committed Aug 28, 2012 973 974  (iii) Touchables that have been floated out from some nested implications, see Note [Float Equalities out of Implications].  dimitris committed Jun 08, 2012 975   Simon Peyton Jones committed Aug 28, 2012 976 977 978 979 980 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 seeing'' some unification. Example (from Trac #4494):  dimitris committed Jun 08, 2012 981   Simon Peyton Jones committed Aug 28, 2012 982  (F Int ~ uf) /\ [untch=beta](forall a. C a => F Int ~ beta)  dimitris committed Jun 08, 2012 983   Simon Peyton Jones committed Aug 28, 2012 984 985 986 987 988 989 990 991 In this example, beta is touchable inside the implication. The first solveInteract step leaves 'uf' ununified. Then we move inside the implication where a new constraint uf ~ beta emerges. We may spontaneously solve it to get uf := beta, so the whole implication disappears but when we pop out again we are left with (F Int ~ uf) which will be unified by our final solveCTyFunEqs stage and uf will get unified *once more* to (F Int).  dimitris committed Jun 08, 2012 992   Simon Peyton Jones committed Aug 28, 2012 993 994 995 996 The solution is to record the unification variables of the flats, and make them untouchables for the nested implication. In the example above uf would become untouchable, so beta would be forced to be unified as beta := uf.  simonpj@microsoft.com committed Sep 13, 2010 997   Simon Peyton Jones committed Aug 28, 2012 998 \begin{code}  dimitris committed Jul 19, 2012 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 unFlattenWC :: WantedConstraints -> TcS WantedConstraints unFlattenWC wc = do { (subst, remaining_unsolved_flats) <- solveCTyFunEqs (wc_flat wc) -- See Note [Solving Family Equations] -- NB: remaining_flats has already had subst applied ; return $WC { wc_flat = mapBag (substCt subst) remaining_unsolved_flats , wc_impl = mapBag (substImplication subst) (wc_impl wc) , wc_insol = mapBag (substCt subst) (wc_insol wc) } } where solveCTyFunEqs :: Cts -> TcS (TvSubst, Cts) -- Default equalities (F xi ~ alpha) by setting (alpha := F xi), whenever possible -- See Note [Solving Family Equations] -- Returns: a bunch of unsolved constraints from the original Cts and implications -- where the newly generated equalities (alpha := F xi) have been substituted through. solveCTyFunEqs cts  Simon Peyton Jones committed Aug 28, 2012 1016  = do { untch <- TcSMonad.getUntouchables  dimitris committed Jul 19, 2012 1017 1018  ; let (unsolved_can_cts, (ni_subst, cv_binds)) = getSolvableCTyFunEqs untch cts  Simon Peyton Jones committed Aug 28, 2012 1019 1020 1021 1022 1023  ; traceTcS "defaultCTyFunEqs" (vcat [ text "Trying to default family equations:" , text "untch" <+> ppr untch , text "subst" <+> ppr ni_subst , text "binds" <+> ppr cv_binds , ppr unsolved_can_cts  dimitris committed Jul 19, 2012 1024 1025 1026 1027 1028  ]) ; mapM_ solve_one cv_binds ; return (niFixTvSubst ni_subst, unsolved_can_cts) } where  Simon Peyton Jones committed Aug 30, 2012 1029  solve_one (CtWanted { ctev_evar = cv }, tv, ty)  dimitris committed Jul 19, 2012 1030  = setWantedTyBind tv ty >> setEvBind cv (EvCoercion (mkTcReflCo ty))  Simon Peyton Jones committed Aug 30, 2012 1031  solve_one (CtDerived {}, tv, ty)  dimitris committed Jul 19, 2012 1032 1033 1034 1035  = setWantedTyBind tv ty solve_one arg = pprPanic "solveCTyFunEqs: can't solve a /given/ family equation!"$ ppr arg  simonpj@microsoft.com committed Jan 12, 2011 1036 ------------  Simon Peyton Jones committed May 07, 2012 1037 type FunEqBinds = (TvSubstEnv, [(CtEvidence, TcTyVar, TcType)])  simonpj@microsoft.com committed Jan 12, 2011 1038 1039 1040 1041 1042  -- The TvSubstEnv is not idempotent, but is loop-free -- See Note [Non-idempotent substitution] in Unify emptyFunEqBinds :: FunEqBinds emptyFunEqBinds = (emptyVarEnv, [])  Simon Peyton Jones committed May 07, 2012 1043 extendFunEqBinds :: FunEqBinds -> CtEvidence -> TcTyVar -> TcType -> FunEqBinds  dimitris committed Mar 28, 2012 1044 1045 extendFunEqBinds (tv_subst, cv_binds) fl tv ty = (extendVarEnv tv_subst tv ty, (fl, tv, ty):cv_binds)  simonpj@microsoft.com committed Jan 12, 2011 1046 1047  ------------  Simon Peyton Jones committed Aug 28, 2012 1048 getSolvableCTyFunEqs :: Untouchables  dimitris committed Nov 16, 2011 1049 1050  -> Cts -- Precondition: all Wanteds or Derived! -> (Cts, FunEqBinds) -- Postcondition: returns the unsolvables  simonpj@microsoft.com committed Nov 12, 2010 1051 getSolvableCTyFunEqs untch cts  dimitris committed Nov 16, 2011 1052  = Bag.foldlBag dflt_funeq (emptyCts, emptyFunEqBinds) cts  simonpj@microsoft.com committed Jan 12, 2011 1053  where  dimitris committed Nov 16, 2011 1054 1055  dflt_funeq :: (Cts, FunEqBinds) -> Ct -> (Cts, FunEqBinds)  simonpj@microsoft.com committed Jan 12, 2011 1056  dflt_funeq (cts_in, feb@(tv_subst, _))  Simon Peyton Jones committed May 07, 2012 1057  (CFunEqCan { cc_ev = fl  simonpj@microsoft.com committed Jan 12, 2011 1058 1059 1060 1061 1062  , cc_fun = tc , cc_tyargs = xis , cc_rhs = xi })