TcSMonad.lhs 56.9 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
    getTcSWorkList, updWorkListTcS, updWorkListTcS_return, keepWanted,
20
    getTcSWorkListTvs, 
21
22
23

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

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

29
30
    isFlexiTcsTv,

31
    canRewrite, canSolve,
dimitris's avatar
dimitris committed
32
    mkSolvedLoc, mkGivenLoc,
33
    ctWantedLoc,
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,

dimitris's avatar
dimitris committed
42
43
44
45
46
47
48
49
50
51
52
53
54
    -- Getting and setting the flattening cache
    getFlatCache, updFlatCache, addToSolved, 
    
    
    setEvBind,
    XEvTerm(..),
    MaybeNew (..), isFresh,
    xCtFlavor, -- Transform a CtFlavor during a step 
    rewriteCtFlavor,          -- Specialized version of xCtFlavor for coercions
    newWantedEvVar, newGivenEvVar, instDFunConstraints, newKindConstraint,
    newDerived,
    xCtFlavor_cache, rewriteCtFlavor_cache,
    
55
       -- Creation of evidence variables
56
57
    setWantedTyBind,

58
    getInstEnvs, getFamInstEnvs,                -- Getting the environments
59
    getTopEnv, getGblEnv, getTcEvBinds, getUntouchables,
60
    getTcEvBindsMap, getTcSContext, getTcSTyBinds, getTcSTyBindsMap,
61

62
63

    newFlattenSkolemTy,                         -- Flatten skolems 
64

65
        -- Inerts 
dimitris's avatar
dimitris committed
66
    InertSet(..), InertCans(..), 
67
    getInertEqs, getCtCoercion,
68
69
70
71
    emptyInert, getTcSInerts, updInertSet, extractUnsolved,
    extractUnsolvedTcS, modifyInertTcS,
    updInertSetTcS, partitionCCanMap, partitionEqMap,
    getRelevantCts, extractRelevantInerts,
dimitris's avatar
dimitris committed
72
73
    CCanMap (..), CtTypeMap, CtFamHeadMap(..), CtPredMap(..),
    pprCtTypeMap, partCtFamHeadMap,
74

75
76

    instDFunTypes,                              -- Instantiation
dimitris's avatar
dimitris committed
77
    -- instDFunConstraints,          
78
    newFlexiTcSTy, instFlexiTcS,
79

80
    compatKind, mkKindErrorCtxtTcS,
81

82
    TcsUntouchables,
83
    isTouchableMetaTyVar,
84
    isTouchableMetaTyVar_InRange, 
85
86
87
88
89
90

    getDefaultInfo, getDynFlags,

    matchClass, matchFam, MatchInstResult (..), 
    checkWellStagedDFun, 
    warnTcS,
91
    pprEq                                    -- Smaller utils, re-exported from TcM
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
                                             -- 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 
111
       ( checkWellStaged, topIdLvl, tcGetDefaultTys )
112
import {-# SOURCE #-} qualified TcUnify as TcM ( mkKindErrorCtxt )
113
import Kind
114
115
import TcType
import DynFlags
116
import Type
117

118
import TcEvidence
119
120
import Class
import TyCon
121

122
123
import Name
import Var
124
import VarEnv
125
126
127
128
import Outputable
import Bag
import MonadUtils
import VarSet
129

130
import FastString
Ian Lynagh's avatar
Ian Lynagh committed
131
import Util
132
import Id 
Ian Lynagh's avatar
Ian Lynagh committed
133
import TcRnTypes
134

135
136
137
138
139
140
import Unique 
import UniqFM
import Maybes ( orElse )

import Control.Monad( when )
import StaticFlags( opt_PprStyle_Debug )
Ian Lynagh's avatar
Ian Lynagh committed
141
import Data.IORef
dimitris's avatar
dimitris committed
142
143
import Data.List ( find )
import Control.Monad ( zipWithM )
144
import TrieMap
145

146
\end{code}
147

148

149
\begin{code}
150
compatKind :: Kind -> Kind -> Bool
Simon Peyton Jones's avatar
Simon Peyton Jones committed
151
compatKind k1 k2 = k1 `tcIsSubKind` k2 || k2 `tcIsSubKind` k1 
152

153
154
155
156
157
158
mkKindErrorCtxtTcS :: Type -> Kind 
                   -> Type -> Kind 
                   -> ErrCtxt
mkKindErrorCtxtTcS ty1 ki1 ty2 ki2
  = (False,TcM.mkKindErrorCtxt ty1 ty2 ki1 ki2)

159
160
\end{code}

161
162
163
164
165
166
167
168
%************************************************************************
%*									*
%*                            Worklists                                *
%*  Canonical and non-canonical constraints that the simplifier has to  *
%*  work on. Including their simplification depths.                     *
%*                                                                      *
%*									*
%************************************************************************
169

170
171
Note [WorkList]
~~~~~~~~~~~~~~~
172

173
174
175
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. 
176

177
178
179
180
181
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. 
182

183
184
185
186
187
188
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. 
189

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

193
194
195
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)
196

197
\begin{code}
198

199
-- See Note [WorkList]
200
201
202
203
data WorkList = WorkList { wl_eqs    :: [Ct]
                         , wl_funeqs :: [Ct]
                         , wl_rest   :: [Ct] 
                         }
204

batterseapower's avatar
batterseapower committed
205

206
207
unionWorkList :: WorkList -> WorkList -> WorkList
unionWorkList new_wl orig_wl = 
dimitris's avatar
dimitris committed
208
209
210
   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 }
211

212

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

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

226
227
228
extendWorkListCt :: Ct -> WorkList -> WorkList
-- Agnostic
extendWorkListCt ct wl
dimitris's avatar
dimitris committed
229
 | isEqPred (ctPred ct) = extendWorkListEq ct wl
