[project @ 2003-09-23 16:52:44 by sof]
[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, Maybe Bool),
599                 -- Domain is all directly-imported modules
600                 -- Maybe value answers the question "is the import restricted?"
601                 --   Nothing    => unrestricted import (e.g., "import Foo")
602                 --   Just True  => restricted import, at least one entity (e.g., "import Foo(x)")
603                 --   Just False => fully restricted import (e.g., "import Foo ()")
604                 --
605                 --  A distinction is made between the first and the third in order
606                 --  to more precisely emit warnings about unused imports.
607                 --
608                 -- We need the Module in the range because we can't get
609                 --      the keys of a ModuleEnv
610                 -- Used 
611                 --   (a) to help construct the usage information in 
612                 --       the interface file; if we import everything we
613                 --       need to recompile if the module version changes
614                 --   (b) to specify what child modules to initialise
615
616         imp_dep_mods :: ModuleEnv (ModuleName, IsBootInterface),
617                 -- Home-package modules needed by the module being compiled
618                 --
619                 -- It doesn't matter whether any of these dependencies are actually
620                 -- *used* when compiling the module; they are listed if they are below
621                 -- it at all.  For example, suppose M imports A which imports X.  Then
622                 -- compiling M might not need to consult X.hi, but X is still listed
623                 -- in M's dependencies.
624
625         imp_dep_pkgs :: [PackageName],
626                 -- Packages needed by the module being compiled, whether
627                 -- directly, or via other modules in this package, or via
628                 -- modules imported from other packages.
629
630         imp_orphs :: [ModuleName]
631                 -- Orphan modules below us in the import tree
632       }
633
634 emptyImportAvails :: ImportAvails
635 emptyImportAvails = ImportAvails { imp_env      = emptyAvailEnv, 
636                                    imp_qual     = emptyModuleEnv, 
637                                    imp_mods     = emptyModuleEnv,
638                                    imp_dep_mods = emptyModuleEnv,
639                                    imp_dep_pkgs = [],
640                                    imp_orphs    = [] }
641
642 plusImportAvails ::  ImportAvails ->  ImportAvails ->  ImportAvails
643 plusImportAvails
644   (ImportAvails { imp_env = env1, imp_qual = unqual1, imp_mods = mods1,
645                   imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1, imp_orphs = orphs1 })
646   (ImportAvails { imp_env = env2, imp_qual = unqual2, imp_mods = mods2,
647                   imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2, imp_orphs = orphs2 })
648   = ImportAvails { imp_env      = env1 `plusAvailEnv` env2, 
649                    imp_qual     = plusModuleEnv_C plusAvailEnv unqual1 unqual2, 
650                    imp_mods     = mods1  `plusModuleEnv` mods2, 
651                    imp_dep_mods = plusModuleEnv_C plus_mod_dep dmods1 dmods2,   
652                    imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
653                    imp_orphs    = orphs1 `unionLists` orphs2 }
654   where
655     plus_mod_dep (m1, boot1) (m2, boot2) 
656         = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
657                 -- Check mod-names match
658           (m1, boot1 && boot2)  -- If either side can "see" a non-hi-boot interface, use that
659 \end{code}
660
661 %************************************************************************
662 %*                                                                      *
663         Avails, AvailEnv, etc
664 %*                                                                      *
665 v%************************************************************************
666
667 \begin{code}
668 plusAvail (Avail n1)       (Avail n2)       = Avail n1
669 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
670 -- Added SOF 4/97
671 #ifdef DEBUG
672 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
673 #endif
674
675 -------------------------
676 pruneAvails :: (Name -> Bool)   -- Keep if this is True
677             -> [AvailInfo]
678             -> [AvailInfo]
679 pruneAvails keep avails
680   = mapMaybe del avails
681   where
682     del :: AvailInfo -> Maybe AvailInfo -- Nothing => nothing left!
683     del (Avail n) | keep n    = Just (Avail n)
684                   | otherwise = Nothing
685     del (AvailTC n ns) | null ns'  = Nothing
686                        | otherwise = Just (AvailTC n ns')
687                        where
688                          ns' = filter keep ns
689 \end{code}
690
691 ---------------------------------------
692         AvailEnv and friends
693 ---------------------------------------
694
695 \begin{code}
696 type AvailEnv = NameEnv AvailInfo       -- Maps a Name to the AvailInfo that contains it
697
698 emptyAvailEnv :: AvailEnv
699 emptyAvailEnv = emptyNameEnv
700
701 unitAvailEnv :: AvailInfo -> AvailEnv
702 unitAvailEnv a = unitNameEnv (availName a) a
703
704 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
705 plusAvailEnv = plusNameEnv_C plusAvail
706
707 lookupAvailEnv_maybe :: AvailEnv -> Name -> Maybe AvailInfo
708 lookupAvailEnv_maybe = lookupNameEnv
709
710 lookupAvailEnv :: AvailEnv -> Name -> AvailInfo
711 lookupAvailEnv env n = case lookupNameEnv env n of
712                          Just avail -> avail
713                          Nothing    -> pprPanic "lookupAvailEnv" (ppr n)
714
715 availEnvElts = nameEnvElts
716
717 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
718 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
719
720 mkAvailEnv :: [AvailInfo] -> AvailEnv
721         -- 'avails' may have several items with the same availName
722         -- E.g  import Ix( Ix(..), index )
723         -- will give Ix(Ix,index,range) and Ix(index)
724         -- We want to combine these; addAvail does that
725 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
726 \end{code}
727
728 %************************************************************************
729 %*                                                                      *
730 \subsection{Where from}
731 %*                                                                      *
732 %************************************************************************
733
734 The @WhereFrom@ type controls where the renamer looks for an interface file
735
736 \begin{code}
737 data WhereFrom 
738   = ImportByUser IsBootInterface        -- Ordinary user import (perhaps {-# SOURCE #-})
739
740   | ImportForUsage IsBootInterface      -- Import when chasing usage info from an interaface file
741                                         --      Failure in this case is not an error
742
743   | ImportBySystem                      -- Non user import.
744
745 instance Outputable WhereFrom where
746   ppr (ImportByUser is_boot) | is_boot     = ptext SLIT("{- SOURCE -}")
747                              | otherwise   = empty
748   ppr (ImportForUsage is_boot) | is_boot   = ptext SLIT("{- USAGE SOURCE -}")
749                                | otherwise = ptext SLIT("{- USAGE -}")
750   ppr ImportBySystem                       = ptext SLIT("{- SYSTEM -}")
751 \end{code}
752
753
754 %************************************************************************
755 %*                                                                      *
756 \subsection[Inst-types]{@Inst@ types}
757 %*                                                                      *
758 v%************************************************************************
759
760 An @Inst@ is either a dictionary, an instance of an overloaded
761 literal, or an instance of an overloaded value.  We call the latter a
762 ``method'' even though it may not correspond to a class operation.
763 For example, we might have an instance of the @double@ function at
764 type Int, represented by
765
766         Method 34 doubleId [Int] origin
767
768 \begin{code}
769 data Inst
770   = Dict
771         Id
772         TcPredType
773         InstLoc
774
775   | Method
776         Id
777
778         TcId    -- The overloaded function
779                         -- This function will be a global, local, or ClassOpId;
780                         --   inside instance decls (only) it can also be an InstId!
781                         -- The id needn't be completely polymorphic.
782                         -- You'll probably find its name (for documentation purposes)
783                         --        inside the InstOrigin
784
785         [TcType]        -- The types to which its polymorphic tyvars
786                         --      should be instantiated.
787                         -- These types must saturate the Id's foralls.
788
789         TcThetaType     -- The (types of the) dictionaries to which the function
790                         -- must be applied to get the method
791
792         TcTauType       -- The tau-type of the method
793
794         InstLoc
795
796         -- INVARIANT 1: in (Method u f tys theta tau loc)
797         --      type of (f tys dicts(from theta)) = tau
798
799         -- INVARIANT 2: tau must not be of form (Pred -> Tau)
800         --   Reason: two methods are considerd equal if the 
801         --           base Id matches, and the instantiating types
802         --           match.  The TcThetaType should then match too.
803         --   This only bites in the call to tcInstClassOp in TcClassDcl.mkMethodBind
804
805   | LitInst
806         Id
807         HsOverLit       -- The literal from the occurrence site
808                         --      INVARIANT: never a rebindable-syntax literal
809                         --      Reason: tcSyntaxName does unification, and we
810                         --              don't want to deal with that during tcSimplify
811         TcType          -- The type at which the literal is used
812         InstLoc
813 \end{code}
814
815 @Insts@ are ordered by their class/type info, rather than by their
816 unique.  This allows the context-reduction mechanism to use standard finite
817 maps to do their stuff.
818
819 \begin{code}
820 instance Ord Inst where
821   compare = cmpInst
822
823 instance Eq Inst where
824   (==) i1 i2 = case i1 `cmpInst` i2 of
825                  EQ    -> True
826                  other -> False
827
828 cmpInst (Dict _ pred1 _)          (Dict _ pred2 _)          = pred1 `tcCmpPred` pred2
829 cmpInst (Dict _ _ _)              other                     = LT
830
831 cmpInst (Method _ _ _ _ _ _)      (Dict _ _ _)              = GT
832 cmpInst (Method _ id1 tys1 _ _ _) (Method _ id2 tys2 _ _ _) = (id1 `compare` id2) `thenCmp` (tys1 `tcCmpTypes` tys2)
833 cmpInst (Method _ _ _ _ _ _)      other                     = LT
834
835 cmpInst (LitInst _ _ _ _)         (Dict _ _ _)              = GT
836 cmpInst (LitInst _ _ _ _)         (Method _ _ _ _ _ _)      = GT
837 cmpInst (LitInst _ lit1 ty1 _)    (LitInst _ lit2 ty2 _)    = (lit1 `compare` lit2) `thenCmp` (ty1 `tcCmpType` ty2)
838 \end{code}
839
840
841 %************************************************************************
842 %*                                                                      *
843 \subsection[Inst-collections]{LIE: a collection of Insts}
844 %*                                                                      *
845 %************************************************************************
846
847 \begin{code}
848 type LIE = Bag Inst
849
850 isEmptyLIE        = isEmptyBag
851 emptyLIE          = emptyBag
852 unitLIE inst      = unitBag inst
853 mkLIE insts       = listToBag insts
854 plusLIE lie1 lie2 = lie1 `unionBags` lie2
855 consLIE inst lie  = inst `consBag` lie
856 plusLIEs lies     = unionManyBags lies
857 lieToList         = bagToList
858 listToLIE         = listToBag
859 \end{code}
860
861
862 %************************************************************************
863 %*                                                                      *
864 \subsection[Inst-origin]{The @InstOrigin@ type}
865 %*                                                                      *
866 %************************************************************************
867
868 The @InstOrigin@ type gives information about where a dictionary came from.
869 This is important for decent error message reporting because dictionaries
870 don't appear in the original source code.  Doubtless this type will evolve...
871
872 It appears in TcMonad because there are a couple of error-message-generation
873 functions that deal with it.
874
875 \begin{code}
876 data InstLoc = InstLoc InstOrigin SrcLoc ErrCtxt
877
878 instLocSrcLoc :: InstLoc -> SrcLoc
879 instLocSrcLoc (InstLoc _ src_loc _) = src_loc
880
881 data InstOrigin
882   = OccurrenceOf Name           -- Occurrence of an overloaded identifier
883
884   | IPOcc (IPName Name)         -- Occurrence of an implicit parameter
885   | IPBind (IPName Name)        -- Binding site of an implicit parameter
886
887   | RecordUpdOrigin
888
889   | DataDeclOrigin              -- Typechecking a data declaration
890
891   | InstanceDeclOrigin          -- Typechecking an instance decl
892
893   | LiteralOrigin HsOverLit     -- Occurrence of a literal
894
895   | PatOrigin RenamedPat
896
897   | ArithSeqOrigin RenamedArithSeqInfo -- [x..], [x..y] etc
898   | PArrSeqOrigin  RenamedArithSeqInfo -- [:x..y:] and [:x,y..z:]
899
900   | SignatureOrigin             -- A dict created from a type signature
901   | Rank2Origin                 -- A dict created when typechecking the argument
902                                 -- of a rank-2 typed function
903
904   | DoOrigin                    -- The monad for a do expression
905   | ProcOrigin                  -- A proc expression
906
907   | ClassDeclOrigin             -- Manufactured during a class decl
908
909   | InstanceSpecOrigin  Class   -- in a SPECIALIZE instance pragma
910                         Type
911
912         -- When specialising instances the instance info attached to
913         -- each class is not yet ready, so we record it inside the
914         -- origin information.  This is a bit of a hack, but it works
915         -- fine.  (Patrick is to blame [WDP].)
916
917   | ValSpecOrigin       Name    -- in a SPECIALIZE pragma for a value
918
919         -- Argument or result of a ccall
920         -- Dictionaries with this origin aren't actually mentioned in the
921         -- translated term, and so need not be bound.  Nor should they
922         -- be abstracted over.
923
924   | CCallOrigin         String                  -- CCall label
925                         (Maybe RenamedHsExpr)   -- Nothing if it's the result
926                                                 -- Just arg, for an argument
927
928   | UnknownOrigin       -- Help! I give up...
929 \end{code}
930
931 \begin{code}
932 pprInstLoc :: InstLoc -> SDoc
933 pprInstLoc (InstLoc orig locn ctxt)
934   = hsep [text "arising from", pp_orig orig, text "at", ppr locn]
935   where
936     pp_orig (OccurrenceOf name)
937         = hsep [ptext SLIT("use of"), quotes (ppr name)]
938     pp_orig (IPOcc name)
939         = hsep [ptext SLIT("use of implicit parameter"), quotes (ppr name)]
940     pp_orig (IPBind name)
941         = hsep [ptext SLIT("binding for implicit parameter"), quotes (ppr name)]
942     pp_orig RecordUpdOrigin
943         = ptext SLIT("a record update")
944     pp_orig DataDeclOrigin
945         = ptext SLIT("the data type declaration")
946     pp_orig InstanceDeclOrigin
947         = ptext SLIT("the instance declaration")
948     pp_orig (LiteralOrigin lit)
949         = hsep [ptext SLIT("the literal"), quotes (ppr lit)]
950     pp_orig (PatOrigin pat)
951         = hsep [ptext SLIT("the pattern"), quotes (ppr pat)]
952     pp_orig (ArithSeqOrigin seq)
953         = hsep [ptext SLIT("the arithmetic sequence"), quotes (ppr seq)]
954     pp_orig (PArrSeqOrigin seq)
955         = hsep [ptext SLIT("the parallel array sequence"), quotes (ppr seq)]
956     pp_orig (SignatureOrigin)
957         =  ptext SLIT("a type signature")
958     pp_orig (Rank2Origin)
959         =  ptext SLIT("a function with an overloaded argument type")
960     pp_orig (DoOrigin)
961         =  ptext SLIT("a do statement")
962     pp_orig (ProcOrigin)
963         =  ptext SLIT("a proc expression")
964     pp_orig (ClassDeclOrigin)
965         =  ptext SLIT("a class declaration")
966     pp_orig (InstanceSpecOrigin clas ty)
967         = hsep [text "a SPECIALIZE instance pragma; class",
968                 quotes (ppr clas), text "type:", ppr ty]
969     pp_orig (ValSpecOrigin name)
970         = hsep [ptext SLIT("a SPECIALIZE user-pragma for"), quotes (ppr name)]
971     pp_orig (CCallOrigin clabel Nothing{-ccall result-})
972         = hsep [ptext SLIT("the result of the _ccall_ to"), quotes (text clabel)]
973     pp_orig (CCallOrigin clabel (Just arg_expr))
974         = hsep [ptext SLIT("an argument in the _ccall_ to"), quotes (text clabel) <> comma, 
975                 text "namely", quotes (ppr arg_expr)]
976     pp_orig (UnknownOrigin)
977         = ptext SLIT("...oops -- I don't know where the overloading came from!")
978 \end{code}