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