230
 | otherwise = extendWorkListNonEq ct wl
231

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

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

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

emptyWorkList :: WorkList
245
emptyWorkList = WorkList { wl_eqs  = [], wl_rest = [], wl_funeqs = [] }
246

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

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

253
254
workListFromCt :: Ct -> WorkList
-- Agnostic 
dimitris's avatar
dimitris committed
255
256
workListFromCt ct | isEqPred (ctPred ct) = workListFromEq ct 
                  | otherwise            = workListFromNonEq ct
257

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

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)

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

274
275
276
277
278
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? 
279

dimitris's avatar
dimitris committed
280
-- Canonical constraint maps
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
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) }
dimitris's avatar
dimitris committed
302
      Solved {}  -> panic "updCCanMap update with solved!" 
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
  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

dimitris's avatar
dimitris committed
319
320
321
322
323
324
lookupCCanMap :: Uniquable a => a -> (Ct -> Bool) -> CCanMap a -> Maybe Ct
lookupCCanMap a p map
   = let possible_cts = lookupUFM (cts_given map)   a `orElse` 
                        lookupUFM (cts_wanted map)  a `orElse` 
                        lookupUFM (cts_derived map) a `orElse` emptyCts
     in find p (bagToList possible_cts)
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340


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

341
partitionEqMap :: (Ct -> Bool) -> TyVarEnv (Ct,TcCoercion) -> ([Ct], TyVarEnv (Ct,TcCoercion))
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
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 })


dimitris's avatar
dimitris committed
359
-- Maps from PredTypes to Constraints
360
type CtTypeMap = TypeMap Ct
dimitris's avatar
dimitris committed
361
362
363
364
newtype CtPredMap = 
  CtPredMap { unCtPredMap :: CtTypeMap }       -- Indexed by TcPredType
newtype CtFamHeadMap = 
  CtFamHeadMap { unCtFamHeadMap :: CtTypeMap } -- Indexed by family head
365
366
367
368
369
370
371

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

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

dimitris's avatar
dimitris committed
372
373
374
375
376
377
378
379
380
381

partCtFamHeadMap :: (Ct -> Bool) 
                 -> CtFamHeadMap 
                 -> (Cts, CtFamHeadMap)
partCtFamHeadMap f ctmap
  = let (cts,tymap_final) = foldTM upd_acc tymap_inside (emptyBag, tymap_inside)
    in (cts, CtFamHeadMap tymap_final)
  where
    tymap_inside = unCtFamHeadMap ctmap 
    upd_acc ct (cts,acc_map)
382
383
         | f ct      = (extendCts cts ct, alterTM ct_key (\_ -> Nothing) acc_map)
         | otherwise = (cts,acc_map)
dimitris's avatar
dimitris committed
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
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
         where ct_key | EqPred ty1 _ <- classifyPredType (ctPred ct)
                      = ty1 
                      | otherwise 
                      = panic "partCtFamHeadMap, encountered non equality!"


\end{code}

%************************************************************************
%*									*
%*                            Inert Sets                                *
%*                                                                      *
%*									*
%************************************************************************

\begin{code}


-- All Given (fully known) or Wanted or Derived, never Solved
-- See Note [Detailed InertCans Invariants] for more
data InertCans 
  = IC { inert_eqs :: TyVarEnv Ct
              -- 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
              -- Superset of the type variables of inert_eqs
       , inert_dicts :: CCanMap Class
              -- Dictionaries only, index is the class
              -- NB: index is /not/ the whole type because FD reactions 
              -- need to match the class but not necessarily the whole type.
       , inert_ips :: CCanMap (IPName Name)
              -- Implicit parameters, index is the name
              -- NB: index is /not/ the whole type because IP reactions need 
              -- to match the ip name but not necessarily the whole type.
       , inert_funeqs :: CtFamHeadMap
              -- Family equations, index is the whole family head type.
       , inert_irreds :: Cts       
              -- Irreducible predicates
       }
    
                     
\end{code}

Note [Detailed InertCans Invariants]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The InertCans represents a collection of constraints with the following properties:
  1 All canonical
  2 All Given or Wanted or Derived. No (partially) Solved
  3 No two dictionaries with the same head
  4 No two family equations with the same head
  5 Family equations inert with top-level
  6 Dictionaries have no matching instance at top level
  7 Constraints are fully rewritten with respect to the equality constraints (CTyEqCan)
  8 Equalities form an idempotent substitution (taking flavors into consideration)
  9 Given family or dictionary constraints don't mention touchable unification variables
\begin{code}


-- The Inert Set
data InertSet
  = IS { inert_cans :: InertCans
              -- Canonical Given,Wanted,Solved
       , inert_frozen :: Cts       
              -- Frozen errors (as non-canonicals)
                               
       , inert_solved :: CtPredMap
              -- Solved constraints (for caching): 
              -- (i) key is by predicate type
              -- (ii) all of 'Solved' flavor, may or may not be canonicals
              -- (iii) we use this field for avoiding creating newEvVars
       , inert_flat_cache :: CtFamHeadMap 
              -- All ``flattening equations'' are kept here. 
              -- Always canonical CTyFunEqs (Given or Wanted only!)
              -- Key is by family head. We used this field during flattening only
       , inert_solved_funeqs :: CtFamHeadMap
461
              -- Memoized Solved family equations co :: F xis ~ xi
dimitris's avatar
dimitris committed
462
463
464
              -- Stored not necessarily as fully rewritten; we'll do that lazily
              -- when we lookup
       }
465
466


dimitris's avatar
dimitris committed
467
468
469
470
471
472
473
474
475
476
477
instance Outputable InertCans where 
  ppr ics = vcat [ vcat (map ppr (varEnvElts (inert_eqs ics)))
                 , vcat (map ppr (Bag.bagToList $ cCanMapToBag (inert_dicts ics)))
                 , vcat (map ppr (Bag.bagToList $ cCanMapToBag (inert_ips ics))) 
                 , vcat (map ppr (Bag.bagToList $ 
                                  ctTypeMapCts (unCtFamHeadMap $ inert_funeqs ics)))
                 , vcat (map ppr (Bag.bagToList $ inert_irreds ics))
                 ]
            
