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