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