instance Outputable InertSet where 
  ppr is = vcat [ ppr $ inert_cans is
478
479
                , text "Frozen errors =" <+> -- Clearly print frozen errors
                    braces (vcat (map ppr (Bag.bagToList $ inert_frozen is)))
dimitris's avatar
dimitris committed
480
481
482
483
                , text "Solved and cached" <+>
                    int (foldTypeMap (\_ x -> x+1) 0 
                             (unCtPredMap $ inert_solved is)) <+> 
                    text "more constraints" ]
484

dimitris's avatar
dimitris committed
485
486
487
488
489
490
491
492
493
494
495
496
emptyInert :: InertSet
emptyInert
  = IS { inert_cans = IC { inert_eqs    = emptyVarEnv
                         , inert_eq_tvs = emptyInScopeSet
                         , inert_dicts  = emptyCCanMap
                         , inert_ips    = emptyCCanMap
                         , inert_funeqs = CtFamHeadMap emptyTM 
                         , inert_irreds = emptyCts }
       , inert_frozen        = emptyCts
       , inert_flat_cache    = CtFamHeadMap emptyTM
       , inert_solved        = CtPredMap emptyTM 
       , inert_solved_funeqs = CtFamHeadMap emptyTM }
497
498
499
500
501
502

type AtomicInert = Ct 

updInertSet :: InertSet -> AtomicInert -> InertSet 
-- Add a new inert element to the inert set. 
updInertSet is item 
dimitris's avatar
dimitris committed
503
504
505
506
507
508
509
510
511
512
513
514
515
  | isSolved (cc_flavor item)
    -- Solved items go in their special place
  = let pty = ctPred item
        upd_solved Nothing = Just item
        upd_solved (Just _existing_solved) = Just item 
               -- .. or Just existing_solved? Is this even possible to happen?
    in is { inert_solved = 
               CtPredMap $ 
               alterTM pty upd_solved (unCtPredMap $ inert_solved is) }

  | isCNonCanonical item 
    -- NB: this may happen if we decide to kick some frozen error 
    -- out to rewrite him. Frozen errors are just NonCanonicals
516
  = is { inert_frozen = inert_frozen is `Bag.snocBag` item }
dimitris's avatar
dimitris committed
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
    
  | otherwise  
    -- A canonical Given, Wanted, or Derived
  = is { inert_cans = upd_inert_cans (inert_cans is) item }
  
  where upd_inert_cans :: InertCans -> AtomicInert -> InertCans
        -- Precondition: item /is/ canonical
        upd_inert_cans ics item
          | isCTyEqCan item                     
          = let upd_err a b = pprPanic "updInertSet" $
                              vcat [ text "Multiple inert equalities:"
                                   , text "Old (already inert):" <+> ppr a
                                   , text "Trying to insert   :" <+> ppr b ]
        
                eqs'     = extendVarEnv_C upd_err (inert_eqs ics) 
                                                  (cc_tyvar item) item        
                inscope' = extendInScopeSetSet (inert_eq_tvs ics)
                                               (tyVarsOfCt item)
                
            in ics { inert_eqs = eqs', inert_eq_tvs = inscope' }

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

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

          | Just _tc <- isCFunEqCan_Maybe item  -- Function equality
          = let fam_head = mkTyConApp (cc_fun item) (cc_tyargs item)
                upd_funeqs Nothing = Just item
                upd_funeqs (Just _already_there) 
                  = panic "updInertSet: item already there!"
            in ics { inert_funeqs = CtFamHeadMap 
                                      (alterTM fam_head upd_funeqs $ 
                                         (unCtFamHeadMap $ inert_funeqs ics)) }
          | otherwise
          = pprPanic "upd_inert set: can't happen! Inserting " $ 
            ppr item 
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578

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 }

dimitris's avatar
dimitris committed
579
580
581
582
583
584

addToSolved :: Ct -> TcS ()
addToSolved ct 
  = ASSERT ( isSolved (cc_flavor ct) )
    updInertSetTcS ct

585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
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. 
-- -----------------------------------------------------------------------------
dimitris's avatar
dimitris committed
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
extractUnsolved (IS { inert_cans = IC { inert_eqs    = eqs
                                      , inert_eq_tvs = eq_tvs
                                      , inert_irreds = irreds
                                      , inert_ips    = ips
                                      , inert_funeqs = funeqs
                                      , inert_dicts  = dicts
                                      }
                    , inert_frozen = frozen
                    , inert_solved = _solved
                    , inert_flat_cache = _flat_cache })
  
  = let is_solved  = IS { inert_cans = IC { inert_eqs    = solved_eqs
                                          , inert_eq_tvs = eq_tvs
                                          , inert_dicts  = solved_dicts
                                          , inert_ips    = solved_ips
                                          , inert_irreds = solved_irreds
                                          , inert_funeqs = solved_funeqs }
                        , inert_frozen = emptyCts -- All out
                                         
                            -- DV: For solved and the flat cache, I am flushing them here:
                            -- Solved cts may depend on wanteds which we kick out. But later
                            -- we may try to re-solve some kicked-out wanteds and I am worried 
                            -- that there is a danger or evidence loops if we keep the solved 
                            -- in for caching purposes. So I am flushing the solved and the 
                            -- flattening cache, quite conservatively.
                        , inert_solved        = CtPredMap emptyTM
                        , inert_flat_cache    = CtFamHeadMap emptyTM
                        , inert_solved_funeqs = CtFamHeadMap emptyTM
634
                        }
