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