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