dimitris's avatar
dimitris committed
635
    in ((frozen, unsolved), is_solved)
636

dimitris's avatar
dimitris committed
637
638
  where solved_eqs = filterVarEnv_Directly (\_ ct -> isGivenOrSolvedCt ct) eqs
        unsolved_eqs = foldVarEnv (\ct cts -> cts `extendCts` ct) emptyCts $
639
640
641
                       eqs `minusVarEnv` solved_eqs

        (unsolved_irreds, solved_irreds) = Bag.partitionBag (not.isGivenOrSolvedCt) irreds
dimitris's avatar
dimitris committed
642
643
        (unsolved_ips, solved_ips)       = extractUnsolvedCMap ips
        (unsolved_dicts, solved_dicts)   = extractUnsolvedCMap dicts
644

dimitris's avatar
dimitris committed
645
646
        (unsolved_funeqs, solved_funeqs) = 
          partCtFamHeadMap (not . isGivenOrSolved . cc_flavor) funeqs
647
648
649
650
651
652
653
654
655
656
657

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



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 
dimitris's avatar
dimitris committed
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
  = modifyInertTcS (extract_relevants wi)
  where extract_relevants wi is 
          = let (cts,ics') = extract_ics_relevants wi (inert_cans is)
            in (cts, is { inert_cans = ics' }) 
            
        extract_ics_relevants (CDictCan {cc_class = cl}) ics = 
            let (cts,dict_map) = getRelevantCts cl (inert_dicts ics) 
            in (cts, ics { inert_dicts = dict_map })
        extract_ics_relevants ct@(CFunEqCan {}) ics = 
            let (cts,feqs_map)  = 
                  let funeq_map = unCtFamHeadMap $ inert_funeqs ics
                      fam_head = mkTyConApp (cc_fun ct) (cc_tyargs ct)
                      lkp = lookupTM fam_head funeq_map
                      new_funeq_map = alterTM fam_head xtm funeq_map
                      xtm Nothing    = Nothing
                      xtm (Just _ct) = Nothing
                  in case lkp of 
                    Nothing -> (emptyCts, funeq_map)
                    Just ct -> (singleCt ct, new_funeq_map)
            in (cts, ics { inert_funeqs = CtFamHeadMap feqs_map })
        extract_ics_relevants (CIPCan { cc_ip_nm = nm } ) ics = 
            let (cts, ips_map) = getRelevantCts nm (inert_ips ics) 
            in (cts, ics { inert_ips = ips_map })
        extract_ics_relevants (CIrredEvCan { }) ics = 
            let cts = inert_irreds ics 
            in (cts, ics { inert_irreds = emptyCts })
        extract_ics_relevants _ ics = (emptyCts,ics)
        

lookupInInerts :: InertSet -> TcPredType -> Maybe Ct
-- Is this exact predicate type cached in the solved or canonicals of the InertSet
lookupInInerts (IS { inert_solved = solved, inert_cans = ics }) pty
  = case lookupInSolved solved pty of
      Just ct -> return ct
      Nothing -> lookupInInertCans ics pty

lookupInSolved :: CtPredMap -> TcPredType -> Maybe Ct
-- Returns just if exactly this predicate type exists in the solved.
lookupInSolved tm pty = lookupTM pty $ unCtPredMap tm

lookupInInertCans :: InertCans -> TcPredType -> Maybe Ct
-- Returns Just if exactly this pred type exists in the inert canonicals
lookupInInertCans ics pty
  = lkp_ics (classifyPredType pty)
  where lkp_ics (ClassPred cls _)
          = lookupCCanMap cls (\ct -> ctPred ct `eqType` pty) (inert_dicts ics)
        lkp_ics (EqPred ty1 _ty2)
          | Just tv <- getTyVar_maybe ty1
          , Just ct <- lookupVarEnv (inert_eqs ics) tv
          , ctPred ct `eqType` pty
          = Just ct
        lkp_ics (EqPred ty1 _ty2) -- Family equation
          | Just _ <- splitTyConApp_maybe ty1
          , Just ct <- lookupTM ty1 (unCtFamHeadMap $ inert_funeqs ics)
          , ctPred ct `eqType` pty
          = Just ct
        lkp_ics (IrredPred {}) 
          = find (\ct -> ctPred ct `eqType` pty) (bagToList (inert_irreds ics))
        lkp_ics _ = Nothing -- NB: No caching for IPs
717
718
\end{code}

719

dimitris's avatar
dimitris committed
720
721


722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
%************************************************************************
%*									*
%*		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 { 
744
      tcs_ev_binds    :: EvBindsVar,
dimitris's avatar
dimitris committed
745
      
746
      tcs_ty_binds :: IORef (TyVarEnv (TcTyVar, TcType)),
747
748
          -- Global type bindings

749
      tcs_context :: SimplContext,
750
                     
751
752
      tcs_untch :: TcsUntouchables,

dimitris's avatar
dimitris committed
753
754
755
      tcs_ic_depth   :: Int,       -- Implication nesting depth
      tcs_count      :: IORef Int, -- Global step count

756
757
      tcs_inerts   :: IORef InertSet, -- Current inert set
      tcs_worklist :: IORef WorkList  -- Current worklist
dimitris's avatar
dimitris committed
758

759
    }
dimitris's avatar
dimitris committed
760

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

\begin{code}
768
data SimplContext
769
770
771
772
  = 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
773
774

instance Outputable SimplContext where
775
776
777
  ppr (SimplInfer d)   = ptext (sLit "SimplInfer") <+> d
  ppr (SimplCheck d)   = ptext (sLit "SimplCheck") <+> d
  ppr (SimplRuleLhs n) = ptext (sLit "SimplRuleLhs") <+> doubleQuotes (ftext n)
778
779
780
781
782
783
784
785
786
787
  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
788
789
simplEqsOnly (SimplRuleLhs {}) = True
simplEqsOnly _                 = False
790
791

performDefaulting :: SimplContext -> Bool
792
793
794
795
performDefaulting (SimplInfer {})   = False
performDefaulting (SimplRuleLhs {}) = False
performDefaulting SimplInteractive  = True
performDefaulting (SimplCheck {})   = True
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
829
830

---------------
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 ()
831
traceTcS herald doc = wrapTcS (TcM.traceTc herald doc)
832

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

838
traceFireTcS :: SubGoalDepth -> SDoc -> TcS ()
839
840
841
842
843
844
845
846
847
-- 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 }
848
849

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

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

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

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

Ian Lynagh's avatar
Ian Lynagh committed
878
879
880
881
882
883
       ; 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)
         }
