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

9 10 11
-- Type definitions for the constraint solver
module TcSMonad ( 

12
       -- Canonical constraints, definition is now in TcRnTypes
13

14 15 16
    WorkList(..), isEmptyWorkList, emptyWorkList,
    workListFromEq, workListFromNonEq, workListFromCt, 
    extendWorkListEq, extendWorkListNonEq, extendWorkListCt, 
dimitris's avatar
dimitris committed
17
    appendWorkListCt, appendWorkListEqs, unionWorkList, selectWorkItem,
18

19 20 21 22
    getTcSWorkList, updWorkListTcS, updWorkListTcS_return, keepWanted,

    Ct(..), Xi, tyVarsOfCt, tyVarsOfCts, tyVarsOfCDicts, 
    emitFrozenError,
23

dimitris's avatar
dimitris committed
24 25 26
    isWanted, isGivenOrSolved, isDerived,
    isGivenOrSolvedCt, isGivenCt_maybe, 
    isWantedCt, isDerivedCt, pprFlavorArising,
27

28 29
    isFlexiTcsTv,

30
    canRewrite, canSolve,
dimitris's avatar
dimitris committed
31 32
    combineCtLoc, mkSolvedFlavor, mkGivenFlavor,
    mkWantedFlavor,
33
    getWantedLoc,
34

35
    TcS, runTcS, failTcS, panicTcS, traceTcS, -- Basic functionality 
36 37 38 39
    traceFireTcS, bumpStepCountTcS, doWithInert,
    tryTcS, nestImplicTcS, recoverTcS,
    wrapErrTcS, wrapWarnTcS,

40 41
    SimplContext(..), isInteractive, simplEqsOnly, performDefaulting,

42
       -- Creation of evidence variables
43 44 45 46
    newEvVar, forceNewEvVar, delCachedEvVar, updateFlatCache, flushFlatCache,
    newGivenEqVar,
    newEqVar, newKindConstraint,
    EvVarCreated (..), isNewEvVar, FlatEqOrigin ( .. ), origin_matches,
47 48

       -- Setting evidence variables 
batterseapower's avatar
batterseapower committed
49 50
    setEqBind,
    setEvBind,
51 52 53

    setWantedTyBind,

54
    getInstEnvs, getFamInstEnvs,                -- Getting the environments
55
    getTopEnv, getGblEnv, getTcEvBinds, getUntouchables,
56 57
    getTcEvBindsMap, getTcSContext, getTcSTyBinds, getTcSTyBindsMap,
    getTcSEvVarCacheMap, getTcSEvVarFlatCache, setTcSEvVarCacheMap, pprEvVarCache,
58 59

    newFlattenSkolemTy,                         -- Flatten skolems 
60

61 62
        -- Inerts 
    InertSet(..), 
63
    getInertEqs, liftInertEqsTy, getCtCoercion,
64 65 66 67 68 69
    emptyInert, getTcSInerts, updInertSet, extractUnsolved,
    extractUnsolvedTcS, modifyInertTcS,
    updInertSetTcS, partitionCCanMap, partitionEqMap,
    getRelevantCts, extractRelevantInerts,
    CCanMap (..), CtTypeMap, pprCtTypeMap, mkPredKeyForTypeMap, partitionCtTypeMap,

70 71

    instDFunTypes,                              -- Instantiation
72
    instDFunConstraints,          
73
    newFlexiTcSTy, instFlexiTcS,
74

dreixel's avatar
dreixel committed
75
    compatKind, compatKindTcS, isSubKindTcS, unifyKindTcS,
76

77
    TcsUntouchables,
78
    isTouchableMetaTyVar,
79
    isTouchableMetaTyVar_InRange, 
80 81 82 83 84 85

    getDefaultInfo, getDynFlags,

    matchClass, matchFam, MatchInstResult (..), 
    checkWellStagedDFun, 
    warnTcS,
86
    pprEq                                    -- Smaller utils, re-exported from TcM
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
                                             -- TODO (DV): these are only really used in the 
                                             -- instance matcher in TcSimplify. I am wondering
                                             -- if the whole instance matcher simply belongs
                                             -- here 
) where 

#include "HsVersions.h"

import HscTypes
import BasicTypes 

import Inst
import InstEnv 
import FamInst 
import FamInstEnv

import qualified TcRnMonad as TcM
import qualified TcMType as TcM
import qualified TcEnv as TcM 
106
       ( checkWellStaged, topIdLvl, tcGetDefaultTys )
