[project @ 2003-06-24 07:58:18 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcRnTypes.lhs
1 %
2 % (c) The GRASP Project, Glasgow University, 1992-2002
3 %
4 \begin{code}
5 module TcRnTypes(
6         TcRn, TcM, RnM, -- The monad is opaque outside this module
7
8         -- Standard monadic operations
9         thenM, thenM_, returnM, failM,
10
11         -- Non-standard operations
12         runTcRn, fixM, tryM, ioToTcRn,
13         newMutVar, readMutVar, writeMutVar,
14         getEnv, setEnv, updEnv, unsafeInterleaveM, zapEnv,
15                 
16         -- The environment types
17         Env(..), TopEnv(..), TcGblEnv(..), 
18         TcLclEnv(..), RnLclEnv(..),
19
20         -- Ranamer types
21         RnMode(..), isInterfaceMode, isCmdLineMode,
22         EntityUsage, emptyUsages, ErrCtxt,
23         ImportAvails(..), emptyImportAvails, plusImportAvails, 
24         plusAvail, pruneAvails,  
25         AvailEnv, emptyAvailEnv, unitAvailEnv, plusAvailEnv, 
26         mkAvailEnv, lookupAvailEnv, lookupAvailEnv_maybe, availEnvElts, addAvail,
27         WhereFrom(..),
28
29         -- Typechecker types
30         TcTyThing(..),
31
32         -- Template Haskell
33         ThStage(..), topStage, topSpliceStage,
34         ThLevel, impLevel, topLevel,
35
36         -- Arrows
37         ArrowCtxt(..), topArrowCtxt, ProcLevel, topProcLevel, 
38
39         -- Insts
40         Inst(..), InstOrigin(..), InstLoc(..), pprInstLoc, instLocSrcLoc,
41         LIE, emptyLIE, unitLIE, plusLIE, consLIE, 
42         plusLIEs, mkLIE, isEmptyLIE, lieToList, listToLIE,
43
44         -- Misc other types
45         TcRef, TcId, TcIdSet
46   ) where
47
48 #include "HsVersions.h"
49
50 import HsSyn            ( PendingSplice, HsOverLit, MonoBinds, RuleDecl, ForeignDecl )
51 import RnHsSyn          ( RenamedHsExpr, RenamedPat, RenamedArithSeqInfo )
52 import HscTypes         ( GhciMode, ExternalPackageState, HomePackageTable, 
53                           NameCache, GlobalRdrEnv, LocalRdrEnv, FixityEnv,
54                           TypeEnv, TyThing, Avails, GenAvailInfo(..), AvailInfo,
55                            availName, IsBootInterface, Deprecations,
56                            ExternalPackageState(..), emptyExternalPackageState )
57 import Packages         ( PackageName )
58 import TcType           ( TcTyVarSet, TcType, TcTauType, TcThetaType, 
59                           TcPredType, TcKind, tcCmpPred, tcCmpType, tcCmpTypes )
60 import InstEnv          ( DFunId, InstEnv )
61 import Name             ( Name )
62 import NameEnv
63 import NameSet          ( NameSet, emptyNameSet )
64 import Type             ( Type )
65 import Class            ( Class )
66 import Var              ( Id, TyVar )
67 import VarEnv           ( TidyEnv )
68 import Module
69 import SrcLoc           ( SrcLoc )
70 import VarSet           ( IdSet )
71 import ErrUtils         ( Messages, Message )
72 import CmdLineOpts      ( DynFlags )
73 import UniqSupply       ( UniqSupply )
74 import BasicTypes       ( IPName )
75 import Util             ( thenCmp )
76 import Bag
77 import Outputable
78 import DATA_IOREF       ( IORef, newIORef, readIORef, writeIORef )
79 import UNSAFE_IO        ( unsafeInterleaveIO )
80 import FIX_IO           ( fixIO )
81 import EXCEPTION        ( Exception(..) )
82 import IO               ( isUserError )
83 import Maybe            ( mapMaybe )
84 import ListSetOps       ( unionLists )
85 import Panic            ( tryJust )
86 \end{code}
87
88
89 \begin{code}
90 type TcRef a = IORef a
91 type TcId    = Id                       -- Type may be a TcType
92 type TcIdSet = IdSet
93 \end{code}
94
95 %************************************************************************
96 %*                                                                      *
97                Standard monad definition for TcRn
98     All the combinators for the monad can be found in TcRnMonad
99 %*                                                                      *
100 %************************************************************************
101
102 The monad itself has to be defined here, 
103 because it is mentioned by ErrCtxt
104
105 \begin{code}
106 newtype TcRn m a = TcRn (Env m -> IO a)
107 unTcRn (TcRn f) = f
108
109 type TcM a = TcRn TcLclEnv a
110 type RnM a = TcRn RnLclEnv a
111
112 returnM :: a -> TcRn m a
113 returnM a = TcRn (\ env -> return a)
114
115 thenM :: TcRn m a -> (a -> TcRn m b) -> TcRn m b
116 thenM (TcRn m) f = TcRn (\ env -> do { r <- m env ;
117                                        unTcRn (f r) env })
118
119 thenM_ :: TcRn m a -> TcRn m b -> TcRn m b
120 thenM_ (TcRn m) f = TcRn (\ env -> do { m env ; unTcRn f env })
121
122 failM :: TcRn m a
123 failM = TcRn (\ env -> ioError (userError "TcRn failure"))
124
125 instance Monad (TcRn m) where
126   (>>=)  = thenM
127   (>>)   = thenM_
128   return = returnM
129   fail s = failM        -- Ignore the string
130 \end{code}
131
132
133 %************************************************************************
134 %*                                                                      *
135         Fundmantal combinators specific to the monad
136 %*                                                                      *
137 %************************************************************************
138
139 Running it
140
141 \begin{code}
142 runTcRn :: Env m -> TcRn m a -> IO a
143 runTcRn env (TcRn m) = m env
144 \end{code}
145
146 The fixpoint combinator
147
148 \begin{code}
149 {-# NOINLINE fixM #-}
150   -- Aargh!  Not inlining fixTc alleviates a space leak problem.
151   -- Normally fixTc is used with a lazy tuple match: if the optimiser is
152   -- shown the definition of fixTc, it occasionally transforms the code
153   -- in such a way that the code generator doesn't spot the selector
154   -- thunks.  Sigh.
155
156 fixM :: (a -> TcRn m a) -> TcRn m a
157 fixM f = TcRn (\ env -> fixIO (\ r -> unTcRn (f r) env))
158 \end{code}
159
160 Error recovery
161
162 \begin{code}
163 tryM :: TcRn m r -> TcRn m (Either Exception r)
164 -- Reflect exception into TcRn monad
165 tryM (TcRn thing) = TcRn (\ env -> tryJust tc_errors (thing env))
166   where 
167 #if __GLASGOW_HASKELL__ > 504 || __GLASGOW_HASKELL__ < 500
168         tc_errors e@(IOException ioe) | isUserError ioe = Just e
169 #elif __GLASGOW_HASKELL__ == 502
170         tc_errors e@(UserError _) = Just e
171 #else 
172         tc_errors e@(IOException ioe) | isUserError e = Just e
173 #endif
174         tc_errors _other = Nothing
175         -- type checker failures show up as UserErrors only
176 \end{code}
177
178 Lazy interleave 
179
180 \begin{code}
181 unsafeInterleaveM :: TcRn m a -> TcRn m a
182 unsafeInterleaveM (TcRn m) = TcRn (\ env -> unsafeInterleaveIO (m env))
183 \end{code}
184
185 \end{code}
186
187 Performing arbitrary I/O, plus the read/write var (for efficiency)
188
189 \begin{code}
190 ioToTcRn :: IO a -> TcRn m a
191 ioToTcRn io = TcRn (\ env -> io)
192
193 newMutVar :: a -> TcRn m (TcRef a)
194 newMutVar val = TcRn (\ env -> newIORef val)
195
196 writeMutVar :: TcRef a -> a -> TcRn m ()
197 writeMutVar var val = TcRn (\ env -> writeIORef var val)
198
199 readMutVar :: TcRef a -> TcRn m a
200 readMutVar var = TcRn (\ env -> readIORef var)
201 \end{code}
202
203 Getting the environment
204
205 \begin{code}
206 getEnv :: TcRn m (Env m)
207 {-# INLINE getEnv #-}
208 getEnv = TcRn (\ env -> return env)
209
210 setEnv :: Env n -> TcRn n a -> TcRn m a
211 {-# INLINE setEnv #-}
212 setEnv new_env (TcRn m) = TcRn (\ env -> m new_env)
213
214 updEnv :: (Env m -> Env n) -> TcRn n a -> TcRn m a
215 {-# INLINE updEnv #-}
216 updEnv upd (TcRn m) = TcRn (\ env -> m (upd env))
217 \end{code}
218
219 \begin{code}
220 zapEnv :: TcRn m a -> TcRn m a
221 zapEnv act = TcRn $ \env@Env{ env_top=top, env_gbl=gbl, env_lcl=lcl } ->
222   case top of {
223    TopEnv{ 
224      top_mode    = mode,
225      top_dflags  = dflags,
226      top_hpt     = hpt,
227      top_eps     = eps,
228      top_us      = us
229     } -> do
230
231   eps_snap <- readIORef eps
232   ref <- newIORef $! emptyExternalPackageState{ eps_PTE = eps_PTE eps_snap }
233
234   let
235      top' = TopEnv {
236                 top_mode   = mode,
237                 top_dflags = dflags,
238                 top_hpt    = hpt,
239                 top_eps    = ref,
240                 top_us     = us
241             }
242
243      type_env = tcg_type_env gbl
244      mod = tcg_mod gbl
245      gbl' = TcGblEnv {
246                 tcg_mod = mod,
247                 tcg_type_env = type_env
248             }
249
250      env' = Env {
251                 env_top = top',
252                 env_gbl = gbl',
253                 env_lcl = lcl
254                 -- leave the rest empty
255              }
256
257   case act of { TcRn f -> f env' }
258  }
259 \end{code}
260
261 %************************************************************************
262 %*                                                                      *
263                 The main environment types
264 %*                                                                      *
265 %************************************************************************
266
267 \begin{code}
268 data Env a      -- Changes as we move into an expression
269   = Env {
270         env_top  :: TopEnv,     -- Top-level stuff that never changes
271                                 --   Mainly a bunch of updatable refs
272                                 --   Includes all info about imported things
273         env_gbl  :: TcGblEnv,   -- Info about things defined at the top leve
274                                 --   of the module being compiled
275
276         env_lcl  :: a,          -- Different for the type checker 
277                                 -- and the renamer
278
279         env_loc  :: SrcLoc      -- Source location
280     }
281
282 data TopEnv     -- Built once at top level then does not change
283                 -- Concerns imported stuff
284                 -- Exceptions: error recovery points, meta computation points
285    = TopEnv {
286         top_mode    :: GhciMode,
287         top_dflags  :: DynFlags,
288
289         -- Stuff about imports
290         top_eps    :: TcRef ExternalPackageState,
291                 -- PIT, ImportedModuleInfo
292                 -- DeclsMap, IfaceRules, IfaceInsts, InstGates
293                 -- TypeEnv, InstEnv, RuleBase
294                 -- Mutable, because we demand-load declarations that extend the state
295
296         top_hpt  :: HomePackageTable,
297                 -- The home package table that we've accumulated while 
298                 -- compiling the home package, 
299                 -- *excluding* the module we are compiling right now.
300                 -- (In one-shot mode the current module is the only
301                 --  home-package module, so tc_hpt is empty.  All other
302                 --  modules count as "external-package" modules.)
303                 -- tc_hpt is not mutable because we only demand-load 
304                 -- external packages; the home package is eagerly 
305                 -- loaded by the compilation manager.
306
307         -- The global name supply
308         top_nc     :: TcRef NameCache,          -- Maps original names to Names
309         top_us     :: TcRef UniqSupply,         -- Unique supply for this module
310         top_errs   :: TcRef Messages
311    }
312
313 -- TcGblEnv describes the top-level of the module at the 
314 -- point at which the typechecker is finished work.
315 -- It is this structure that is handed on to the desugarer
316
317 data TcGblEnv
318   = TcGblEnv {
319         tcg_mod    :: Module,           -- Module being compiled
320         tcg_usages :: TcRef EntityUsage,  -- What version of what entities 
321                                           -- have been used from other home-pkg modules
322         tcg_rdr_env :: GlobalRdrEnv,    -- Top level envt; used during renaming
323         tcg_fix_env :: FixityEnv,       -- Ditto
324         tcg_default :: [Type],          -- Types used for defaulting
325
326         tcg_type_env :: TypeEnv,        -- Global type env for the module we are compiling now
327                 -- All TyCons and Classes (for this module) end up in here right away,
328                 -- along with their derived constructors, selectors.
329                 --
330                 -- (Ids defined in this module start in the local envt, 
331                 --  though they move to the global envt during zonking)
332         
333         tcg_inst_env :: TcRef InstEnv,  -- Global instance env: a combination of 
334                                         --      tc_pcs, tc_hpt, *and* tc_insts
335                 -- This field is mutable so that it can be updated inside a
336                 -- Template Haskell splice, which might suck in some new
337                 -- instance declarations.  This is a slightly different strategy
338                 -- than for the type envt, where we look up first in tcg_type_env
339                 -- and then in the mutable EPS, because the InstEnv for this module
340                 -- is constructed (in principle at least) only from the modules
341                 -- 'below' this one, so it's this-module-specific
342                 --
343                 -- On the other hand, a declaration quote [d| ... |] may introduce
344                 -- some new instance declarations that we *don't* want to persist
345                 -- outside the quote, so we tiresomely need to revert the InstEnv
346                 -- after finishing the quote (see TcSplice.tcBracket)
347
348                 -- Now a bunch of things about this module that are simply 
349                 -- accumulated, but never consulted until the end.  
350                 -- Nevertheless, it's convenient to accumulate them along 
351                 -- with the rest of the info from this module.
352         tcg_exports :: Avails,                  -- What is exported
353         tcg_imports :: ImportAvails,            -- Information about what was imported 
354                                                 --    from where, including things bound
355                                                 --    in this module
356
357                 -- The next fields accumulate the payload of the module
358                 -- The binds, rules and foreign-decl fiels are collected
359                 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
360         tcg_binds   :: MonoBinds Id,            -- Value bindings in this module
361         tcg_deprecs :: Deprecations,            -- ...Deprecations 
362         tcg_insts   :: [DFunId],                -- ...Instances
363         tcg_rules   :: [RuleDecl Id],           -- ...Rules
364         tcg_fords   :: [ForeignDecl Id]         -- ...Foreign import & exports
365     }
366 \end{code}
367
368
369 %************************************************************************
370 %*                                                                      *
371                 The local typechecker environment
372 %*                                                                      *
373 %************************************************************************
374
375 The Global-Env/Local-Env story
376 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
377 During type checking, we keep in the tcg_type_env
378         * All types and classes
379         * All Ids derived from types and classes (constructors, selectors)
380
381 At the end of type checking, we zonk the local bindings,
382 and as we do so we add to the tcg_type_env
383         * Locally defined top-level Ids
384
385 Why?  Because they are now Ids not TcIds.  This final GlobalEnv is
386         a) fed back (via the knot) to typechecking the 
387            unfoldings of interface signatures
388         b) used in the ModDetails of this module
389
390 \begin{code}
391 data TcLclEnv
392   = TcLclEnv {
393         tcl_ctxt :: ErrCtxt,    -- Error context
394
395         tcl_th_ctxt    :: ThStage,      -- Template Haskell context
396         tcl_arrow_ctxt :: ArrowCtxt,    -- Arrow-notation context
397
398         tcl_env    :: NameEnv TcTyThing,  -- The local type environment: Ids and TyVars
399                                           -- defined in this module
400                                         
401         tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
402                                         -- Namely, the in-scope TyVars bound in tcl_lenv, 
403                                         -- plus the tyvars mentioned in the types of 
404                                         -- Ids bound in tcl_lenv
405                                         -- Why mutable? see notes with tcGetGlobalTyVars
406
407         tcl_lie :: TcRef LIE            -- Place to accumulate type constraints
408     }
409
410 ---------------------------
411 -- Template Haskell levels 
412 ---------------------------
413
414 type ThLevel = Int      -- Always >= 0
415
416 data ThStage
417   = Comp                                -- Ordinary compiling, at level topLevel
418   | Splice ThLevel                      -- Inside a splice
419   | Brack  ThLevel                      -- Inside brackets; 
420            (TcRef [PendingSplice])      --   accumulate pending splices here
421            (TcRef LIE)                  --   and type constraints here
422 topStage, topSpliceStage :: ThStage
423 topStage       = Comp
424 topSpliceStage = Splice (topLevel - 1)  -- Stage for the body of a top-level splice
425
426
427 impLevel, topLevel :: ThLevel
428 topLevel = 1    -- Things defined at top level of this module
429 impLevel = 0    -- Imported things; they can be used inside a top level splice
430 --
431 -- For example: 
432 --      f = ...
433 --      g1 = $(map ...)         is OK
434 --      g2 = $(f ...)           is not OK; because we havn't compiled f yet
435
436
437 ---------------------------
438 -- Arrow-notation stages
439 ---------------------------
440
441 -- In arrow notation, a variable bound by a proc (or enclosed let/kappa)
442 -- is not in scope to the left of an arrow tail (-<).  For example
443 --
444 --      proc x -> (e1 -< e2)
445 --
446 -- Here, x is not in scope in e1, but it is in scope in e2.  This can get 
447 -- a bit complicated:
448 --
449 --      let x = 3 in
450 --      prox y -> (proc z -> e1) -< e2
451 --
452 -- Here, x and z are in scope in e1, but y is not.  Here's how we track this:
453 --      a) Assign an "proc level" to each proc, being the number of
454 --         lexically-enclosing procs + 1.  
455 --      b) Assign to each local variable the proc-level of its lexically
456 --         enclosing proc.
457 --      c) Keep a list of out-of-scope procs.  When moving to the left of
458 --         an arrow-tail, add the proc-level of the immediately enclosing
459 --         proc to the list.
460 --      d) When looking up a variable, complain if its proc-level is in
461 --         the banned list
462
463 type ProcLevel = Int    -- Always >= 0
464 topProcLevel = 0        -- Not inside any proc
465
466 data ArrowCtxt = ArrCtxt { proc_level :: ProcLevel,     -- Current level
467                            proc_banned :: [ProcLevel] } -- Out of scope proc-levels
468
469 topArrowCtxt = ArrCtxt { proc_level = topProcLevel, proc_banned = [] }
470
471 ---------------------------
472 -- TcTyThing
473 ---------------------------
474
475 data TcTyThing
476   = AGlobal TyThing                     -- Used only in the return type of a lookup
477   | ATcId   TcId ThLevel ProcLevel      -- Ids defined in this module; may not be fully zonked
478   | ATyVar  TyVar                       -- Type variables
479   | AThing  TcKind                      -- Used temporarily, during kind checking
480 -- Here's an example of how the AThing guy is used
481 -- Suppose we are checking (forall a. T a Int):
482 --      1. We first bind (a -> AThink kv), where kv is a kind variable. 
483 --      2. Then we kind-check the (T a Int) part.
484 --      3. Then we zonk the kind variable.
485 --      4. Now we know the kind for 'a', and we add (a -> ATyVar a::K) to the environment
486
487 instance Outputable TcTyThing where     -- Debugging only
488    ppr (AGlobal g)     = text "AGlobal" <+> ppr g
489    ppr (ATcId g tl pl) = text "ATcId" <+> ppr g <+> ppr tl <+> ppr pl
490    ppr (ATyVar t)      = text "ATyVar" <+> ppr t
491    ppr (AThing k)      = text "AThing" <+> ppr k
492 \end{code}
493
494 \begin{code}
495 type ErrCtxt = [TidyEnv -> TcM (TidyEnv, Message)]      
496                         -- Innermost first.  Monadic so that we have a chance
497                         -- to deal with bound type variables just before error
498                         -- message construction
499 \end{code}
500
501
502 %************************************************************************
503 %*                                                                      *
504                 The local renamer environment
505 %*                                                                      *
506 %************************************************************************
507
508 \begin{code}
509 data RnLclEnv
510   = RnLclEnv {
511         rn_mode :: RnMode,
512         rn_lenv :: LocalRdrEnv          -- Local name envt
513                 --   Does *not* include global name envt; may shadow it
514                 --   Includes both ordinary variables and type variables;
515                 --   they are kept distinct because tyvar have a different
516                 --   occurrence contructor (Name.TvOcc)
517                 -- We still need the unsullied global name env so that
518                 --   we can look up record field names
519      }  
520
521 data RnMode = SourceMode                -- Renaming source code
522             | InterfaceMode Module      -- Renaming interface declarations from M
523             | CmdLineMode               -- Renaming a command-line expression
524
525 isInterfaceMode (InterfaceMode _) = True
526 isInterfaceMode _                 = False
527
528 isCmdLineMode CmdLineMode = True
529 isCmdLineMode _ = False
530 \end{code}
531
532
533 %************************************************************************
534 %*                                                                      *
535                         EntityUsage
536 %*                                                                      *
537 %************************************************************************
538
539 EntityUsage tells what things are actually need in order to compile this
540 module.  It is used for generating the usage-version field of the ModIface.
541
542 Note that we do not record version info for entities from 
543 other (non-home) packages.  If the package changes, GHC doesn't help.
544
545 \begin{code}
546 type EntityUsage = NameSet
547         -- The Names are all the (a) home-package
548         --                       (b) "big" (i.e. no data cons, class ops)
549         --                       (c) non-locally-defined
550         --                       (d) non-wired-in
551         -- names that have been slurped in so far.
552         -- This is used to generate the "usage" information for this module.
553
554 emptyUsages :: EntityUsage
555 emptyUsages = emptyNameSet
556 \end{code}
557
558
559 %************************************************************************
560 %*                                                                      *
561         Operations over ImportAvails
562 %*                                                                      *
563 %************************************************************************
564
565 ImportAvails summarises what was imported from where, irrespective
566 of whether the imported htings are actually used or not
567 It is used      * when processing the export list
568                 * when constructing usage info for the inteface file
569                 * to identify the list of directly imported modules
570                         for initialisation purposes
571                 * when figuring out what things are really unused
572
573 \begin{code}
574 data ImportAvails 
575    = ImportAvails {
576         imp_env :: AvailEnv,
577                 -- All the things that are available from the import
578                 -- Its domain is all the "main" things;
579                 -- i.e. *excluding* class ops and constructors
580                 --      (which appear inside their parent AvailTC)
581
582         imp_qual :: ModuleEnv AvailEnv,
583                 -- Used to figure out "module M" export specifiers
584                 -- (see 1.4 Report Section 5.1.1).  Ultimately, we want to find 
585                 -- everything that is unambiguously in scope as 'M.x'
586                 -- and where plain 'x' is (perhaps ambiguously) in scope.
587                 -- So the starting point is all things that are in scope as 'M.x',
588                 -- which is what this field tells us.
589                 --
590                 -- Domain is the *module qualifier* for imports.
591                 --   e.g.        import List as Foo
592                 -- would add a binding Foo |-> ...stuff from List...
593                 -- to imp_qual.
594                 -- We keep the stuff as an AvailEnv so that it's easy to 
595                 -- combine stuff coming from different (unqualified) 
596                 -- imports of the same module
597
598         imp_mods :: ModuleEnv (Module, Bool),
599                 -- Domain is all directly-imported modules
600                 -- Bool is True if there was an unrestricted import
601                 --      (i.e. not a selective list)
602                 -- We need the Module in the range because we can't get
603                 --      the keys of a ModuleEnv
604                 -- Used 
605                 --   (a) to help construct the usage information in 
606                 --       the interface file; if we import everything we
607                 --       need to recompile if the module version changes
608                 --   (b) to specify what child modules to initialise
609
610         imp_dep_mods :: ModuleEnv (ModuleName, IsBootInterface),
611                 -- Home-package modules needed by the module being compiled
612                 --
613                 -- It doesn't matter whether any of these dependencies are actually
614                 -- *used* when compiling the module; they are listed if they are below
615                 -- it at all.  For example, suppose M imports A which imports X.  Then
616                 -- compiling M might not need to consult X.hi, but X is still listed
617                 -- in M's dependencies.
618
619         imp_dep_pkgs :: [PackageName],
620                 -- Packages needed by the module being compiled, whether
621                 -- directly, or via other modules in this package, or via
622                 -- modules imported from other packages.
623
624         imp_orphs :: [ModuleName]
625                 -- Orphan modules below us in the import tree
626       }
627
628 emptyImportAvails :: ImportAvails
629 emptyImportAvails = ImportAvails { imp_env      = emptyAvailEnv, 
630                                    imp_qual     = emptyModuleEnv, 
631                                    imp_mods     = emptyModuleEnv,
632                                    imp_dep_mods = emptyModuleEnv,
633                                    imp_dep_pkgs = [],
634                                    imp_orphs    = [] }
635
636 plusImportAvails ::  ImportAvails ->  ImportAvails ->  ImportAvails
637 plusImportAvails
638   (ImportAvails { imp_env = env1, imp_qual = unqual1, imp_mods = mods1,
639                   imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1, imp_orphs = orphs1 })
640   (ImportAvails { imp_env = env2, imp_qual = unqual2, imp_mods = mods2,
641                   imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2, imp_orphs = orphs2 })
642   = ImportAvails { imp_env      = env1 `plusAvailEnv` env2, 
643                    imp_qual     = plusModuleEnv_C plusAvailEnv unqual1 unqual2, 
644                    imp_mods     = mods1  `plusModuleEnv` mods2, 
645                    imp_dep_mods = plusModuleEnv_C plus_mod_dep dmods1 dmods2,   
646                    imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
647                    imp_orphs    = orphs1 `unionLists` orphs2 }
648   where
649     plus_mod_dep (m1, boot1) (m2, boot2) 
650         = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
651                 -- Check mod-names match
652           (m1, boot1 && boot2)  -- If either side can "see" a non-hi-boot interface, use that
653 \end{code}
654
655 %************************************************************************
656 %*                                                                      *
657         Avails, AvailEnv, etc
658 %*                                                                      *
659 v%************************************************************************
660
661 \begin{code}
662 plusAvail (Avail n1)       (Avail n2)       = Avail n1
663 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
664 -- Added SOF 4/97
665 #ifdef DEBUG
666 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
667 #endif
668
669 -------------------------
670 pruneAvails :: (Name -> Bool)   -- Keep if this is True
671             -> [AvailInfo]
672             -> [AvailInfo]
673 pruneAvails keep avails
674   = mapMaybe del avails
675   where
676     del :: AvailInfo -> Maybe AvailInfo -- Nothing => nothing left!
677     del (Avail n) | keep n    = Just (Avail n)
678                   | otherwise = Nothing
679     del (AvailTC n ns) | null ns'  = Nothing
680                        | otherwise = Just (AvailTC n ns')
681                        where
682                          ns' = filter keep ns
683 \end{code}
684
685 ---------------------------------------
686         AvailEnv and friends
687 ---------------------------------------
688
689 \begin{code}
690 type AvailEnv = NameEnv AvailInfo       -- Maps a Name to the AvailInfo that contains it
691
692 emptyAvailEnv :: AvailEnv
693 emptyAvailEnv = emptyNameEnv
694
695 unitAvailEnv :: AvailInfo -> AvailEnv
696 unitAvailEnv a = unitNameEnv (availName a) a
697
698 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
699 plusAvailEnv = plusNameEnv_C plusAvail
700
701 lookupAvailEnv_maybe :: AvailEnv -> Name -> Maybe AvailInfo
702 lookupAvailEnv_maybe = lookupNameEnv
703
704 lookupAvailEnv :: AvailEnv -> Name -> AvailInfo
705 lookupAvailEnv env n = case lookupNameEnv env n of
706                          Just avail -> avail
707                          Nothing    -> pprPanic "lookupAvailEnv" (ppr n)
708
709 availEnvElts = nameEnvElts
710
711 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
712 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
713
714 mkAvailEnv :: [AvailInfo] -> AvailEnv
715         -- 'avails' may have several items with the same availName
716         -- E.g  import Ix( Ix(..), index )
717         -- will give Ix(Ix,index,range) and Ix(index)
718         -- We want to combine these; addAvail does that
719 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
720 \end{code}
721
722 %************************************************************************
723 %*                                                                      *
724 \subsection{Where from}
725 %*                                                                      *
726 %************************************************************************
727
728 The @WhereFrom@ type controls where the renamer looks for an interface file
729
730 \begin{code}
731 data WhereFrom 
732   = ImportByUser IsBootInterface        -- Ordinary user import (perhaps {-# SOURCE #-})
733
734   | ImportForUsage IsBootInterface      -- Import when chasing usage info from an interaface file
735                                         --      Failure in this case is not an error
736
737   | ImportBySystem                      -- Non user import.
738
739 instance Outputable WhereFrom where
740   ppr (ImportByUser is_boot) | is_boot     = ptext SLIT("{- SOURCE -}")
741                              | otherwise   = empty
742   ppr (ImportForUsage is_boot) | is_boot   = ptext SLIT("{- USAGE SOURCE -}")
743                                | otherwise = ptext SLIT("{- USAGE -}")
744   ppr ImportBySystem                       = ptext SLIT("{- SYSTEM -}")
745 \end{code}
746
747
748 %************************************************************************
749 %*                                                                      *
750 \subsection[Inst-types]{@Inst@ types}
751 %*                                                                      *
752 v%************************************************************************
753
754 An @Inst@ is either a dictionary, an instance of an overloaded
755 literal, or an instance of an overloaded value.  We call the latter a
756 ``method'' even though it may not correspond to a class operation.
757 For example, we might have an instance of the @double@ function at
758 type Int, represented by
759
760         Method 34 doubleId [Int] origin
761
762 \begin{code}
763 data Inst
764   = Dict
765         Id
766         TcPredType
767         InstLoc
768
769   | Method
770         Id
771
772         TcId    -- The overloaded function
773                         -- This function will be a global, local, or ClassOpId;
774                         --   inside instance decls (only) it can also be an InstId!
775                         -- The id needn't be completely polymorphic.
776                         -- You'll probably find its name (for documentation purposes)
777                         --        inside the InstOrigin
778
779         [TcType]        -- The types to which its polymorphic tyvars
780                         --      should be instantiated.
781                         -- These types must saturate the Id's foralls.
782
783         TcThetaType     -- The (types of the) dictionaries to which the function
784                         -- must be applied to get the method
785
786         TcTauType       -- The tau-type of the method
787
788         InstLoc
789
790         -- INVARIANT 1: in (Method u f tys theta tau loc)
791         --      type of (f tys dicts(from theta)) = tau
792
793         -- INVARIANT 2: tau must not be of form (Pred -> Tau)
794         --   Reason: two methods are considerd equal if the 
795         --           base Id matches, and the instantiating types
796         --           match.  The TcThetaType should then match too.
797         --   This only bites in the call to tcInstClassOp in TcClassDcl.mkMethodBind
798
799   | LitInst
800         Id
801         HsOverLit       -- The literal from the occurrence site
802                         --      INVARIANT: never a rebindable-syntax literal
803                         --      Reason: tcSyntaxName does unification, and we
804                         --              don't want to deal with that during tcSimplify
805         TcType          -- The type at which the literal is used
806         InstLoc
807 \end{code}
808
809 @Insts@ are ordered by their class/type info, rather than by their
810 unique.  This allows the context-reduction mechanism to use standard finite
811 maps to do their stuff.
812
813 \begin{code}
814 instance Ord Inst where
815   compare = cmpInst
816
817 instance Eq Inst where
818   (==) i1 i2 = case i1 `cmpInst` i2 of
819                  EQ    -> True
820                  other -> False
821
822 cmpInst (Dict _ pred1 _)          (Dict _ pred2 _)          = pred1 `tcCmpPred` pred2
823 cmpInst (Dict _ _ _)              other                     = LT
824
825 cmpInst (Method _ _ _ _ _ _)      (Dict _ _ _)              = GT
826 cmpInst (Method _ id1 tys1 _ _ _) (Method _ id2 tys2 _ _ _) = (id1 `compare` id2) `thenCmp` (tys1 `tcCmpTypes` tys2)
827 cmpInst (Method _ _ _ _ _ _)      other                     = LT
828
829 cmpInst (LitInst _ _ _ _)         (Dict _ _ _)              = GT
830 cmpInst (LitInst _ _ _ _)         (Method _ _ _ _ _ _)      = GT
831 cmpInst (LitInst _ lit1 ty1 _)    (LitInst _ lit2 ty2 _)    = (lit1 `compare` lit2) `thenCmp` (ty1 `tcCmpType` ty2)
832 \end{code}
833
834
835 %************************************************************************
836 %*                                                                      *
837 \subsection[Inst-collections]{LIE: a collection of Insts}
838 %*                                                                      *
839 %************************************************************************
840
841 \begin{code}
842 type LIE = Bag Inst
843
844 isEmptyLIE        = isEmptyBag
845 emptyLIE          = emptyBag
846 unitLIE inst      = unitBag inst
847 mkLIE insts       = listToBag insts
848 plusLIE lie1 lie2 = lie1 `unionBags` lie2
849 consLIE inst lie  = inst `consBag` lie
850 plusLIEs lies     = unionManyBags lies
851 lieToList         = bagToList
852 listToLIE         = listToBag
853 \end{code}
854
855
856 %************************************************************************
857 %*                                                                      *
858 \subsection[Inst-origin]{The @InstOrigin@ type}
859 %*                                                                      *
860 %************************************************************************
861
862 The @InstOrigin@ type gives information about where a dictionary came from.
863 This is important for decent error message reporting because dictionaries
864 don't appear in the original source code.  Doubtless this type will evolve...
865
866 It appears in TcMonad because there are a couple of error-message-generation
867 functions that deal with it.
868
869 \begin{code}
870 data InstLoc = InstLoc InstOrigin SrcLoc ErrCtxt
871
872 instLocSrcLoc :: InstLoc -> SrcLoc
873 instLocSrcLoc (InstLoc _ src_loc _) = src_loc
874
875 data InstOrigin
876   = OccurrenceOf Name           -- Occurrence of an overloaded identifier
877
878   | IPOcc (IPName Name)         -- Occurrence of an implicit parameter
879   | IPBind (IPName Name)        -- Binding site of an implicit parameter
880
881   | RecordUpdOrigin
882
883   | DataDeclOrigin              -- Typechecking a data declaration
884
885   | InstanceDeclOrigin          -- Typechecking an instance decl
886
887   | LiteralOrigin HsOverLit     -- Occurrence of a literal
888
889   | PatOrigin RenamedPat
890
891   | ArithSeqOrigin RenamedArithSeqInfo -- [x..], [x..y] etc
892   | PArrSeqOrigin  RenamedArithSeqInfo -- [:x..y:] and [:x,y..z:]
893
894   | SignatureOrigin             -- A dict created from a type signature
895   | Rank2Origin                 -- A dict created when typechecking the argument
896                                 -- of a rank-2 typed function
897
898   | DoOrigin                    -- The monad for a do expression
899   | ProcOrigin                  -- A proc expression
900
901   | ClassDeclOrigin             -- Manufactured during a class decl
902
903   | InstanceSpecOrigin  Class   -- in a SPECIALIZE instance pragma
904                         Type
905
906         -- When specialising instances the instance info attached to
907         -- each class is not yet ready, so we record it inside the
908         -- origin information.  This is a bit of a hack, but it works
909         -- fine.  (Patrick is to blame [WDP].)
910
911   | ValSpecOrigin       Name    -- in a SPECIALIZE pragma for a value
912
913         -- Argument or result of a ccall
914         -- Dictionaries with this origin aren't actually mentioned in the
915         -- translated term, and so need not be bound.  Nor should they
916         -- be abstracted over.
917
918   | CCallOrigin         String                  -- CCall label
919                         (Maybe RenamedHsExpr)   -- Nothing if it's the result
920                                                 -- Just arg, for an argument
921
922   | LitLitOrigin        String  -- the litlit
923
924   | UnknownOrigin       -- Help! I give up...
925 \end{code}
926
927 \begin{code}
928 pprInstLoc :: InstLoc -> SDoc
929 pprInstLoc (InstLoc orig locn ctxt)
930   = hsep [text "arising from", pp_orig orig, text "at", ppr locn]
931   where
932     pp_orig (OccurrenceOf name)
933         = hsep [ptext SLIT("use of"), quotes (ppr name)]
934     pp_orig (IPOcc name)
935         = hsep [ptext SLIT("use of implicit parameter"), quotes (ppr name)]
936     pp_orig (IPBind name)
937         = hsep [ptext SLIT("binding for implicit parameter"), quotes (ppr name)]
938     pp_orig RecordUpdOrigin
939         = ptext SLIT("a record update")
940     pp_orig DataDeclOrigin
941         = ptext SLIT("the data type declaration")
942     pp_orig InstanceDeclOrigin
943         = ptext SLIT("the instance declaration")
944     pp_orig (LiteralOrigin lit)
945         = hsep [ptext SLIT("the literal"), quotes (ppr lit)]
946     pp_orig (PatOrigin pat)
947         = hsep [ptext SLIT("the pattern"), quotes (ppr pat)]
948     pp_orig (ArithSeqOrigin seq)
949         = hsep [ptext SLIT("the arithmetic sequence"), quotes (ppr seq)]
950     pp_orig (PArrSeqOrigin seq)
951         = hsep [ptext SLIT("the parallel array sequence"), quotes (ppr seq)]
952     pp_orig (SignatureOrigin)
953         =  ptext SLIT("a type signature")
954     pp_orig (Rank2Origin)
955         =  ptext SLIT("a function with an overloaded argument type")
956     pp_orig (DoOrigin)
957         =  ptext SLIT("a do statement")
958     pp_orig (ProcOrigin)
959         =  ptext SLIT("a proc expression")
960     pp_orig (ClassDeclOrigin)
961         =  ptext SLIT("a class declaration")
962     pp_orig (InstanceSpecOrigin clas ty)
963         = hsep [text "a SPECIALIZE instance pragma; class",
964                 quotes (ppr clas), text "type:", ppr ty]
965     pp_orig (ValSpecOrigin name)
966         = hsep [ptext SLIT("a SPECIALIZE user-pragma for"), quotes (ppr name)]
967     pp_orig (CCallOrigin clabel Nothing{-ccall result-})
968         = hsep [ptext SLIT("the result of the _ccall_ to"), quotes (text clabel)]
969     pp_orig (CCallOrigin clabel (Just arg_expr))
970         = hsep [ptext SLIT("an argument in the _ccall_ to"), quotes (text clabel) <> comma, 
971                 text "namely", quotes (ppr arg_expr)]
972     pp_orig (LitLitOrigin s)
973         = hsep [ptext SLIT("the ``literal-literal''"), quotes (text s)]
974     pp_orig (UnknownOrigin)
975         = ptext SLIT("...oops -- I don't know where the overloading came from!")
976 \end{code}