884
             -- And return
885
886
       ; ev_binds <- TcM.getTcEvBinds ev_binds_var
       ; return (res, ev_binds) }
887
888
  where
    do_unification (tv,ty) = TcM.writeMetaTyVar tv ty
889

890
891
892
893

doWithInert :: InertSet -> TcS a -> TcS a 
doWithInert inert (TcS action)
  = TcS $ \env -> do { new_inert_var <- TcM.newTcRef inert
dimitris's avatar
dimitris committed
894
                     ; action (env { tcs_inerts = new_inert_var }) }
895
896
897
898
899
900
901
902
903
904

nestImplicTcS :: EvBindsVar -> TcsUntouchables -> TcS a -> TcS a 
nestImplicTcS ref (inner_range, inner_tcs) (TcS thing_inside) 
  = TcS $ \ TcSEnv { tcs_ty_binds = ty_binds
                   , 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
905
    do { let inner_untch = (inner_range, outer_tcs `unionVarSet` inner_tcs)
906
907
908
909
       		   -- 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
910

911
912
913
         -- Inherit the inerts from the outer scope
       ; orig_inerts <- TcM.readTcRef inert_var
       ; new_inert_var <- TcM.newTcRef orig_inerts
dimitris's avatar
dimitris committed
914
                           
915
916
917
918
919
920
921
922
923
924
925
926
       ; let nest_env = TcSEnv { tcs_ev_binds    = ref
                               , 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 } 
927

928
929
930
931
932
recoverTcS :: TcS a -> TcS a -> TcS a
recoverTcS (TcS recovery_code) (TcS thing_inside)
  = TcS $ \ env ->
    TcM.recoverM (recovery_code env) (thing_inside env)

933
934
ctxtUnderImplic :: SimplContext -> SimplContext
-- See Note [Simplifying RULE lhs constraints] in TcSimplify
935
936
937
ctxtUnderImplic (SimplRuleLhs n) = SimplCheck (ptext (sLit "lhs of rule") 
                                               <+> doubleQuotes (ftext n))
ctxtUnderImplic ctxt              = ctxt
938

939
tryTcS :: TcS a -> TcS a
940
941
942
-- 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
943
tryTcS tcs
944
945
946
947
948
949
950
951
952
953
954
955
956
957
  = TcS (\env -> 
             do { wl_var <- TcM.newTcRef emptyWorkList
                ; is_var <- TcM.newTcRef emptyInert

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

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

-- Getters and setters of TcEnv fields
958
959
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

960
961
962
963
964
965
966
967
968
969
970
971
972
-- 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) 

973
974
975
976
977
978
979
980
981
982

getTcSWorkListTvs :: TcS TyVarSet
-- Return the variables of the worklist
getTcSWorkListTvs 
  = do { wl <- getTcSWorkList
       ; return $
         cts_tvs (wl_eqs wl) `unionVarSet` cts_tvs (wl_funeqs wl) `unionVarSet` cts_tvs (wl_rest wl) }
  where cts_tvs = foldr (unionVarSet . tyVarsOfCt) emptyVarSet 


983
984
985
986
987
988
989
990
991
992
993
994
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 }

dimitris's avatar
dimitris committed
995
emitFrozenError :: CtFlavor -> SubGoalDepth -> TcS ()
996
-- Emits a non-canonical constraint that will stand for a frozen error in the inerts. 
dimitris's avatar
dimitris committed
997
998
emitFrozenError fl depth 
  = do { traceTcS "Emit frozen error" (ppr (ctFlavPred fl))
999
1000
       ; inert_ref <- getTcSInertsRef 
       ; inerts <- wrapTcS (TcM.readTcRef inert_ref)
dimitris's avatar
dimitris committed
1001
       ; let ct = CNonCanonical { cc_flavor = fl
1002
1003
1004
1005
                                , cc_depth = depth } 
             inerts_new = inerts { inert_frozen = extendCts (inert_frozen inerts) ct } 
       ; wrapTcS (TcM.writeTcRef inert_ref inerts_new) }

1006
instance HasDynFlags TcS where
1007
    getDynFlags = wrapTcS getDynFlags
1008
1009
1010
1011
1012
1013
1014

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

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

dimitris's avatar
dimitris committed
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
getFlatCache :: TcS CtTypeMap 
getFlatCache = getTcSInerts >>= (return . unCtFamHeadMap . inert_flat_cache)

updFlatCache :: Ct -> TcS ()
-- Pre: constraint is a flat family equation (equal to a flatten skolem)
updFlatCache flat_eq@(CFunEqCan { cc_flavor = fl, cc_fun = tc, cc_tyargs = xis })
  = modifyInertTcS upd_inert_cache
  where upd_inert_cache is = ((), is { inert_flat_cache = CtFamHeadMap new_fc })
                           where new_fc = alterTM pred_key upd_cache fc
                                 fc = unCtFamHeadMap $ inert_flat_cache is
        pred_key = mkTyConApp tc xis
        upd_cache (Just ct) | cc_flavor ct `canSolve` fl = Just ct 
        upd_cache (Just _ct) = Just flat_eq 
        upd_cache Nothing    = Just flat_eq
updFlatCache other_ct = pprPanic "updFlatCache: non-family constraint" $
                        ppr other_ct
                        
1032
1033


1034
getUntouchables :: TcS TcsUntouchables
1035
1036
getUntouchables = TcS (return . tcs_untch)

1037
getTcSTyBinds :: TcS (IORef (TyVarEnv (TcTyVar, TcType)))
1038
1039
getTcSTyBinds = TcS (return . tcs_ty_binds)

1040
getTcSTyBindsMap :: TcS (TyVarEnv (TcTyVar, TcType))
1041
getTcSTyBindsMap = getTcSTyBinds >>= wrapTcS . (TcM.readTcRef) 
1042

1043
1044
getTcEvBindsMap :: TcS EvBindMap
getTcEvBindsMap
1045
1046
1047
1048
1049
  = do { EvBindsVar ev_ref _ <- getTcEvBinds 
       ; wrapTcS $ TcM.readTcRef ev_ref }

setWantedTyBind :: TcTyVar -> TcType -> TcS () 
-- Add a type binding
1050
-- We never do this twice!
1051
1052
1053
1054
setWantedTyBind tv ty 
  = do { ref <- getTcSTyBinds
       ; wrapTcS $ 
         do { ty_binds <- TcM.readTcRef ref
Ian Lynagh's avatar
Ian Lynagh committed
1055
1056
1057
1058
1059
            ; 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)]
1060
            ; TcM.writeTcRef ref (extendVarEnv ty_binds tv (tv,ty)) } }
