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