More refactoring of constraint simplification
[ghc-hetmet.git] / compiler / typecheck / TcRnTypes.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP Project, Glasgow University, 1992-2002
4 %
5 \begin{code}
6 module TcRnTypes(
7         TcRnIf, TcRn, TcM, RnM, IfM, IfL, IfG, -- The monad is opaque outside this module
8         TcRef,
9
10         -- The environment types
11         Env(..), 
12         TcGblEnv(..), TcLclEnv(..), 
13         IfGblEnv(..), IfLclEnv(..), 
14
15         -- Ranamer types
16         ErrCtxt,
17         ImportAvails(..), emptyImportAvails, plusImportAvails, 
18         WhereFrom(..), mkModDeps,
19
20         -- Typechecker types
21         TcTyThing(..), pprTcTyThingCategory, 
22
23         -- Template Haskell
24         ThStage(..), topStage, topSpliceStage,
25         ThLevel, impLevel, topLevel,
26
27         -- Arrows
28         ArrowCtxt(NoArrowCtxt), newArrowScope, escapeArrowScope,
29
30         -- Insts
31         Inst(..), InstOrigin(..), InstLoc(..), 
32         pprInstLoc, pprInstArising, instLocSpan, instLocOrigin,
33         LIE, emptyLIE, unitLIE, plusLIE, consLIE, instLoc, instSpan,
34         plusLIEs, mkLIE, isEmptyLIE, lieToList, listToLIE,
35
36         -- Misc other types
37         TcId, TcIdSet, TcDictBinds
38   ) where
39
40 #include "HsVersions.h"
41
42 import HsSyn hiding (LIE)
43 import HscTypes
44 import Packages
45 import Type
46 import TcType
47 import TcGadt
48 import InstEnv
49 import FamInstEnv
50 import IOEnv
51 import RdrName
52 import Name
53 import NameEnv
54 import NameSet
55 import Var
56 import VarEnv
57 import Module
58 import UniqFM
59 import SrcLoc
60 import VarSet
61 import ErrUtils
62 import UniqSupply
63 import BasicTypes
64 import Util
65 import Bag
66 import Outputable
67 import ListSetOps
68
69 import Data.Maybe
70 import Data.List
71 \end{code}
72
73
74 %************************************************************************
75 %*                                                                      *
76                Standard monad definition for TcRn
77     All the combinators for the monad can be found in TcRnMonad
78 %*                                                                      *
79 %************************************************************************
80
81 The monad itself has to be defined here, because it is mentioned by ErrCtxt
82
83 \begin{code}
84 type TcRef a     = IORef a
85 type TcId        = Id                   -- Type may be a TcType
86 type TcIdSet     = IdSet
87 type TcDictBinds = DictBinds TcId       -- Bag of dictionary bindings
88
89 type TcRnIf a b c = IOEnv (Env a b) c
90 type IfM lcl a  = TcRnIf IfGblEnv lcl a         -- Iface stuff
91
92 type IfG a  = IfM () a                          -- Top level
93 type IfL a  = IfM IfLclEnv a                    -- Nested
94 type TcRn a = TcRnIf TcGblEnv TcLclEnv a
95 type RnM  a = TcRn a            -- Historical
96 type TcM  a = TcRn a            -- Historical
97 \end{code}
98
99
100 %************************************************************************
101 %*                                                                      *
102                 The main environment types
103 %*                                                                      *
104 %************************************************************************
105
106 \begin{code}
107 data Env gbl lcl        -- Changes as we move into an expression
108   = Env {
109         env_top  :: HscEnv,     -- Top-level stuff that never changes
110                                 -- Includes all info about imported things
111
112         env_us   :: {-# UNPACK #-} !(IORef UniqSupply), 
113                                 -- Unique supply for local varibles
114
115         env_gbl  :: gbl,        -- Info about things defined at the top level
116                                 -- of the module being compiled
117
118         env_lcl  :: lcl         -- Nested stuff; changes as we go into 
119                                 -- an expression
120     }
121
122 -- TcGblEnv describes the top-level of the module at the 
123 -- point at which the typechecker is finished work.
124 -- It is this structure that is handed on to the desugarer
125
126 data TcGblEnv
127   = TcGblEnv {
128         tcg_mod     :: Module,          -- Module being compiled
129         tcg_src     :: HscSource,       -- What kind of module 
130                                         -- (regular Haskell, hs-boot, ext-core)
131
132         tcg_rdr_env :: GlobalRdrEnv,    -- Top level envt; used during renaming
133         tcg_default :: Maybe [Type],    -- Types used for defaulting
134                                         -- Nothing => no 'default' decl
135
136         tcg_fix_env  :: FixityEnv,      -- Just for things in this module
137
138         tcg_type_env :: TypeEnv,        -- Global type env for the module we are compiling now
139                 -- All TyCons and Classes (for this module) end up in here right away,
140                 -- along with their derived constructors, selectors.
141                 --
142                 -- (Ids defined in this module start in the local envt, 
143                 --  though they move to the global envt during zonking)
144
145         tcg_type_env_var :: TcRef TypeEnv,      
146                 -- Used only to initialise the interface-file
147                 -- typechecker in initIfaceTcRn, so that it can see stuff
148                 -- bound in this module when dealing with hi-boot recursions
149                 -- Updated at intervals (e.g. after dealing with types and classes)
150         
151         tcg_inst_env     :: InstEnv,    -- Instance envt for *home-package* 
152                                         -- modules; Includes the dfuns in 
153                                         -- tcg_insts
154         tcg_fam_inst_env :: FamInstEnv, -- Ditto for family instances
155
156                 -- Now a bunch of things about this module that are simply 
157                 -- accumulated, but never consulted until the end.  
158                 -- Nevertheless, it's convenient to accumulate them along 
159                 -- with the rest of the info from this module.
160         tcg_exports :: [AvailInfo],     -- What is exported
161         tcg_imports :: ImportAvails,    -- Information about what was imported 
162                                         --    from where, including things bound
163                                         --    in this module
164
165         tcg_dus :: DefUses,     -- What is defined in this module and what is used.
166                                 -- The latter is used to generate 
167                                 --      (a) version tracking; no need to recompile if these
168                                 --              things have not changed version stamp
169                                 --      (b) unused-import info
170
171         tcg_keep :: TcRef NameSet,      -- Locally-defined top-level names to keep alive
172                 -- "Keep alive" means give them an Exported flag, so
173                 -- that the simplifier does not discard them as dead 
174                 -- code, and so that they are exposed in the interface file
175                 -- (but not to export to the user).
176                 --
177                 -- Some things, like dict-fun Ids and default-method Ids are 
178                 -- "born" with the Exported flag on, for exactly the above reason,
179                 -- but some we only discover as we go.  Specifically:
180                 --      * The to/from functions for generic data types
181                 --      * Top-level variables appearing free in the RHS of an orphan rule
182                 --      * Top-level variables appearing free in a TH bracket
183
184         tcg_inst_uses :: TcRef NameSet, -- Home-package Dfuns actually used 
185                 -- Used to generate version dependencies
186                 -- This records usages, rather like tcg_dus, but it has to
187                 -- be a mutable variable so it can be augmented 
188                 -- when we look up an instance.  These uses of dfuns are
189                 -- rather like the free variables of the program, but
190                 -- are implicit instead of explicit.
191
192         tcg_th_used :: TcRef Bool,      -- True <=> Template Haskell syntax used
193                 -- We need this so that we can generate a dependency on the
194                 -- Template Haskell package, becuase the desugarer is going to
195                 -- emit loads of references to TH symbols.  It's rather like 
196                 -- tcg_inst_uses; the reference is implicit rather than explicit,
197                 -- so we have to zap a mutable variable.
198
199         tcg_dfun_n  :: TcRef Int,       -- Allows us to number off the names of DFuns
200                 -- It's convenient to allocate an External Name for a DFun, with
201                 -- a permanently-fixed unique, just like other top-level functions
202                 -- defined in this module.  But that means we need a canonical 
203                 -- occurrence name, distinct from all other dfuns in this module,
204                 -- and this name supply serves that purpose (df1, df2, etc).
205
206                 -- The next fields accumulate the payload of the module
207                 -- The binds, rules and foreign-decl fiels are collected
208                 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
209
210                 -- The next fields accumulate the payload of the
211                 -- module The binds, rules and foreign-decl fiels are
212                 -- collected initially in un-zonked form and are
213                 -- finally zonked in tcRnSrcDecls
214
215         tcg_rn_imports :: Maybe [LImportDecl Name],
216         tcg_rn_exports :: Maybe [Located (IE Name)],
217         tcg_rn_decls :: Maybe (HsGroup Name),   -- renamed decls, maybe
218                 -- Nothing <=> Don't retain renamed decls
219
220         tcg_binds     :: LHsBinds Id,       -- Value bindings in this module
221         tcg_deprecs   :: Deprecations,      -- ...Deprecations 
222         tcg_insts     :: [Instance],        -- ...Instances
223         tcg_fam_insts :: [FamInst],         -- ...Family instances
224         tcg_rules     :: [LRuleDecl Id],    -- ...Rules
225         tcg_fords     :: [LForeignDecl Id], -- ...Foreign import & exports
226
227         tcg_doc :: Maybe (HsDoc Name), -- Maybe Haddock documentation
228         tcg_hmi :: HaddockModInfo Name -- Haddock module information
229     }
230 \end{code}
231
232 %************************************************************************
233 %*                                                                      *
234                 The interface environments
235               Used when dealing with IfaceDecls
236 %*                                                                      *
237 %************************************************************************
238
239 \begin{code}
240 data IfGblEnv 
241   = IfGblEnv {
242         -- The type environment for the module being compiled,
243         -- in case the interface refers back to it via a reference that
244         -- was originally a hi-boot file.
245         -- We need the module name so we can test when it's appropriate
246         -- to look in this env.
247         if_rec_types :: Maybe (Module, IfG TypeEnv)
248                 -- Allows a read effect, so it can be in a mutable
249                 -- variable; c.f. handling the external package type env
250                 -- Nothing => interactive stuff, no loops possible
251     }
252
253 data IfLclEnv
254   = IfLclEnv {
255         -- The module for the current IfaceDecl
256         -- So if we see   f = \x -> x
257         -- it means M.f = \x -> x, where M is the if_mod
258         if_mod :: Module,
259
260         -- The field is used only for error reporting
261         -- if (say) there's a Lint error in it
262         if_loc :: SDoc,
263                 -- Where the interface came from:
264                 --      .hi file, or GHCi state, or ext core
265                 -- plus which bit is currently being examined
266
267         if_tv_env  :: UniqFM TyVar,     -- Nested tyvar bindings
268         if_id_env  :: UniqFM Id         -- Nested id binding
269     }
270 \end{code}
271
272
273 %************************************************************************
274 %*                                                                      *
275                 The local typechecker environment
276 %*                                                                      *
277 %************************************************************************
278
279 The Global-Env/Local-Env story
280 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
281 During type checking, we keep in the tcg_type_env
282         * All types and classes
283         * All Ids derived from types and classes (constructors, selectors)
284
285 At the end of type checking, we zonk the local bindings,
286 and as we do so we add to the tcg_type_env
287         * Locally defined top-level Ids
288
289 Why?  Because they are now Ids not TcIds.  This final GlobalEnv is
290         a) fed back (via the knot) to typechecking the 
291            unfoldings of interface signatures
292         b) used in the ModDetails of this module
293
294 \begin{code}
295 data TcLclEnv           -- Changes as we move inside an expression
296                         -- Discarded after typecheck/rename; not passed on to desugarer
297   = TcLclEnv {
298         tcl_loc  :: SrcSpan,            -- Source span
299         tcl_ctxt :: ErrCtxt,            -- Error context
300         tcl_errs :: TcRef Messages,     -- Place to accumulate errors
301
302         tcl_th_ctxt    :: ThStage,      -- Template Haskell context
303         tcl_arrow_ctxt :: ArrowCtxt,    -- Arrow-notation context
304
305         tcl_rdr :: LocalRdrEnv,         -- Local name envt
306                 -- Maintained during renaming, of course, but also during
307                 -- type checking, solely so that when renaming a Template-Haskell
308                 -- splice we have the right environment for the renamer.
309                 -- 
310                 --   Does *not* include global name envt; may shadow it
311                 --   Includes both ordinary variables and type variables;
312                 --   they are kept distinct because tyvar have a different
313                 --   occurrence contructor (Name.TvOcc)
314                 -- We still need the unsullied global name env so that
315                 --   we can look up record field names
316
317         tcl_env  :: NameEnv TcTyThing,  -- The local type environment: Ids and TyVars
318                                         -- defined in this module
319                                         
320         tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
321                         -- Namely, the in-scope TyVars bound in tcl_env, 
322                         -- plus the tyvars mentioned in the types of Ids bound in tcl_lenv
323                         -- Why mutable? see notes with tcGetGlobalTyVars
324
325         tcl_lie   :: TcRef LIE          -- Place to accumulate type constraints
326     }
327
328
329 {- Note [Given Insts]
330    ~~~~~~~~~~~~~~~~~~
331 Because of GADTs, we have to pass inwards the Insts provided by type signatures 
332 and existential contexts. Consider
333         data T a where { T1 :: b -> b -> T [b] }
334         f :: Eq a => T a -> Bool
335         f (T1 x y) = [x]==[y]
336
337 The constructor T1 binds an existential variable 'b', and we need Eq [b].
338 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we 
339 pass it inwards.
340
341 -}
342
343 ---------------------------
344 -- Template Haskell levels 
345 ---------------------------
346
347 type ThLevel = Int      
348         -- Indicates how many levels of brackets we are inside
349         --      (always >= 0)
350         -- Incremented when going inside a bracket,
351         -- decremented when going inside a splice
352         -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
353         --     original "Template meta-programmign for Haskell" paper
354
355 impLevel, topLevel :: ThLevel
356 topLevel = 1    -- Things defined at top level of this module
357 impLevel = 0    -- Imported things; they can be used inside a top level splice
358 --
359 -- For example: 
360 --      f = ...
361 --      g1 = $(map ...)         is OK
362 --      g2 = $(f ...)           is not OK; because we havn't compiled f yet
363
364
365 data ThStage
366   = Comp                                -- Ordinary compiling, at level topLevel
367   | Splice ThLevel                      -- Inside a splice
368   | Brack  ThLevel                      -- Inside brackets; 
369            (TcRef [PendingSplice])      --   accumulate pending splices here
370            (TcRef LIE)                  --   and type constraints here
371 topStage, topSpliceStage :: ThStage
372 topStage       = Comp
373 topSpliceStage = Splice (topLevel - 1)  -- Stage for the body of a top-level splice
374
375 ---------------------------
376 -- Arrow-notation context
377 ---------------------------
378
379 {-
380 In arrow notation, a variable bound by a proc (or enclosed let/kappa)
381 is not in scope to the left of an arrow tail (-<) or the head of (|..|).
382 For example
383
384         proc x -> (e1 -< e2)
385
386 Here, x is not in scope in e1, but it is in scope in e2.  This can get
387 a bit complicated:
388
389         let x = 3 in
390         proc y -> (proc z -> e1) -< e2
391
392 Here, x and z are in scope in e1, but y is not.  We implement this by
393 recording the environment when passing a proc (using newArrowScope),
394 and returning to that (using escapeArrowScope) on the left of -< and the
395 head of (|..|).
396 -}
397
398 data ArrowCtxt
399   = NoArrowCtxt
400   | ArrowCtxt (Env TcGblEnv TcLclEnv)
401
402 -- Record the current environment (outside a proc)
403 newArrowScope :: TcM a -> TcM a
404 newArrowScope
405   = updEnv $ \env ->
406         env { env_lcl = (env_lcl env) { tcl_arrow_ctxt = ArrowCtxt env } }
407
408 -- Return to the stored environment (from the enclosing proc)
409 escapeArrowScope :: TcM a -> TcM a
410 escapeArrowScope
411   = updEnv $ \ env -> case tcl_arrow_ctxt (env_lcl env) of
412         NoArrowCtxt -> env
413         ArrowCtxt env' -> env'
414
415 ---------------------------
416 -- TcTyThing
417 ---------------------------
418
419 data TcTyThing
420   = AGlobal TyThing             -- Used only in the return type of a lookup
421
422   | ATcId   {           -- Ids defined in this module; may not be fully zonked
423         tct_id :: TcId,         
424         tct_co :: Maybe HsWrapper,      -- Nothing <=>  Do not apply a GADT type refinement
425                                         --              I am wobbly, or have no free
426                                         --              type variables
427                                         -- Just co <=>  Apply any type refinement to me,
428                                         --              and record it in the coercion
429         tct_type  :: TcType,    -- Type of (coercion applied to id)
430         tct_level :: ThLevel }
431
432   | ATyVar  Name TcType         -- The type to which the lexically scoped type vaiable
433                                 -- is currently refined. We only need the Name
434                                 -- for error-message purposes
435
436   | AThing  TcKind              -- Used temporarily, during kind checking, for the
437                                 --      tycons and clases in this recursive group
438
439 instance Outputable TcTyThing where     -- Debugging only
440    ppr (AGlobal g)      = ppr g
441    ppr elt@(ATcId {})   = text "Identifier" <> 
442                           ifPprDebug (brackets (ppr (tct_id elt) <> dcolon <> ppr (tct_type elt) <> comma
443                                  <+> ppr (tct_level elt) <+> ppr (tct_co elt)))
444    ppr (ATyVar tv _)    = text "Type variable" <+> quotes (ppr tv)
445    ppr (AThing k)       = text "AThing" <+> ppr k
446
447 pprTcTyThingCategory :: TcTyThing -> SDoc
448 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
449 pprTcTyThingCategory (ATyVar {})     = ptext SLIT("Type variable")
450 pprTcTyThingCategory (ATcId {})      = ptext SLIT("Local identifier")
451 pprTcTyThingCategory (AThing {})     = ptext SLIT("Kinded thing")
452 \end{code}
453
454 \begin{code}
455 type ErrCtxt = [TidyEnv -> TcM (TidyEnv, Message)]      
456                         -- Innermost first.  Monadic so that we have a chance
457                         -- to deal with bound type variables just before error
458                         -- message construction
459 \end{code}
460
461
462 %************************************************************************
463 %*                                                                      *
464         Operations over ImportAvails
465 %*                                                                      *
466 %************************************************************************
467
468 ImportAvails summarises what was imported from where, irrespective
469 of whether the imported things are actually used or not
470 It is used      * when processing the export list
471                 * when constructing usage info for the inteface file
472                 * to identify the list of directly imported modules
473                         for initialisation purposes and
474                         for optimsed overlap checking of family instances
475                 * when figuring out what things are really unused
476
477 \begin{code}
478 data ImportAvails 
479    = ImportAvails {
480         imp_mods :: ModuleEnv (Module, Bool, SrcSpan),
481                 -- Domain is all directly-imported modules
482                 -- Bool means:
483                 --   True => import was "import Foo ()"
484                 --   False  => import was some other form
485                 --
486                 -- We need the Module in the range because we can't get
487                 --      the keys of a ModuleEnv
488                 -- Used 
489                 --   (a) to help construct the usage information in 
490                 --       the interface file; if we import somethign we
491                 --       need to recompile if the export version changes
492                 --   (b) to specify what child modules to initialise
493                 --
494                 -- We need a full ModuleEnv rather than a ModuleNameEnv
495                 -- here, because we might be importing modules of the
496                 -- same name from different packages. (currently not the case,
497                 -- but might be in the future).
498
499         imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
500                 -- Home-package modules needed by the module being compiled
501                 --
502                 -- It doesn't matter whether any of these dependencies
503                 -- are actually *used* when compiling the module; they
504                 -- are listed if they are below it at all.  For
505                 -- example, suppose M imports A which imports X.  Then
506                 -- compiling M might not need to consult X.hi, but X
507                 -- is still listed in M's dependencies.
508
509         imp_dep_pkgs :: [PackageId],
510                 -- Packages needed by the module being compiled, whether
511                 -- directly, or via other modules in this package, or via
512                 -- modules imported from other packages.
513
514         imp_orphs :: [Module],
515                 -- Orphan modules below us in the import tree (and maybe
516                 -- including us for imported modules) 
517
518         imp_finsts :: [Module]
519                 -- Family instance modules below us in the import tree  (and
520                 -- maybe including us for imported modules)
521       }
522
523 mkModDeps :: [(ModuleName, IsBootInterface)]
524           -> ModuleNameEnv (ModuleName, IsBootInterface)
525 mkModDeps deps = foldl add emptyUFM deps
526                where
527                  add env elt@(m,_) = addToUFM env m elt
528
529 emptyImportAvails :: ImportAvails
530 emptyImportAvails = ImportAvails { imp_mods     = emptyModuleEnv,
531                                    imp_dep_mods = emptyUFM,
532                                    imp_dep_pkgs = [],
533                                    imp_orphs    = [],
534                                    imp_finsts   = [] }
535
536 plusImportAvails ::  ImportAvails ->  ImportAvails ->  ImportAvails
537 plusImportAvails
538   (ImportAvails { imp_mods = mods1,
539                   imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1, 
540                   imp_orphs = orphs1, imp_finsts = finsts1 })
541   (ImportAvails { imp_mods = mods2,
542                   imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
543                   imp_orphs = orphs2, imp_finsts = finsts2 })
544   = ImportAvails { imp_mods     = mods1  `plusModuleEnv` mods2, 
545                    imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2, 
546                    imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
547                    imp_orphs    = orphs1 `unionLists` orphs2,
548                    imp_finsts   = finsts1 `unionLists` finsts2 }
549   where
550     plus_mod_dep (m1, boot1) (m2, boot2) 
551         = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
552                 -- Check mod-names match
553           (m1, boot1 && boot2)  -- If either side can "see" a non-hi-boot interface, use that
554 \end{code}
555
556 %************************************************************************
557 %*                                                                      *
558 \subsection{Where from}
559 %*                                                                      *
560 %************************************************************************
561
562 The @WhereFrom@ type controls where the renamer looks for an interface file
563
564 \begin{code}
565 data WhereFrom 
566   = ImportByUser IsBootInterface        -- Ordinary user import (perhaps {-# SOURCE #-})
567   | ImportBySystem                      -- Non user import.
568
569 instance Outputable WhereFrom where
570   ppr (ImportByUser is_boot) | is_boot     = ptext SLIT("{- SOURCE -}")
571                              | otherwise   = empty
572   ppr ImportBySystem                       = ptext SLIT("{- SYSTEM -}")
573 \end{code}
574
575
576 %************************************************************************
577 %*                                                                      *
578 \subsection[Inst-types]{@Inst@ types}
579 %*                                                                      *
580 v%************************************************************************
581
582 An @Inst@ is either a dictionary, an instance of an overloaded
583 literal, or an instance of an overloaded value.  We call the latter a
584 ``method'' even though it may not correspond to a class operation.
585 For example, we might have an instance of the @double@ function at
586 type Int, represented by
587
588         Method 34 doubleId [Int] origin
589
590 \begin{code}
591 data Inst
592   = Dict {
593         tci_name :: Name,
594         tci_pred :: TcPredType,
595         tci_loc  :: InstLoc 
596     }
597
598   | ImplicInst {        -- An implication constraint
599                         -- forall tvs. (reft, given) => wanted
600         tci_name   :: Name,
601         tci_tyvars :: [TcTyVar],    -- Quantified type variables
602                                     -- Includes coercion variables
603                                     --   mentioned in tci_reft
604         tci_reft   :: Refinement,
605         tci_given  :: [Inst],       -- Only Dicts
606                                     --   (no Methods, LitInsts, ImplicInsts)
607         tci_wanted :: [Inst],       -- Only Dicts and ImplicInsts
608                                     --   (no Methods or LitInsts)
609
610         tci_loc    :: InstLoc
611     }
612         -- NB: the tci_given are not necessarily rigid,
613         --     although they will be if the tci_reft is non-trivial
614         -- NB: the tci_reft is already applied to tci_given and tci_wanted
615
616   | Method {
617         tci_id :: TcId,         -- The Id for the Inst
618
619         tci_oid :: TcId,        -- The overloaded function
620                 -- This function will be a global, local, or ClassOpId;
621                 --   inside instance decls (only) it can also be an InstId!
622                 -- The id needn't be completely polymorphic.
623                 -- You'll probably find its name (for documentation purposes)
624                 --        inside the InstOrigin
625
626         tci_tys :: [TcType],    -- The types to which its polymorphic tyvars
627                                 --      should be instantiated.
628                                 -- These types must saturate the Id's foralls.
629
630         tci_theta :: TcThetaType,       
631                         -- The (types of the) dictionaries to which the function
632                         -- must be applied to get the method
633
634         tci_loc :: InstLoc 
635     }
636         -- INVARIANT 1: in (Method m f tys theta tau loc)
637         --      type of m = type of (f tys dicts(from theta))
638
639         -- INVARIANT 2: type of m must not be of form (Pred -> Tau)
640         --   Reason: two methods are considered equal if the 
641         --           base Id matches, and the instantiating types
642         --           match.  The TcThetaType should then match too.
643         --   This only bites in the call to tcInstClassOp in TcClassDcl.mkMethodBind
644
645   | LitInst {
646         tci_name :: Name,
647         tci_lit  :: HsOverLit Name,     -- The literal from the occurrence site
648                         -- INVARIANT: never a rebindable-syntax literal
649                         -- Reason: tcSyntaxName does unification, and we
650                         --         don't want to deal with that during tcSimplify,
651                         --         when resolving LitInsts
652
653         tci_ty :: TcType,       -- The type at which the literal is used
654         tci_loc :: InstLoc
655     }
656 \end{code}
657
658 @Insts@ are ordered by their class/type info, rather than by their
659 unique.  This allows the context-reduction mechanism to use standard finite
660 maps to do their stuff.  It's horrible that this code is here, rather
661 than with the Avails handling stuff in TcSimplify
662
663 \begin{code}
664 instance Ord Inst where
665   compare = cmpInst
666
667 instance Eq Inst where
668   (==) i1 i2 = case i1 `cmpInst` i2 of
669                  EQ    -> True
670                  other -> False
671
672 cmpInst d1@(Dict {})    d2@(Dict {})    = tci_pred d1 `tcCmpPred` tci_pred d2
673 cmpInst (Dict {})       other           = LT
674
675 cmpInst (Method {})     (Dict {})       = GT
676 cmpInst m1@(Method {})  m2@(Method {})  = (tci_oid m1 `compare` tci_oid m2) `thenCmp`
677                                           (tci_tys m1 `tcCmpTypes` tci_tys m2)
678 cmpInst (Method {})     other           = LT
679
680 cmpInst (LitInst {})    (Dict {})       = GT
681 cmpInst (LitInst {})    (Method {})     = GT
682 cmpInst l1@(LitInst {}) l2@(LitInst {}) = (tci_lit l1 `compare` tci_lit l2) `thenCmp`
683                                           (tci_ty l1 `tcCmpType` tci_ty l2)
684 cmpInst (LitInst {})    other           = LT
685
686         -- Implication constraints are compared by *name*
687         -- not by type; that is, we make no attempt to do CSE on them
688 cmpInst (ImplicInst {})    (Dict {})          = GT
689 cmpInst (ImplicInst {})    (Method {})        = GT
690 cmpInst (ImplicInst {})    (LitInst {})       = GT
691 cmpInst i1@(ImplicInst {}) i2@(ImplicInst {}) = tci_name i1 `compare` tci_name i2
692 \end{code}
693
694
695 %************************************************************************
696 %*                                                                      *
697 \subsection[Inst-collections]{LIE: a collection of Insts}
698 %*                                                                      *
699 %************************************************************************
700
701 \begin{code}
702 -- FIXME: Rename this. It clashes with (Located (IE ...))
703 type LIE = Bag Inst
704
705 isEmptyLIE        = isEmptyBag
706 emptyLIE          = emptyBag
707 unitLIE inst      = unitBag inst
708 mkLIE insts       = listToBag insts
709 plusLIE lie1 lie2 = lie1 `unionBags` lie2
710 plusLIEs lies     = unionManyBags lies
711 lieToList         = bagToList
712 listToLIE         = listToBag
713
714 consLIE inst lie  = lie `snocBag` inst
715 -- Putting the new Inst at the *end* of the bag is a half-hearted attempt
716 -- to ensure that we tend to report the *leftmost* type-constraint error
717 -- E.g.         f :: [a]
718 --              f = [1,2,3]
719 -- we'd like to complain about the '1', not the '3'.
720 --
721 -- "Half-hearted" because the rest of the type checker makes no great
722 -- claims for retaining order in the constraint set.  Still, this 
723 -- seems to improve matters slightly.  Exampes: mdofail001, tcfail015
724 \end{code}
725
726
727 %************************************************************************
728 %*                                                                      *
729 \subsection[Inst-origin]{The @InstOrigin@ type}
730 %*                                                                      *
731 %************************************************************************
732
733 The @InstOrigin@ type gives information about where a dictionary came from.
734 This is important for decent error message reporting because dictionaries
735 don't appear in the original source code.  Doubtless this type will evolve...
736
737 It appears in TcMonad because there are a couple of error-message-generation
738 functions that deal with it.
739
740 \begin{code}
741 -------------------------------------------
742 data InstLoc = InstLoc InstOrigin SrcSpan ErrCtxt
743
744 instLoc :: Inst -> InstLoc
745 instLoc inst = tci_loc inst
746
747 instSpan :: Inst -> SrcSpan
748 instSpan wanted = instLocSpan (instLoc wanted)
749
750 instLocSpan :: InstLoc -> SrcSpan
751 instLocSpan (InstLoc _ s _) = s
752
753 instLocOrigin :: InstLoc -> InstOrigin
754 instLocOrigin (InstLoc o _ _) = o
755
756 pprInstArising :: Inst -> SDoc
757 pprInstArising loc = ptext SLIT("arising from") <+> pprInstLoc (tci_loc loc)
758
759 pprInstLoc :: InstLoc -> SDoc
760 pprInstLoc (InstLoc orig span _) = sep [ppr orig, text "at" <+> ppr span]
761
762 -------------------------------------------
763 data InstOrigin
764   = SigOrigin SkolemInfo        -- Pattern, class decl, inst decl etc;
765                                 -- Places that bind type variables and introduce
766                                 -- available constraints
767
768   | IPBindOrigin (IPName Name)  -- Binding site of an implicit parameter
769
770         -------------------------------------------------------
771         -- The rest are all occurrences: Insts that are 'wanted'
772         -------------------------------------------------------
773   | OccurrenceOf Name           -- Occurrence of an overloaded identifier
774
775   | IPOccOrigin  (IPName Name)  -- Occurrence of an implicit parameter
776
777   | LiteralOrigin (HsOverLit Name)      -- Occurrence of a literal
778
779   | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
780   | PArrSeqOrigin  (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
781
782   | InstSigOrigin       -- A dict occurrence arising from instantiating
783                         -- a polymorphic type during a subsumption check
784
785   | RecordUpdOrigin
786   | InstScOrigin        -- Typechecking superclasses of an instance declaration
787   | DerivOrigin         -- Typechecking deriving
788   | StandAloneDerivOrigin -- Typechecking stand-alone deriving
789   | DefaultOrigin       -- Typechecking a default decl
790   | DoOrigin            -- Arising from a do expression
791   | ProcOrigin          -- Arising from a proc expression
792   | ImplicOrigin SDoc   -- An implication constraint
793
794 instance Outputable InstOrigin where
795     ppr (OccurrenceOf name)   = hsep [ptext SLIT("a use of"), quotes (ppr name)]
796     ppr (IPOccOrigin name)    = hsep [ptext SLIT("a use of implicit parameter"), quotes (ppr name)]
797     ppr (IPBindOrigin name)   = hsep [ptext SLIT("a binding for implicit parameter"), quotes (ppr name)]
798     ppr RecordUpdOrigin       = ptext SLIT("a record update")
799     ppr (LiteralOrigin lit)   = hsep [ptext SLIT("the literal"), quotes (ppr lit)]
800     ppr (ArithSeqOrigin seq)  = hsep [ptext SLIT("the arithmetic sequence"), quotes (ppr seq)]
801     ppr (PArrSeqOrigin seq)   = hsep [ptext SLIT("the parallel array sequence"), quotes (ppr seq)]
802     ppr InstSigOrigin         = ptext SLIT("instantiating a type signature")
803     ppr InstScOrigin          = ptext SLIT("the superclasses of an instance declaration")
804     ppr DerivOrigin           = ptext SLIT("the 'deriving' clause of a data type declaration")
805     ppr StandAloneDerivOrigin = ptext SLIT("a 'deriving' declaration")
806     ppr DefaultOrigin         = ptext SLIT("a 'default' declaration")
807     ppr DoOrigin              = ptext SLIT("a do statement")
808     ppr ProcOrigin            = ptext SLIT("a proc expression")
809     ppr (ImplicOrigin doc)    = doc
810     ppr (SigOrigin info)      = pprSkolInfo info
811 \end{code}