1061
1062


1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
\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}
1108

1109
1110
1111
1112
1113
1114
1115
1116
1117

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
1118
       ; (tys, flags) <- wrapTcS TcM.tcGetDefaultTys
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
       ; 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
1149
pprEq ty1 ty2 = pprType $ mkEqPred ty1 ty2
1150
1151

isTouchableMetaTyVar :: TcTyVar -> TcS Bool
1152
isTouchableMetaTyVar tv 
1153
1154
1155
  = do { untch <- getUntouchables
       ; return $ isTouchableMetaTyVar_InRange untch tv } 

1156
1157
isTouchableMetaTyVar_InRange :: TcsUntouchables -> TcTyVar -> Bool 
isTouchableMetaTyVar_InRange (untch,untch_tcs) tv 
1158
1159
  = ASSERT2 ( isTcTyVar tv, ppr tv )
    case tcTyVarDetails tv of 
1160
1161
      MetaTv TcsTv _ -> not (tv `elemVarSet` untch_tcs)
                        -- See Note [Touchable meta type variables] 
1162
1163
1164
1165
      MetaTv {}      -> inTouchableRange untch tv 
      _              -> False 


1166
1167
\end{code}

1168

1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
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.
1179
1180


1181
\begin{code}
1182
1183
1184
1185
1186
-- Flatten skolems
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

newFlattenSkolemTy :: TcType -> TcS TcType
newFlattenSkolemTy ty = mkTyVarTy <$> newFlattenSkolemTyVar ty
1187
1188
1189

newFlattenSkolemTyVar :: TcType -> TcS TcTyVar
newFlattenSkolemTyVar ty
dimitris's avatar
dimitris committed
1190
1191
1192
1193
1194
1195
  = do { tv <- wrapTcS $ 
               do { uniq <- TcM.newUnique
                  ; let name = TcM.mkTcTyVarName uniq (fsLit "f")
                  ; return $ mkTcTyVar name (typeKind ty) (FlatSkol ty) } 
       ; traceTcS "New Flatten Skolem Born" $
         ppr tv <+> text "[:= " <+> ppr ty <+> text "]"
1196
       ; return tv }
1197
1198
1199
1200
1201

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

instDFunTypes :: [Either TyVar TcType] -> TcS [TcType] 
1202
1203
1204
1205
instDFunTypes mb_inst_tys 
  = mapM inst_tv mb_inst_tys
  where
    inst_tv :: Either TyVar TcType -> TcS Type
1206
    inst_tv (Left tv)  = mkTyVarTy <$> instFlexiTcS tv
1207
    inst_tv (Right ty) = return ty 
1208

1209
instFlexiTcS :: TyVar -> TcS TcTyVar 
dimitris's avatar
dimitris committed
1210
1211
-- Like TcM.instMetaTyVar but the variable that is created is 
-- always touchable; we are supposed to guess its instantiation.
1212
-- See Note [Touchable meta type variables] 
1213
instFlexiTcS tv = instFlexiTcSHelper (tyVarName tv) (tyVarKind tv) 
1214

1215
1216
1217
1218
1219
newFlexiTcSTy :: Kind -> TcS TcType  
newFlexiTcSTy knd 
  = wrapTcS $
    do { uniq <- TcM.newUnique 
       ; ref  <- TcM.newMutVar  Flexi 
1220
       ; let name = TcM.mkTcTyVarName uniq (fsLit "uf")
1221
1222
       ; return $ mkTyVarTy (mkTcTyVar name knd (MetaTv TcsTv ref)) }

1223
1224
1225
1226
1227
1228
isFlexiTcsTv :: TyVar -> Bool
isFlexiTcsTv tv
  | not (isTcTyVar tv)                  = False
  | MetaTv TcsTv _ <- tcTyVarDetails tv = True
  | otherwise                           = False

1229
1230
instFlexiTcSHelper :: Name -> Kind -> TcS TcTyVar
instFlexiTcSHelper tvname tvkind
1231
1232
1233
1234
1235
1236
  = wrapTcS $ 
    do { uniq <- TcM.newUnique 
       ; ref  <- TcM.newMutVar  Flexi 
       ; let name = setNameUnique tvname uniq 
             kind = tvkind 
       ; return (mkTcTyVar name kind (MetaTv TcsTv ref)) }