dreixel's avatar
dreixel committed
107
import {-# SOURCE #-} qualified TcUnify as TcM ( unifyKindEq, mkKindErrorCtxt )
108
import Kind
109 110
import TcType
import DynFlags
111
import Type
112

113
import TcEvidence
114 115
import Class
import TyCon
116 117
import TypeRep 

118 119
import Name
import Var
120
import VarEnv
121 122 123 124
import Outputable
import Bag
import MonadUtils
import VarSet
125

126
import FastString
Ian Lynagh's avatar
Ian Lynagh committed
127
import Util
128
import Id 
Ian Lynagh's avatar
Ian Lynagh committed
129
import TcRnTypes
130

131 132 133 134 135 136
import Unique 
import UniqFM
import Maybes ( orElse )

import Control.Monad( when )
import StaticFlags( opt_PprStyle_Debug )
Ian Lynagh's avatar
Ian Lynagh committed
137
import Data.IORef
138

139
import TrieMap
140

141
\end{code}
142

143

144
\begin{code}
145 146
compatKind :: Kind -> Kind -> Bool
compatKind k1 k2 = k1 `isSubKind` k2 || k2 `isSubKind` k1 
147

dreixel's avatar
dreixel committed
148 149 150 151 152 153 154 155 156 157
compatKindTcS :: Kind -> Kind -> TcS Bool
-- Because kind unification happens during constraint solving, we have
-- to make sure that two kinds are zonked before we compare them.
compatKindTcS k1 k2 = wrapTcS (TcM.compatKindTcM k1 k2)

isSubKindTcS :: Kind -> Kind -> TcS Bool
isSubKindTcS k1 k2 = wrapTcS (TcM.isSubKindTcM k1 k2)

unifyKindTcS :: Type -> Type     -- Context
             -> Kind -> Kind     -- Corresponding kinds
158
             -> TcS Bool
dreixel's avatar
dreixel committed
159
unifyKindTcS ty1 ty2 ki1 ki2
160 161 162
  = wrapTcS $ TcM.addErrCtxtM ctxt $ do
      (_errs, mb_r) <- TcM.tryTc (TcM.unifyKindEq ki1 ki2)
      return (maybe False (const True) mb_r)
163 164
  where 
    ctxt = TcM.mkKindErrorCtxt ty1 ki1 ty2 ki2
165 166
\end{code}

167 168 169 170 171 172 173 174
%************************************************************************
%*									*
%*                            Worklists                                *
%*  Canonical and non-canonical constraints that the simplifier has to  *
%*  work on. Including their simplification depths.                     *
%*                                                                      *
%*									*
%************************************************************************
175

176 177
Note [WorkList]
~~~~~~~~~~~~~~~
178

179 180 181
A WorkList contains canonical and non-canonical items (of all flavors). 
Notice that each Ct now has a simplification depth. We may 
consider using this depth for prioritization as well in the future. 
182

183 184 185 186 187
As a simple form of priority queue, our worklist separates out
equalities (wl_eqs) from the rest of the canonical constraints, 
so that it's easier to deal with them first, but the separation 
is not strictly necessary. Notice that non-canonical constraints 
are also parts of the worklist. 
188

189 190 191 192 193 194
Note [NonCanonical Semantics]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Note that canonical constraints involve a CNonCanonical constructor. In the worklist
we use this constructor for constraints that have not yet been canonicalized such as 
   [Int] ~ [a] 
In other words, all constraints start life as NonCanonicals. 
195

196 197
On the other hand, in the Inert Set (see below) the presence of a NonCanonical somewhere
means that we have a ``frozen error''. 
198

199 200 201
NonCanonical constraints never interact directly with other constraints -- but they can
be rewritten by equalities (for instance if a non canonical exists in the inert, we'd 
better rewrite it as much as possible before reporting it as an error to the user)
202

203
\begin{code}
204

205
-- See Note [WorkList]
dimitris's avatar
dimitris committed
206
data WorkList = WorkList { wl_eqs  :: [Ct], wl_funeqs :: [Ct], wl_rest :: [Ct] }
207

batterseapower's avatar
batterseapower committed
208

209 210
unionWorkList :: WorkList -> WorkList -> WorkList
unionWorkList new_wl orig_wl = 
dimitris's avatar
dimitris committed
211 212 213
   WorkList { wl_eqs    = wl_eqs new_wl ++ wl_eqs orig_wl
            , wl_funeqs = wl_funeqs new_wl ++ wl_funeqs orig_wl
            , wl_rest   = wl_rest new_wl ++ wl_rest orig_wl }
214

215 216
extendWorkListEq :: Ct -> WorkList -> WorkList
-- Extension by equality
dimitris's avatar
dimitris committed
217 218 219 220 221
extendWorkListEq ct wl 
  | Just {} <- isCFunEqCan_Maybe ct
  = wl { wl_funeqs = ct : wl_funeqs wl }
  | otherwise
  = wl { wl_eqs = ct : wl_eqs wl }
222

223 224 225
extendWorkListNonEq :: Ct -> WorkList -> WorkList
-- Extension by non equality
extendWorkListNonEq ct wl = wl { wl_rest = ct : wl_rest wl }
226

227 228 229
extendWorkListCt :: Ct -> WorkList -> WorkList
-- Agnostic
extendWorkListCt ct wl
230
 | isEqVar (cc_id ct) = extendWorkListEq ct wl
231
 | otherwise = extendWorkListNonEq ct wl
232

233 234 235
appendWorkListCt :: [Ct] -> WorkList -> WorkList
-- Agnostic
appendWorkListCt cts wl = foldr extendWorkListCt wl cts
236

237 238 239
appendWorkListEqs :: [Ct] -> WorkList -> WorkList
-- Append a list of equalities
appendWorkListEqs cts wl = foldr extendWorkListEq wl cts
240 241

isEmptyWorkList :: WorkList -> Bool
dimitris's avatar
dimitris committed
242 243
isEmptyWorkList wl 
  = null (wl_eqs wl) &&  null (wl_rest wl) && null (wl_funeqs wl)
244 245

emptyWorkList :: WorkList
dimitris's avatar
dimitris committed
246
emptyWorkList = WorkList { wl_eqs  = [], wl_rest = [], wl_funeqs = []}
247

248
workListFromEq :: Ct -> WorkList
dimitris's avatar
dimitris committed
249
workListFromEq ct = extendWorkListEq ct emptyWorkList
250

251
workListFromNonEq :: Ct -> WorkList
dimitris's avatar
dimitris committed
252
workListFromNonEq ct = extendWorkListNonEq ct emptyWorkList
253

254 255
workListFromCt :: Ct -> WorkList
-- Agnostic 
256 257
workListFromCt ct | isEqVar (cc_id ct) = workListFromEq ct 
                  | otherwise          = workListFromNonEq ct
258

dimitris's avatar
dimitris committed
259 260 261 262 263 264 265 266 267

selectWorkItem :: WorkList -> (Maybe Ct, WorkList)
selectWorkItem wl@(WorkList { wl_eqs = eqs, wl_funeqs = feqs, wl_rest = rest })
  = case (eqs,feqs,rest) of
      (ct:cts,_,_)     -> (Just ct, wl { wl_eqs    = cts })
      (_,(ct:cts),_)   -> (Just ct, wl { wl_funeqs = cts })
      (_,_,(ct:cts))   -> (Just ct, wl { wl_rest   = cts })
      (_,_,_)          -> (Nothing,wl)

268 269 270
-- Pretty printing 
instance Outputable WorkList where 
  ppr wl = vcat [ text "WorkList (eqs)   = " <+> ppr (wl_eqs wl)
dimitris's avatar
dimitris committed
271
                , text "WorkList (funeqs)= " <+> ppr (wl_funeqs wl)
272 273
                , text "WorkList (rest)  = " <+> ppr (wl_rest wl)
                ]
274

275 276 277 278 279
keepWanted :: Cts -> Cts
keepWanted = filterBag isWantedCt
    -- DV: there used to be a note here that read: 
    -- ``Important: use fold*r*Bag to preserve the order of the evidence variables'' 
    -- DV: Is this still relevant? 
280

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
\end{code}

%************************************************************************
%*									*
%*                            Inert sets                                *
%*                                                                      *
%*									*
%************************************************************************


Note [InertSet invariants]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
An InertSet is a bag of canonical constraints, with the following invariants:

  1 No two constraints react with each other. 
    
    A tricky case is when there exists a given (solved) dictionary 
    constraint and a wanted identical constraint in the inert set, but do 
    not react because reaction would create loopy dictionary evidence for 
    the wanted. See note [Recursive dictionaries]
301

302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
  2 Given equalities form an idempotent substitution [none of the
    given LHS's occur in any of the given RHS's or reactant parts]

  3 Wanted equalities also form an idempotent substitution

  4 The entire set of equalities is acyclic.

  5 Wanted dictionaries are inert with the top-level axiom set 

  6 Equalities of the form tv1 ~ tv2 always have a touchable variable
    on the left (if possible).

  7 No wanted constraints tv1 ~ tv2 with tv1 touchable. Such constraints
    will be marked as solved right before being pushed into the inert set. 
    See note [Touchables and givens].

  8 No Given constraint mentions a touchable unification variable, but 
    Given/Solved may do so. 

  9 Given constraints will also have their superclasses in the inert set, 
    but Given/Solved will not. 
 
Note that 6 and 7 are /not/ enforced by canonicalization but rather by 
insertion in the inert list, ie by TcInteract. 

During the process of solving, the inert set will contain some
previously given constraints, some wanted constraints, and some given
constraints which have arisen from solving wanted constraints. For
now we do not distinguish between given and solved constraints.

Note that we must switch wanted inert items to given when going under an
implication constraint (when in top-level inference mode).

\begin{code}

data CCanMap a = CCanMap { cts_given   :: UniqFM Cts
                                          -- Invariant: all Given
                         , cts_derived :: UniqFM Cts 
                                          -- Invariant: all Derived
                         , cts_wanted  :: UniqFM Cts } 
                                          -- Invariant: all Wanted

cCanMapToBag :: CCanMap a -> Cts 
cCanMapToBag cmap = foldUFM unionBags rest_wder (cts_given cmap)
  where rest_wder = foldUFM unionBags rest_der  (cts_wanted cmap) 
        rest_der  = foldUFM unionBags emptyCts  (cts_derived cmap)

emptyCCanMap :: CCanMap a 
emptyCCanMap = CCanMap { cts_given = emptyUFM, cts_derived = emptyUFM, cts_wanted = emptyUFM } 

updCCanMap:: Uniquable a => (a,Ct) -> CCanMap a -> CCanMap a 
updCCanMap (a,ct) cmap 
  = case cc_flavor ct of 
      Wanted {}  -> cmap { cts_wanted  = insert_into (cts_wanted cmap)  } 
      Given {}   -> cmap { cts_given   = insert_into (cts_given cmap)   }
      Derived {} -> cmap { cts_derived = insert_into (cts_derived cmap) }
  where 
    insert_into m = addToUFM_C unionBags m a (singleCt ct)

getRelevantCts :: Uniquable a => a -> CCanMap a -> (Cts, CCanMap a) 
-- Gets the relevant constraints and returns the rest of the CCanMap
getRelevantCts a cmap 
    = let relevant = lookup (cts_wanted cmap) `unionBags`
                     lookup (cts_given cmap)  `unionBags`
                     lookup (cts_derived cmap) 
          residual_map = cmap { cts_wanted  = delFromUFM (cts_wanted cmap) a
                              , cts_given   = delFromUFM (cts_given cmap) a
                              , cts_derived = delFromUFM (cts_derived cmap) a }
      in (relevant, residual_map) 
  where
    lookup map = lookupUFM map a `orElse` emptyCts


getCtTypeMapRelevants :: PredType -> TypeMap Ct -> (Cts, TypeMap Ct)
getCtTypeMapRelevants key_pty tmap
  = partitionCtTypeMap (\ct -> mkPredKeyForTypeMap ct `eqType` key_pty) tmap


partitionCCanMap :: (Ct -> Bool) -> CCanMap a -> (Cts,CCanMap a) 
-- All constraints that /match/ the predicate go in the bag, the rest remain in the map
partitionCCanMap pred cmap
  = let (ws_map,ws) = foldUFM_Directly aux (emptyUFM,emptyCts) (cts_wanted cmap) 
        (ds_map,ds) = foldUFM_Directly aux (emptyUFM,emptyCts) (cts_derived cmap)
        (gs_map,gs) = foldUFM_Directly aux (emptyUFM,emptyCts) (cts_given cmap) 
    in (ws `andCts` ds `andCts` gs, cmap { cts_wanted  = ws_map
                                         , cts_given   = gs_map
                                         , cts_derived = ds_map }) 
  where aux k this_cts (mp,acc_cts) = (new_mp, new_acc_cts)
                                    where new_mp      = addToUFM mp k cts_keep
                                          new_acc_cts = acc_cts `andCts` cts_out
                                          (cts_out, cts_keep) = partitionBag pred this_cts

394
partitionEqMap :: (Ct -> Bool) -> TyVarEnv (Ct,TcCoercion) -> ([Ct], TyVarEnv (Ct,TcCoercion))
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
partitionEqMap pred isubst 
  = let eqs_out = foldVarEnv extend_if_pred [] isubst
        eqs_in  = filterVarEnv_Directly (\_ (ct,_) -> not (pred ct)) isubst
    in (eqs_out, eqs_in)
  where extend_if_pred (ct,_) cts = if pred ct then ct : cts else cts


extractUnsolvedCMap :: CCanMap a -> (Cts, CCanMap a)
-- Gets the wanted or derived constraints and returns a residual
-- CCanMap with only givens.
extractUnsolvedCMap cmap =
  let wntd = foldUFM unionBags emptyCts (cts_wanted cmap)
      derd = foldUFM unionBags emptyCts (cts_derived cmap)
  in (wntd `unionBags` derd, 
      cmap { cts_wanted = emptyUFM, cts_derived = emptyUFM })

-- See Note [InertSet invariants]
data InertSet 
413
  = IS { inert_eqs     :: TyVarEnv (Ct,TcCoercion) 
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
         -- Must all be CTyEqCans! If an entry exists of the form: 
         --   a |-> ct,co
         -- Then ct = CTyEqCan { cc_tyvar = a, cc_rhs = xi } 
         -- And  co : a ~ xi
       , inert_eq_tvs  :: InScopeSet -- Invariant: superset of inert_eqs tvs

       , inert_dicts        :: CCanMap Class -- Dictionaries only, index is the class
       , inert_ips          :: CCanMap (IPName Name)      -- Implicit parameters 
         -- NB: We do not want to use TypeMaps here because functional dependencies
         -- will only match on the class but not the type. Similarly IPs match on the
         -- name but not on the whole datatype

       , inert_funeqs       :: CtTypeMap -- Map from family heads to CFunEqCan constraints

       , inert_irreds       :: Cts  -- Irreducible predicates
       , inert_frozen       :: Cts  -- All non-canonicals are kept here (as frozen errors)
       }


type CtTypeMap = TypeMap Ct

pprCtTypeMap :: TypeMap Ct -> SDoc 
pprCtTypeMap ctmap = ppr (foldTM (:) ctmap [])

ctTypeMapCts :: TypeMap Ct -> Cts
ctTypeMapCts ctmap = foldTM (\ct cts -> extendCts cts ct) ctmap emptyCts

mkPredKeyForTypeMap :: Ct -> PredType
-- Create a key from a constraint to use in the inert CtTypeMap.
-- The only interesting case is for family applications, where the 
-- key is not the whole PredType of cc_id, but rather the family 
-- equality left hand side (head)
mkPredKeyForTypeMap (CFunEqCan { cc_fun = fn, cc_tyargs = xis }) 
  = mkTyConApp fn xis
mkPredKeyForTypeMap ct 
  = evVarPred (cc_id ct)

partitionCtTypeMap :: (Ct -> Bool)
                   -> TypeMap Ct -> (Cts, TypeMap Ct)
-- Kick out the ones that match the predicate and keep the rest in the typemap
partitionCtTypeMap f ctmap
  = foldTM upd_acc ctmap (emptyBag,ctmap)
  where upd_acc ct (cts,acc_map)
         | f ct      = (extendCts cts ct, alterTM ct_key (\_ -> Nothing) acc_map)
         | otherwise = (cts,acc_map)
         where ct_key = mkPredKeyForTypeMap ct


instance Outputable InertSet where
  ppr is = vcat [ vcat (map ppr (varEnvElts (inert_eqs is)))
                , vcat (map ppr (Bag.bagToList $ inert_irreds is)) 
                , vcat (map ppr (Bag.bagToList $ cCanMapToBag (inert_dicts is)))
                , vcat (map ppr (Bag.bagToList $ cCanMapToBag (inert_ips is))) 
                , vcat (map ppr (Bag.bagToList $ ctTypeMapCts (inert_funeqs is)))
                , text "Frozen errors =" <+> -- Clearly print frozen errors
                    braces (vcat (map ppr (Bag.bagToList $ inert_frozen is)))
                , text "Warning: Not displaying cached (solved) constraints"
                ]
                       
emptyInert :: InertSet
emptyInert = IS { inert_eqs     = emptyVarEnv
                , inert_eq_tvs  = emptyInScopeSet
                , inert_frozen  = emptyCts
                , inert_irreds  = emptyCts
                , inert_dicts   = emptyCCanMap
                , inert_ips     = emptyCCanMap
                , inert_funeqs  = emptyTM
                }


type AtomicInert = Ct 

updInertSet :: InertSet -> AtomicInert -> InertSet 
-- Add a new inert element to the inert set. 
updInertSet is item 
  | isCTyEqCan item                     
490 491 492 493 494
  = let upd_err a b = pprPanic "updInertSet" $
                      vcat [ text "Multiple inert equalities:"
                           , text "Old (already inert):" <+> ppr a
                           , text "Trying to insert   :" <+> ppr b
                           ]
495 496
                           
        -- If evidence is cached, pick it up from the flavor!
497
        coercion = getCtCoercion item
498

499 500
        eqs'     = extendVarEnv_C upd_err (inert_eqs is)
                                          (cc_tyvar item)
501
                                          (item, coercion)
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
        inscope' = extendInScopeSetSet (inert_eq_tvs is) (tyVarsOfCt item)
    in is { inert_eqs = eqs', inert_eq_tvs = inscope' }

  | Just x  <- isCIPCan_Maybe item      -- IP 
  = is { inert_ips   = updCCanMap (x,item) (inert_ips is) }  
  | isCIrredEvCan item                  -- Presently-irreducible evidence
  = is { inert_irreds = inert_irreds is `Bag.snocBag` item }


  | Just cls <- isCDictCan_Maybe item   -- Dictionary 
  = is { inert_dicts = updCCanMap (cls,item) (inert_dicts is) }

  | Just _tc <- isCFunEqCan_Maybe item  -- Function equality
  = let pty = mkPredKeyForTypeMap item
        upd_funeqs Nothing = Just item
        upd_funeqs (Just _alredy_there) = panic "updInertSet: item already there!"
    in is { inert_funeqs = alterTM pty upd_funeqs (inert_funeqs is) }
     
  | otherwise 
  = is { inert_frozen = inert_frozen is `Bag.snocBag` item }

updInertSetTcS :: AtomicInert -> TcS ()
-- Add a new item in the inerts of the monad
updInertSetTcS item
  = do { traceTcS "updInertSetTcs {" $ 
         text "Trying to insert new inert item:" <+> ppr item

       ; modifyInertTcS (\is -> ((), updInertSet is item)) 
                        
       ; traceTcS "updInertSetTcs }" $ empty }


modifyInertTcS :: (InertSet -> (a,InertSet)) -> TcS a 
-- Modify the inert set with the supplied function
modifyInertTcS upd 
  = do { is_var <- getTcSInertsRef
       ; curr_inert <- wrapTcS (TcM.readTcRef is_var)
       ; let (a, new_inert) = upd curr_inert
       ; wrapTcS (TcM.writeTcRef is_var new_inert)
       ; return a }

extractUnsolvedTcS :: TcS (Cts,Cts) 
-- Extracts frozen errors and remaining unsolved and sets the 
-- inert set to be the remaining! 
extractUnsolvedTcS = 
  modifyInertTcS extractUnsolved 

extractUnsolved :: InertSet -> ((Cts,Cts), InertSet)
-- Postcondition
-- -------------
-- When: 
--   ((frozen,cts),is_solved) <- extractUnsolved inert
-- Then: 
-- -----------------------------------------------------------------------------
--  cts       |  The unsolved (Derived or Wanted only) residual 
--            |  canonical constraints, that is, no CNonCanonicals.
-- -----------|-----------------------------------------------------------------
--  frozen    | The CNonCanonicals of the original inert (frozen errors), 
--            | of all flavors
-- -----------|-----------------------------------------------------------------
--  is_solved | Whatever remains from the inert after removing the previous two. 
-- -----------------------------------------------------------------------------
extractUnsolved is@(IS {inert_eqs = eqs, inert_irreds = irreds}) 
  = let is_solved  = is { inert_eqs    = solved_eqs
                        , inert_eq_tvs = inert_eq_tvs is
                        , inert_dicts  = solved_dicts
                        , inert_ips    = solved_ips
                        , inert_irreds = solved_irreds
                        , inert_frozen = emptyCts
                        , inert_funeqs = solved_funeqs
                        }
    in ((inert_frozen is, unsolved), is_solved)

  where solved_eqs = filterVarEnv_Directly (\_ (ct,_) -> isGivenOrSolvedCt ct) eqs
        unsolved_eqs = foldVarEnv (\(ct,_co) cts -> cts `extendCts` ct) emptyCts $
                       eqs `minusVarEnv` solved_eqs

        (unsolved_irreds, solved_irreds) = Bag.partitionBag (not.isGivenOrSolvedCt) irreds
        (unsolved_ips, solved_ips)       = extractUnsolvedCMap (inert_ips is) 
        (unsolved_dicts, solved_dicts)   = extractUnsolvedCMap (inert_dicts is) 

        (unsolved_funeqs, solved_funeqs) = extractUnsolvedCtTypeMap (inert_funeqs is)

        unsolved = unsolved_eqs `unionBags` unsolved_irreds `unionBags`
                   unsolved_ips `unionBags` unsolved_dicts `unionBags` unsolved_funeqs

extractUnsolvedCtTypeMap :: TypeMap Ct -> (Cts,TypeMap Ct)
extractUnsolvedCtTypeMap
  = partitionCtTypeMap (not . isGivenOrSolved . cc_flavor)


extractRelevantInerts :: Ct -> TcS Cts
-- Returns the constraints from the inert set that are 'relevant' to react with 
-- this constraint. The monad is left with the 'thinner' inerts. 
-- NB: This function contains logic specific to the constraint solver, maybe move there?
extractRelevantInerts wi 
  = modifyInertTcS (extract_inert_relevants wi)
  where extract_inert_relevants (CDictCan {cc_class = cl}) is = 
            let (cts,dict_map) = getRelevantCts cl (inert_dicts is) 
            in (cts, is { inert_dicts = dict_map })
        extract_inert_relevants (CFunEqCan {cc_fun = tc, cc_tyargs = xis}) is = 
            let (cts,feqs_map)  = getCtTypeMapRelevants (mkTyConApp tc xis) (inert_funeqs is)
            in (cts, is { inert_funeqs = feqs_map })
        extract_inert_relevants (CIPCan { cc_ip_nm = nm } ) is = 
            let (cts, ips_map) = getRelevantCts nm (inert_ips is) 
            in (cts, is { inert_ips = ips_map })
        extract_inert_relevants (CIrredEvCan { }) is = 
            let cts = inert_irreds is 
            in (cts, is { inert_irreds = emptyCts })
        extract_inert_relevants _ is = (emptyCts,is)
612 613
\end{code}

614 615


616

617 618 619 620 621 622 623 624
%************************************************************************
%*									*
                    CtFlavor
         The "flavor" of a canonical constraint
%*									*
%************************************************************************

\begin{code}
625
getWantedLoc :: Ct -> WantedLoc
626 627 628 629 630 631
getWantedLoc ct 
  = ASSERT (isWanted (cc_flavor ct))
    case cc_flavor ct of 
      Wanted wl -> wl 
      _         -> pprPanic "Can't get WantedLoc of non-wanted constraint!" empty

632
isWantedCt :: Ct -> Bool
633
isWantedCt ct = isWanted (cc_flavor ct)
634
isDerivedCt :: Ct -> Bool
635
isDerivedCt ct = isDerived (cc_flavor ct)
636

637
isGivenCt_maybe :: Ct -> Maybe GivenKind
dimitris's avatar
dimitris committed
638 639
isGivenCt_maybe ct = isGiven_maybe (cc_flavor ct)

640
isGivenOrSolvedCt :: Ct -> Bool
dimitris's avatar
dimitris committed
641 642 643
isGivenOrSolvedCt ct = isGivenOrSolved (cc_flavor ct)


644 645 646
canSolve :: CtFlavor -> CtFlavor -> Bool 
-- canSolve ctid1 ctid2 
-- The constraint ctid1 can be used to solve ctid2 
dimitris@microsoft.com's avatar
dimitris@microsoft.com committed
647 648 649 650 651
-- "to solve" means a reaction where the active parts of the two constraints match.
--  active(F xis ~ xi) = F xis 
--  active(tv ~ xi)    = tv 
--  active(D xis)      = D xis 
--  active(IP nm ty)   = nm 
652 653
--
-- NB:  either (a `canSolve` b) or (b `canSolve` a) must hold
dimitris@microsoft.com's avatar
dimitris@microsoft.com committed
654
-----------------------------------------
655
canSolve (Given {})   _            = True 
656
canSolve (Wanted {})  (Derived {}) = True
657
canSolve (Wanted {})  (Wanted {})  = True
658 659
canSolve (Derived {}) (Derived {}) = True  -- Important: derived can't solve wanted/given
canSolve _ _ = False  	       	     	   -- (There is no *evidence* for a derived.)
660

661 662
canRewrite :: CtFlavor -> CtFlavor -> Bool 
-- canRewrite ctid1 ctid2 
dimitris@microsoft.com's avatar
dimitris@microsoft.com committed
663
-- The *equality_constraint* ctid1 can be used to rewrite inside ctid2 
664
canRewrite = canSolve 
dimitris@microsoft.com's avatar
dimitris@microsoft.com committed
665

666 667
combineCtLoc :: CtFlavor -> CtFlavor -> WantedLoc
-- Precondition: At least one of them should be wanted 
dimitris's avatar
dimitris committed
668 669 670 671
combineCtLoc (Wanted loc) _    = loc
combineCtLoc _ (Wanted loc)    = loc
combineCtLoc (Derived loc ) _  = loc
combineCtLoc _ (Derived loc )  = loc
672
combineCtLoc _ _ = panic "combineCtLoc: both given"
673

674
mkSolvedFlavor :: CtFlavor -> SkolemInfo -> EvTerm -> CtFlavor
dimitris's avatar
dimitris committed
675
-- To be called when we actually solve a wanted/derived (perhaps leaving residual goals)
676 677 678
mkSolvedFlavor (Wanted  loc) sk  evterm  = Given (setCtLocOrigin loc sk) (GivenSolved (Just evterm))
mkSolvedFlavor (Derived loc) sk  evterm  = Given (setCtLocOrigin loc sk) (GivenSolved (Just evterm))
mkSolvedFlavor fl@(Given {}) _sk _evterm = pprPanic "Solving a given constraint!" $ ppr fl
679

dimitris's avatar
dimitris committed
680 681 682 683
mkGivenFlavor :: CtFlavor -> SkolemInfo -> CtFlavor
mkGivenFlavor (Wanted  loc) sk  = Given (setCtLocOrigin loc sk) GivenOrig
mkGivenFlavor (Derived loc) sk  = Given (setCtLocOrigin loc sk) GivenOrig
mkGivenFlavor fl@(Given {}) _sk = pprPanic "Solving a given constraint!" $ ppr fl
684 685

mkWantedFlavor :: CtFlavor -> CtFlavor
686 687
mkWantedFlavor (Wanted  loc) = Wanted loc
mkWantedFlavor (Derived loc) = Wanted loc
dimitris's avatar
dimitris committed
688
mkWantedFlavor fl@(Given {}) = pprPanic "mkWantedFlavor" (ppr fl)
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
\end{code}

%************************************************************************
%*									*
%*		The TcS solver monad                                    *
%*									*
%************************************************************************

Note [The TcS monad]
~~~~~~~~~~~~~~~~~~~~
The TcS monad is a weak form of the main Tc monad

All you can do is
    * fail
    * allocate new variables
    * fill in evidence variables

Filling in a dictionary evidence variable means to create a binding
for it, so TcS carries a mutable location where the binding can be
added.  This is initialised from the innermost implication constraint.

\begin{code}
data TcSEnv
  = TcSEnv { 
713 714 715 716
      tcs_ev_binds    :: EvBindsVar,
      tcs_evvar_cache :: IORef EvVarCache,
          -- Evidence bindings and a cache from predicate types to the created evidence 
          -- variables. The scope of the cache will be the same as the scope of tcs_ev_binds
717

718
      tcs_ty_binds :: IORef (TyVarEnv (TcTyVar, TcType)),
719 720
          -- Global type bindings

721
      tcs_context :: SimplContext,
722
                     
723 724
      tcs_untch :: TcsUntouchables,

dimitris's avatar
dimitris committed
725 726 727
      tcs_ic_depth   :: Int,       -- Implication nesting depth
      tcs_count      :: IORef Int, -- Global step count

728 729
      tcs_inerts   :: IORef InertSet, -- Current inert set
      tcs_worklist :: IORef WorkList  -- Current worklist
dimitris's avatar
dimitris committed
730 731


732 733 734
    -- TcSEnv invariant: the tcs_evvar_cache is a superset of tcs_inerts, tcs_worklist, tcs_ev_binds which must 
    --                   all be disjoint with each other.
    }
dimitris's avatar
dimitris committed
735

736 737 738 739
data EvVarCache
  = EvVarCache { evc_cache     :: TypeMap (EvVar,CtFlavor)    
                     -- Map from PredTys to Evidence variables
                     -- used to avoid creating new goals
740
               , evc_flat_cache :: TypeMap (TcCoercion,(Xi,CtFlavor,FlatEqOrigin))
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
                     -- Map from family-free heads (F xi) to family-free types.
                     -- Useful during flattening to share flatten skolem generation
                     -- The boolean flag:
                     --   True  <-> This equation was generated originally during flattening
                     --   False <-> This equation was generated by having solved a goal
               }

data FlatEqOrigin = WhileFlattening  -- Was it generated during flattening?
                  | WhenSolved       -- Was it generated when a family equation was solved?
                  | Any

origin_matches :: FlatEqOrigin -> FlatEqOrigin -> Bool
origin_matches Any _                           = True
origin_matches WhenSolved WhenSolved           = True
origin_matches WhileFlattening WhileFlattening = True
origin_matches _ _ = False
dimitris's avatar
dimitris committed
757 758


759 760 761 762
type TcsUntouchables = (Untouchables,TcTyVarSet)
-- Like the TcM Untouchables, 
-- but records extra TcsTv variables generated during simplification
-- See Note [Extra TcsTv untouchables] in TcSimplify
763 764 765
\end{code}

\begin{code}
766
data SimplContext
767 768 769 770
  = SimplInfer SDoc	   -- Inferring type of a let-bound thing
  | SimplRuleLhs RuleName  -- Inferring type of a RULE lhs
  | SimplInteractive	   -- Inferring type at GHCi prompt
  | SimplCheck SDoc	   -- Checking a type signature or RULE rhs
771 772

instance Outputable SimplContext where
773 774 775
  ppr (SimplInfer d)   = ptext (sLit "SimplInfer") <+> d
  ppr (SimplCheck d)   = ptext (sLit "SimplCheck") <+> d
  ppr (SimplRuleLhs n) = ptext (sLit "SimplRuleLhs") <+> doubleQuotes (ftext n)
776 777 778 779 780 781 782 783 784 785
  ppr SimplInteractive = ptext (sLit "SimplInteractive")

isInteractive :: SimplContext -> Bool
isInteractive SimplInteractive = True
isInteractive _                = False

simplEqsOnly :: SimplContext -> Bool
-- Simplify equalities only, not dictionaries
-- This is used for the LHS of rules; ee
-- Note [Simplifying RULE lhs constraints] in TcSimplify
786 787
simplEqsOnly (SimplRuleLhs {}) = True
simplEqsOnly _                 = False
788 789

performDefaulting :: SimplContext -> Bool
790 791 792 793
performDefaulting (SimplInfer {})   = False
performDefaulting (SimplRuleLhs {}) = False
performDefaulting SimplInteractive  = True
performDefaulting (SimplCheck {})   = True
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828

---------------
newtype TcS a = TcS { unTcS :: TcSEnv -> TcM a } 

instance Functor TcS where
  fmap f m = TcS $ fmap f . unTcS m

instance Monad TcS where 
  return x  = TcS (\_ -> return x) 
  fail err  = TcS (\_ -> fail err) 
  m >>= k   = TcS (\ebs -> unTcS m ebs >>= \r -> unTcS (k r) ebs)

-- Basic functionality 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
wrapTcS :: TcM a -> TcS a 
-- Do not export wrapTcS, because it promotes an arbitrary TcM to TcS,
-- and TcS is supposed to have limited functionality
wrapTcS = TcS . const -- a TcM action will not use the TcEvBinds

wrapErrTcS :: TcM a -> TcS a 
-- The thing wrapped should just fail
-- There's no static check; it's up to the user
-- Having a variant for each error message is too painful
wrapErrTcS = wrapTcS

wrapWarnTcS :: TcM a -> TcS a 
-- The thing wrapped should just add a warning, or no-op
-- There's no static check; it's up to the user
wrapWarnTcS = wrapTcS

failTcS, panicTcS :: SDoc -> TcS a
failTcS      = wrapTcS . TcM.failWith
panicTcS doc = pprPanic "TcCanonical" doc

traceTcS :: String -> SDoc -> TcS ()
829
traceTcS herald doc = wrapTcS (TcM.traceTc herald doc)
830

831 832 833 834 835
bumpStepCountTcS :: TcS ()
bumpStepCountTcS = TcS $ \env -> do { let ref = tcs_count env
                                    ; n <- TcM.readTcRef ref
                                    ; TcM.writeTcRef ref (n+1) }

836
traceFireTcS :: SubGoalDepth -> SDoc -> TcS ()
837 838 839 840 841 842 843 844 845
-- Dump a rule-firing trace
traceFireTcS depth doc 
  = TcS $ \env -> 
    TcM.ifDOptM Opt_D_dump_cs_trace $ 
    do { n <- TcM.readTcRef (tcs_count env)
       ; let msg = int n 
                <> text (replicate (tcs_ic_depth env) '>')
                <> brackets (int depth) <+> doc
       ; TcM.dumpTcRn msg }
846 847

runTcS :: SimplContext
848
       -> Untouchables 	       -- Untouchables
849 850
       -> InertSet             -- Initial inert set
       -> WorkList             -- Initial work list
851
       -> TcS a		       -- What to run
852
       -> TcM (a, Bag EvBind)
853
runTcS context untouch is wl tcs 
854
  = do { ty_binds_var <- TcM.newTcRef emptyVarEnv
855 856
       ; ev_cache_var <- TcM.newTcRef $ 
                         EvVarCache { evc_cache = emptyTM, evc_flat_cache = emptyTM }
857
       ; ev_binds_var@(EvBindsVar evb_ref _) <- TcM.newTcEvBinds
858
       ; step_count <- TcM.newTcRef 0
859 860 861 862

       ; inert_var <- TcM.newTcRef is 
       ; wl_var <- TcM.newTcRef wl

863
       ; let env = TcSEnv { tcs_ev_binds = ev_binds_var
864
                          , tcs_evvar_cache = ev_cache_var
865
                          , tcs_ty_binds = ty_binds_var
866
                          , tcs_context  = context
867
                          , tcs_untch    = (untouch, emptyVarSet) -- No Tcs untouchables yet
868 869
			  , tcs_count    = step_count
			  , tcs_ic_depth = 0
870 871
                          , tcs_inerts   = inert_var
                          , tcs_worklist = wl_var }
872 873

	     -- Run the computation
874
       ; res <- unTcS tcs env
875 876
	     -- Perform the type unifications required
       ; ty_binds <- TcM.readTcRef ty_binds_var
877
       ; mapM_ do_unification (varEnvElts ty_binds)
878

Ian Lynagh's avatar
Ian Lynagh committed
879 880 881 882 883 884
       ; when debugIsOn $ do {
             count <- TcM.readTcRef step_count
           ; when (opt_PprStyle_Debug && count > 0) $
             TcM.debugDumpTcRn (ptext (sLit "Constraint solver steps =") 
                                <+> int count <+> ppr context)
         }
885
             -- And return
886
       ; ev_binds      <- TcM.readTcRef evb_ref
887
       ; return (res, evBindMapBinds ev_binds) }
888 889
  where
    do_unification (tv,ty) = TcM.writeMetaTyVar tv ty
890

891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910

doWithInert :: InertSet -> TcS a -> TcS a 
doWithInert inert (TcS action)
  = TcS $ \env -> do { new_inert_var <- TcM.newTcRef inert
                     ; orig_cache_var <- TcM.readTcRef (tcs_evvar_cache env)
                     ; new_cache_var <- TcM.newTcRef orig_cache_var
                     ; action (env { tcs_inerts = new_inert_var 
                                   , tcs_evvar_cache = new_cache_var }) }


nestImplicTcS :: EvBindsVar -> TcsUntouchables -> TcS a -> TcS a 
nestImplicTcS ref (inner_range, inner_tcs) (TcS thing_inside) 
  = TcS $ \ TcSEnv { tcs_ty_binds = ty_binds
                   , tcs_evvar_cache = orig_evvar_cache_var
                   , tcs_untch = (_outer_range, outer_tcs)
                   , tcs_count = count
                   , tcs_ic_depth = idepth
                   , tcs_context = ctxt
                   , tcs_inerts = inert_var
                   , tcs_worklist = wl_var } -> 
dimitris's avatar
dimitris committed
911
    do { let inner_untch = (inner_range, outer_tcs `unionVarSet` inner_tcs)
912 913 914 915
       		   -- The inner_range should be narrower than the outer one
		   -- (thus increasing the set of untouchables) but 
		   -- the inner Tcs-untouchables must be unioned with the
		   -- outer ones!
dimitris's avatar
dimitris committed
916

917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
         -- Inherit the inerts from the outer scope
       ; orig_inerts <- TcM.readTcRef inert_var
       ; new_inert_var <- TcM.newTcRef orig_inerts
                          
         -- Inherit EvVar cache
       ; orig_evvar_cache <- TcM.readTcRef orig_evvar_cache_var
       ; evvar_cache <- TcM.newTcRef orig_evvar_cache
 
       ; let nest_env = TcSEnv { tcs_ev_binds    = ref
                               , tcs_evvar_cache = evvar_cache
                               , tcs_ty_binds    = ty_binds
                               , tcs_untch       = inner_untch
                               , tcs_count       = count
                               , tcs_ic_depth    = idepth+1
                               , tcs_context     = ctxtUnderImplic ctxt 
                               , tcs_inerts      = new_inert_var
                               , tcs_worklist    = wl_var 
                               -- NB: worklist is going to be empty anyway, 
                               -- so reuse the same ref cell
                               }
       ; thing_inside nest_env } 
938

939 940 941 942 943
recoverTcS :: TcS a -> TcS a -> TcS a
recoverTcS (TcS recovery_code) (TcS thing_inside)
  = TcS $ \ env ->
    TcM.recoverM (recovery_code env) (thing_inside env)

944 945
ctxtUnderImplic :: SimplContext -> SimplContext
-- See Note [Simplifying RULE lhs constraints] in TcSimplify
946 947 948
ctxtUnderImplic (SimplRuleLhs n) = SimplCheck (ptext (sLit "lhs of rule") 
                                               <+> doubleQuotes (ftext n))
ctxtUnderImplic ctxt              = ctxt
949

950
tryTcS :: TcS a -> TcS a
951 952 953
-- Like runTcS, but from within the TcS monad 
-- Completely afresh inerts and worklist, be careful! 
-- Moreover, we will simply throw away all the evidence generated. 
dimitris's avatar
dimitris committed
954
tryTcS tcs
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
  = TcS (\env -> 
             do { wl_var <- TcM.newTcRef emptyWorkList
                ; is_var <- TcM.newTcRef emptyInert

                ; ty_binds_var <- TcM.newTcRef emptyVarEnv
                ; ev_binds_var <- TcM.newTcEvBinds

                ; ev_binds_cache_var <- TcM.newTcRef (EvVarCache emptyTM emptyTM)
                    -- Empty cache: Don't inherit cache from above, see 
                    -- Note [tryTcS for defaulting] in TcSimplify

                ; let env1 = env { tcs_ev_binds = ev_binds_var
                                 , tcs_evvar_cache = ev_binds_cache_var
                                 , tcs_ty_binds = ty_binds_var
                                 , tcs_inerts   = is_var
                                 , tcs_worklist = wl_var } 
                ; unTcS tcs env1 })

-- Getters and setters of TcEnv fields
974 975
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
-- Getter of inerts and worklist
getTcSInertsRef :: TcS (IORef InertSet)
getTcSInertsRef = TcS (return . tcs_inerts)

getTcSWorkListRef :: TcS (IORef WorkList) 
getTcSWorkListRef = TcS (return . tcs_worklist) 

getTcSInerts :: TcS InertSet 
getTcSInerts = getTcSInertsRef >>= wrapTcS . (TcM.readTcRef) 

getTcSWorkList :: TcS WorkList
getTcSWorkList = getTcSWorkListRef >>= wrapTcS . (TcM.readTcRef) 

updWorkListTcS :: (WorkList -> WorkList) -> TcS () 
updWorkListTcS f 
  = updWorkListTcS_return (\w -> ((),f w))

updWorkListTcS_return :: (WorkList -> (a,WorkList)) -> TcS a
updWorkListTcS_return f
  = do { wl_var <- getTcSWorkListRef
       ; wl_curr <- wrapTcS (TcM.readTcRef wl_var)
       ; let (res,new_work) = f wl_curr
       ; wrapTcS (TcM.writeTcRef wl_var new_work)
       ; return res }

emitFrozenError :: CtFlavor -> EvVar -> SubGoalDepth -> TcS ()
-- Emits a non-canonical constraint that will stand for a frozen error in the inerts. 
emitFrozenError fl ev depth 
  = do { traceTcS "Emit frozen error" (ppr ev <+> dcolon <+> ppr (evVarPred ev))
       ; inert_ref <- getTcSInertsRef 
       ; inerts <- wrapTcS (TcM.readTcRef inert_ref)
       ; let ct = CNonCanonical { cc_id = ev
                                , cc_flavor = fl
                                , cc_depth = depth } 
             inerts_new = inerts { inert_frozen = extendCts (inert_frozen inerts) ct } 
       ; wrapTcS (TcM.writeTcRef inert_ref inerts_new) }

1013 1014
instance HasDynFlags TcS where
    getDynFlags = wrapTcS TcM.getDOpts
1015 1016 1017 1018 1019 1020 1021

getTcSContext :: TcS SimplContext
getTcSContext = TcS (return . tcs_context)

getTcEvBinds :: TcS EvBindsVar
getTcEvBinds = TcS (return . tcs_ev_binds) 

1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
getTcSEvVarCache :: TcS (IORef EvVarCache)
getTcSEvVarCache = TcS (return . tcs_evvar_cache)

flushFlatCache :: TcS ()
flushFlatCache
  = do { cache_var <- getTcSEvVarCache
       ; the_cache <- wrapTcS $ TcM.readTcRef cache_var
       ; wrapTcS $ TcM.writeTcRef cache_var (the_cache { evc_flat_cache = emptyTM }) }


getTcSEvVarCacheMap :: TcS (TypeMap (EvVar,CtFlavor))
getTcSEvVarCacheMap = do { cache_var <- getTcSEvVarCache 
                         ; the_cache <- wrapTcS $ TcM.readTcRef cache_var 
                         ; return (evc_cache the_cache) }

1037
getTcSEvVarFlatCache :: TcS (TypeMap (TcCoercion,(Type,CtFlavor,FlatEqOrigin)))
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
getTcSEvVarFlatCache = do { cache_var <- getTcSEvVarCache 
                          ; the_cache <- wrapTcS $ TcM.readTcRef cache_var 
                          ; return (evc_flat_cache the_cache) }

setTcSEvVarCacheMap :: TypeMap (EvVar,CtFlavor) -> TcS () 
setTcSEvVarCacheMap cache = do { cache_var <- getTcSEvVarCache 
                               ; orig_cache <- wrapTcS $ TcM.readTcRef cache_var
                               ; let new_cache = orig_cache { evc_cache = cache } 
                               ; wrapTcS $ TcM.writeTcRef cache_var new_cache }

1048
getUntouchables :: TcS TcsUntouchables
1049 1050
getUntouchables = TcS (return . tcs_untch)

1051
getTcSTyBinds :: TcS (IORef (TyVarEnv (TcTyVar, TcType)))
1052 1053
getTcSTyBinds = TcS (return . tcs_ty_binds)

1054
getTcSTyBindsMap :: TcS (TyVarEnv (TcTyVar, TcType))
1055
getTcSTyBindsMap = getTcSTyBinds >>= wrapTcS . (TcM.readTcRef) 
1056

1057 1058 1059

getTcEvBindsMap :: TcS EvBindMap
getTcEvBindsMap
1060 1061 1062
  = do { EvBindsVar ev_ref _ <- getTcEvBinds 
       ; wrapTcS $ TcM.readTcRef ev_ref }

1063

1064 1065
setEqBind :: EqVar -> TcCoercion -> CtFlavor -> TcS CtFlavor
setEqBind eqv co fl = setEvBind eqv (EvCoercion co) fl
1066 1067 1068

setWantedTyBind :: TcTyVar -> TcType -> TcS () 
-- Add a type binding
1069
-- We never do this twice!
1070 1071 1072 1073
setWantedTyBind tv ty 
  = do { ref <- getTcSTyBinds
       ; wrapTcS $ 
         do { ty_binds <- TcM.readTcRef ref
Ian Lynagh's avatar
Ian Lynagh committed
1074 1075 1076 1077 1078
            ; when debugIsOn $
                  TcM.checkErr (not (tv `elemVarEnv` ty_binds)) $
                  vcat [ text "TERRIBLE ERROR: double set of meta type variable"
                       , ppr tv <+> text ":=" <+> ppr ty
                       , text "Old value =" <+> ppr (lookupVarEnv_NF ty_binds tv)]
1079
            ; TcM.writeTcRef ref (extendVarEnv ty_binds tv (tv,ty)) } }
1080 1081


1082 1083
setEvBind :: EvVar -> EvTerm -> CtFlavor -> TcS CtFlavor
-- If the flavor is Solved, we cache the new evidence term inside the returned flavor
1084
-- see Note [Optimizing Spontaneously Solved Coercions]
1085
setEvBind ev t fl
1086
  = do { tc_evbinds <- getTcEvBinds
1087 1088 1089 1090
       ; wrapTcS $ TcM.addTcEvBind tc_evbinds ev t

#ifdef DEBUG
       ; binds <- getTcEvBindsMap
1091
       ; let cycle = any (reaches binds) (evVarsOfTerm t)
1092 1093
       ; when cycle (fail_if_co_loop binds)
#endif
1094 1095 1096 1097 1098
       ; return $ 
         case fl of 
           Given gl (GivenSolved _) 
               -> Given gl (GivenSolved (Just t))
           _   -> fl
1099 1100 1101 1102 1103 1104
       }

#ifdef DEBUG
  where fail_if_co_loop binds
          = pprTrace "setEvBind" (vcat [ text "Cycle in evidence binds, evvar =" <+> ppr ev
                                       , ppr (evBindMapBinds binds) ]) $
1105
            when (isEqVar ev) (pprPanic "setEvBind" (text "BUG: Coercion loop!"))
1106 1107 1108 1109 1110 1111 1112

        reaches :: EvBindMap -> Var -> Bool 
        -- Does this evvar reach ev? 
        reaches ebm ev0 = go ev0
          where go ev0
                  | ev0 == ev = True
                  | Just (EvBind _ evtrm) <- lookupEvBind ebm ev0
1113
                  = any go (evVarsOfTerm evtrm)
1114 1115 1116
                  | otherwise = False
#endif

1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
\end{code}
Note [Optimizing Spontaneously Solved Coercions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 

Spontaneously solved coercions such as alpha := tau used to be bound as everything else
in the evidence binds. Subsequently they were used for rewriting other wanted or solved
goals. For instance: 

WorkItem = [S] g1 : a ~ tau
Inerts   = [S] g2 : b ~ [a]
           [S] g3 : c ~ [(a,a)]

Would result, eventually, after the workitem rewrites the inerts, in the
following evidence bindings:

        g1 = ReflCo tau
        g2 = ReflCo [a]
        g3 = ReflCo [(a,a)]
        g2' = g2 ; [g1] 
        g3' = g3 ; [(g1,g1)]

This ia annoying because it puts way too much stress to the zonker and
desugarer, since we /know/ at the generation time (spontaneously
solving) that the evidence for a particular evidence variable is the
identity.

For this reason, our solution is to cache inside the GivenSolved
flavor of a constraint the term which is actually solving this
constraint. Whenever we perform a setEvBind, a new flavor is returned
so that if it was a GivenSolved to start with, it remains a
GivenSolved with a new evidence term inside. Then, when we use solved
goals to rewrite other constraints we simply use whatever is in the
GivenSolved flavor and not the constraint cc_id.

In our particular case we'd get the following evidence bindings, eventually: 

       g1 = ReflCo tau
       g2 = ReflCo [a]
       g3 = ReflCo [(a,a)]
       g2'= ReflCo [a]
       g3'= ReflCo [(a,a)]

Since we use smart constructors to get rid of g;ReflCo t ~~> g etc.

\begin{code}
1162

1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202

warnTcS :: CtLoc orig -> Bool -> SDoc -> TcS ()
warnTcS loc warn_if doc 
  | warn_if   = wrapTcS $ TcM.setCtLoc loc $ TcM.addWarnTc doc
  | otherwise = return ()

getDefaultInfo ::  TcS (SimplContext, [Type], (Bool, Bool))
getDefaultInfo 
  = do { ctxt <- getTcSContext
       ; (tys, flags) <- wrapTcS (TcM.tcGetDefaultTys (isInteractive ctxt))
       ; return (ctxt, tys, flags) }

-- Just get some environments needed for instance looking up and matching
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

getInstEnvs :: TcS (InstEnv, InstEnv) 
getInstEnvs = wrapTcS $ Inst.tcGetInstEnvs 

getFamInstEnvs :: TcS (FamInstEnv, FamInstEnv) 
getFamInstEnvs = wrapTcS $ FamInst.tcGetFamInstEnvs

getTopEnv :: TcS HscEnv 
getTopEnv = wrapTcS $ TcM.getTopEnv 

getGblEnv :: TcS TcGblEnv 
getGblEnv = wrapTcS $ TcM.getGblEnv 

-- Various smaller utilities [TODO, maybe will be absorbed in the instance matcher]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

checkWellStagedDFun :: PredType -> DFunId -> WantedLoc -> TcS () 
checkWellStagedDFun pred dfun_id loc 
  = wrapTcS $ TcM.setCtLoc loc $ 
    do { use_stage <- TcM.getStage
       ; TcM.checkWellStaged pp_thing bind_lvl (thLevel use_stage) }
  where
    pp_thing = ptext (sLit "instance for") <+> quotes (ppr pred)
    bind_lvl = TcM.topIdLvl dfun_id

pprEq :: TcType -> TcType -> SDoc
batterseapower's avatar
batterseapower committed
1203
pprEq ty1 ty2 = pprType $ mkEqPred (ty1,ty2)
1204 1205

isTouchableMetaTyVar :: TcTyVar -> TcS Bool
1206
isTouchableMetaTyVar tv 
1207 1208 1209
  = do { untch <- getUntouchables
       ; return $ isTouchableMetaTyVar_InRange untch tv } 

1210 1211
isTouchableMetaTyVar_InRange :: TcsUntouchables -> TcTyVar -> Bool 
isTouchableMetaTyVar_InRange (untch,untch_tcs) tv 
1212
  = case tcTyVarDetails tv of 
1213 1214
      MetaTv TcsTv _ -> not (tv `elemVarSet` untch_tcs)
                        -- See Note [Touchable meta type variables] 
1215 1216 1217 1218
      MetaTv {}      -> inTouchableRange untch tv 
      _              -> False 


1219 1220
\end{code}

1221

1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
Note [Touchable meta type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Meta type variables allocated *by the constraint solver itself* are always
touchable.  Example: 
   instance C a b => D [a] where...
if we use this instance declaration we "make up" a fresh meta type
variable for 'b', which we must later guess.  (Perhaps C has a
functional dependency.)  But since we aren't in the constraint *generator*
we can't allocate a Unique in the touchable range for this implication
constraint.  Instead, we mark it as a "TcsTv", which makes it always-touchable.
1232 1233


1234
\begin{code}
1235 1236 1237 1238 1239
-- Flatten skolems
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

newFlattenSkolemTy :: TcType -> TcS TcType
newFlattenSkolemTy ty = mkTyVarTy <$> newFlattenSkolemTyVar ty
1240 1241 1242

newFlattenSkolemTyVar :: TcType -> TcS TcTyVar
newFlattenSkolemTyVar ty
1243
  = do { tv <- wrapTcS $ do { uniq <- TcM.newUnique
1244
                            ; let name = TcM.mkTcTyVarName uniq (fsLit "f")
1245 1246 1247 1248
                            ; return $ mkTcTyVar name (typeKind ty) (FlatSkol ty) } 
       ; traceTcS "New Flatten Skolem Born" $ 
           (ppr tv <+> text "[:= " <+> ppr ty <+> text "]")
       ; return tv }
1249 1250 1251 1252 1253

-- Instantiations 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

instDFunTypes :: [Either TyVar TcType] -> TcS [TcType] 
1254