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