1237
1238


dimitris's avatar
dimitris committed
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
-- Creating and setting evidence variables and CtFlavors
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

data XEvTerm = 
  XEvTerm { ev_comp   :: [EvVar] -> EvTerm
                         -- How to compose evidence 
          , ev_decomp :: EvVar -> [EvTerm]
                         -- How to decompose evidence 
          }

data MaybeNew a = Fresh  { mn_thing :: a } 
                | Cached { mn_thing :: a }

isFresh :: MaybeNew a -> Bool
isFresh (Fresh {}) = True
isFresh _ = False

setEvBind :: EvVar -> EvTerm -> TcS ()
setEvBind ev t
  = do { tc_evbinds <- getTcEvBinds
       ; wrapTcS $ TcM.addTcEvBind tc_evbinds ev t

1261
1262
1263
       ; traceTcS "setEvBind" $ vcat [ text "ev =" <+> ppr ev
                                     , text "t  =" <+> ppr t ]

dimitris's avatar
dimitris committed
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
#ifdef DEBUG
       ; binds <- getTcEvBindsMap
       ; let cycle = any (reaches binds) (evVarsOfTerm t)
       ; when cycle (fail_if_co_loop binds)
#endif
       ; return () }

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

        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
                  = any go (evVarsOfTerm evtrm)
                  | otherwise = False
#endif

newGivenEvVar  :: TcPredType -> EvTerm -> TcS (MaybeNew EvVar)
newGivenEvVar pty evterm
  = do { is <- getTcSInerts
       ; case lookupInInerts is pty of
            Just ct | isGivenOrSolvedCt ct 
1292
                    -> return (Cached (ctId ct))
dimitris's avatar
dimitris committed
1293
1294
1295
1296
1297
1298
1299
1300
1301
            _ -> do { new_ev <- wrapTcS $ TcM.newEvVar pty
                    ; setEvBind new_ev evterm
                    ; return (Fresh new_ev) } }

newWantedEvVar :: TcPredType -> TcS (MaybeNew EvVar)
newWantedEvVar pty
  = do { is <- getTcSInerts
       ; case lookupInInerts is pty of
            Just ct | not (isDerivedCt ct) 
1302
1303
                    -> do { traceTcS "newWantedEvVar/cache hit" $ ppr ct
                          ; return (Cached (ctId ct)) }
dimitris's avatar
dimitris committed
1304
            _ -> do { new_ev <- wrapTcS $ TcM.newEvVar pty
1305
                    ; traceTcS "newWantedEvVar/cache miss" $ ppr new_ev
dimitris's avatar
dimitris committed
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
                    ; return (Fresh new_ev) } }

newDerived :: TcPredType -> TcS (MaybeNew TcPredType)
newDerived pty
  = do { is <- getTcSInerts
       ; case lookupInInerts is pty of
            Just {} -> return (Cached pty)
            _       -> return (Fresh pty) }
    
newKindConstraint :: TcTyVar -> Kind -> TcS (MaybeNew EvVar)
-- Create new wanted CoVar that constrains the type to have the specified kind. 
newKindConstraint tv knd
  = do { tv_k <- instFlexiTcSHelper (tyVarName tv) knd 
       ; let ty_k = mkTyVarTy tv_k
       ; newWantedEvVar (mkTcEqPred (mkTyVarTy tv) ty_k) }

instDFunConstraints :: TcThetaType -> TcS [MaybeNew EvVar]
instDFunConstraints = mapM newWantedEvVar

                
xCtFlavor :: CtFlavor              -- Original flavor   
          -> [TcPredType]          -- New predicate types
          -> XEvTerm               -- Instructions about how to manipulate evidence
          -> ([CtFlavor] -> TcS a) -- What to do with any remaining /fresh/ goals!
          -> TcS a
xCtFlavor = xCtFlavor_cache True          


1334
xCtFlavor_cache :: Bool            -- True = if wanted add to the solved bag!    
dimitris's avatar
dimitris committed
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
          -> CtFlavor              -- Original flavor   
          -> [TcPredType]          -- New predicate types
          -> XEvTerm               -- Instructions about how to manipulate evidence
          -> ([CtFlavor] -> TcS a) -- What to do with any remaining /fresh/ goals!
          -> TcS a
xCtFlavor_cache _ (Given { flav_gloc = gl, flav_evar = evar }) ptys xev cont_with
  = do { let ev_trms = ev_decomp xev evar
       ; new_evars <- zipWithM newGivenEvVar ptys ev_trms
       ; cont_with $
         map (\x -> Given gl (mn_thing x)) (filter isFresh new_evars) }
  
xCtFlavor_cache cache (Wanted { flav_wloc = wl, flav_evar = evar }) ptys xev cont_with
  = do { new_evars <- mapM newWantedEvVar ptys
       ; let evars  = map mn_thing new_evars
             evterm = ev_comp xev evars
       ; setEvBind evar evterm
       ; let solved_flav = Solved { flav_gloc = mkSolvedLoc wl UnkSkol
                                  , flav_evar = evar }
       ; when cache $ addToSolved (mkNonCanonical solved_flav)
       ; cont_with $
         map (\x -> Wanted wl (mn_thing x)) (filter isFresh new_evars) }
    
xCtFlavor_cache _ (Derived { flav_wloc = wl }) ptys _xev cont_with
  = do { ders <- mapM newDerived ptys
       ; cont_with $ 
         map (\x -> Derived wl (mn_thing x)) (filter isFresh ders) }
    
    -- I am not sure I actually want to do this (e.g. from recanonicalizing a solved?)
    -- but if we plan to use xCtFlavor for rewriting as well then I might as well add a case
xCtFlavor_cache _ (Solved { flav_gloc = gl, flav_evar = evar }) ptys xev cont_with
  = do { let ev_trms = ev_decomp xev evar
       ; new_evars <- zipWithM newGivenEvVar ptys ev_trms
       ; cont_with $
         map (\x -> Solved gl (mn_thing x)) (filter isFresh new_evars) }

rewriteCtFlavor :: CtFlavor
                -> TcPredType   -- new predicate
                -> TcCoercion   -- new ~ old     
                -> TcS (Maybe CtFlavor)
rewriteCtFlavor = rewriteCtFlavor_cache True
-- Returns Nothing only if rewriting has happened and the rewritten constraint is cached
-- Returns Just if either (i) we rewrite by reflexivity or 
--                        (ii) we rewrite and original not cached

rewriteCtFlavor_cache :: Bool 
                -> CtFlavor
                -> TcPredType   -- new predicate
                -> TcCoercion   -- new ~ old     
                -> TcS (Maybe CtFlavor)
-- If derived, don't even look at the coercion
-- NB: this allows us to sneak away with ``error'' thunks for 
-- coercions that come from derived ids (which don't exist!) 
rewriteCtFlavor_cache _cache (Derived wl _pty_orig) pty_new _co
  = newDerived pty_new >>= from_mn
  where from_mn (Cached {}) = return Nothing
        from_mn (Fresh {})  = return $ Just (Derived wl pty_new)
        
rewriteCtFlavor_cache cache fl pty co
  | isTcReflCo co
  -- If just reflexivity then you may re-use the same variable as optimization
  = return (Just $ case fl of
               Derived wl _pty_orig -> Derived wl pty
               Given gl ev  -> Given  gl (setVarType ev pty)
               Wanted wl ev -> Wanted wl (setVarType ev pty)
               Solved gl ev -> Solved gl (setVarType ev pty))
  | otherwise 
  = xCtFlavor_cache cache fl [pty] (XEvTerm ev_comp ev_decomp) cont
1402
  where ev_comp [x] = mkEvCast x co
dimitris's avatar
dimitris committed
1403
        ev_comp _   = panic "Coercion can only have one subgoal"
1404
        ev_decomp x = [mkEvCast x (mkTcSymCo co)]
dimitris's avatar
dimitris committed
1405
1406
1407
1408
        cont []     = return Nothing
        cont [fl]   = return $ Just fl
        cont _      = panic "At most one constraint can be subgoal of coercion!"

1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423

-- Matching and looking up classes and family instances
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

data MatchInstResult mi
  = MatchInstNo         -- No matching instance 
  | MatchInstSingle mi  -- Single matching instance
  | MatchInstMany       -- Multiple matching instances


matchClass :: Class -> [Type] -> TcS (MatchInstResult (DFunId, [Either TyVar TcType])) 
-- Look up a class constraint in the instance environment
matchClass clas tys
  = do	{ let pred = mkClassPred clas tys 
        ; instEnvs <- getInstEnvs
1424
        ; case lookupInstEnv instEnvs clas tys of {
1425
            ([], unifs, _)               -- Nothing matches  
1426
1427
1428
1429
1430
                -> do { traceTcS "matchClass not matching"
                                 (vcat [ text "dict" <+> ppr pred, 
                                         text "unifs" <+> ppr unifs ]) 
                      ; return MatchInstNo  
                      } ;  
1431
	    ([(ispec, inst_tys)], [], _) -- A single match 
1432
1433
1434
1435
		-> do	{ let dfun_id = is_dfun ispec
			; traceTcS "matchClass success"
				   (vcat [text "dict" <+> ppr pred, 
				          text "witness" <+> ppr dfun_id
1436
                                           <+> ppr (idType dfun_id) ])
1437
				  -- Record that this dfun is needed
1438
                        ; return $ MatchInstSingle (dfun_id, inst_tys)
1439
                        } ;
1440
     	    (matches, unifs, _)          -- More than one matches 
1441
1442
1443
1444
1445
1446
1447
1448
		-> do	{ traceTcS "matchClass multiple matches, deferring choice"
			           (vcat [text "dict" <+> ppr pred,
				   	  text "matches" <+> ppr matches,
				   	  text "unifs" <+> ppr unifs])
                        ; return MatchInstMany 
		        }
	}
        }
1449

1450
matchFam :: TyCon -> [Type] -> TcS (Maybe (FamInst, [Type]))
1451
matchFam tycon args = wrapTcS $ tcLookupFamInst tycon args
1452
\end{code}
1453
1454
1455
1456
1457
1458


-- Rewriting with respect to the inert equalities 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
\begin{code}

dimitris's avatar
dimitris committed
1459
getInertEqs :: TcS (TyVarEnv Ct, InScopeSet)
1460
getInertEqs = do { inert <- getTcSInerts
dimitris's avatar
dimitris committed
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
                 ; let ics = inert_cans inert
                 ; return (inert_eqs ics, inert_eq_tvs ics) }

getCtCoercion :: EvBindMap -> Ct -> TcCoercion
-- Precondition: A CTyEqCan which is either Wanted or Given, never Derived or Solved!
getCtCoercion bs ct 
  = case lookupEvBind bs cc_id of
        -- Given and bound to a coercion term
      Just (EvBind _ (EvCoercion co)) -> co
                      -- NB: The constraint could have been rewritten due to spontaneous 
                -- unifications but because we are optimizing away mkRefls the evidence
                -- variable may still have type (alpha ~ [beta]). The constraint may 
                -- however have a more accurate type (alpha ~ [Int]) (where beta ~ Int has
                -- been previously solved by spontaneous unification). So if we are going 
                -- to use the evidence variable for rewriting other constraints, we'd better 
                -- make sure it's of the right type!
                -- Always the ctPred type is more accurate, so we just pick that type

      _ -> mkTcCoVarCo (setVarType cc_id (ctPred ct))
      
1481
  where cc_id = ctId ct
1482

1483
\end{code}