[project @ 2002-05-03 11:10:47 by simonmar]
[ghc-hetmet.git] / ghc / compiler / rename / Rename.lhs
1 %
2 % (c) The GRASP Project, Glasgow University, 1992-1998
3 %
4 \section[Rename]{Renaming and dependency analysis passes}
5
6 \begin{code}
7 module Rename 
8         ( renameModule
9         , RnResult(..)
10         , renameStmt
11         , renameRdrName
12         , renameExtCore
13         , mkGlobalContext
14         , closeIfaceDecls
15         , checkOldIface
16         , slurpIface
17         ) where
18
19 #include "HsVersions.h"
20
21 import HsSyn
22 import RdrHsSyn         ( RdrNameHsModule, RdrNameHsDecl, RdrNameDeprecation, 
23                           RdrNameTyClDecl, RdrNameRuleDecl, RdrNameInstDecl, RdrNameImportDecl,
24                           RdrNameStmt
25                         )
26 import RnHsSyn          ( RenamedHsDecl, RenamedTyClDecl, RenamedRuleDecl, RenamedInstDecl,
27                           RenamedStmt,
28                           instDeclFVs, tyClDeclFVs, ruleDeclFVs
29                         )
30
31 import CmdLineOpts      ( DynFlags, DynFlag(..), opt_InPackage )
32 import RnMonad
33 import RnExpr           ( rnStmt )
34 import RnNames          ( getGlobalNames, exportsFromAvail )
35 import RnSource         ( rnSourceDecls, rnTyClDecl, rnIfaceRuleDecl, rnInstDecl )
36 import RnIfaces         ( slurpImpDecls, mkImportInfo, recordLocalSlurps,
37                           closeDecls,
38                           RecompileRequired, outOfDate, recompileRequired
39                         )
40 import RnHiFiles        ( readIface, loadInterface,
41                           loadExports, loadFixDecls, loadDeprecs,
42                         )
43 import RnEnv            ( availsToNameSet,
44                           unitAvailEnv, availEnvElts, availNames,
45                           plusAvailEnv, groupAvails, warnUnusedImports, 
46                           warnUnusedLocalBinds, warnUnusedModules, 
47                           lookupSrcName, getImplicitStmtFVs, 
48                           getImplicitModuleFVs, newGlobalName, unQualInScope,
49                           ubiquitousNames, lookupOccRn, checkMain,
50                           plusGlobalRdrEnv, mkGlobalRdrEnv
51                         )
52 import Module           ( Module, ModuleName, WhereFrom(..),
53                           moduleNameUserString, moduleName,
54                           moduleEnvElts
55                         )
56 import Name             ( Name, nameModule, isExternalName )
57 import NameEnv
58 import NameSet
59 import RdrName          ( foldRdrEnv, isQual, emptyRdrEnv )
60 import PrelNames        ( iNTERACTIVE, pRELUDE_Name )
61 import ErrUtils         ( dumpIfSet, dumpIfSet_dyn, showPass, 
62                           printErrorsAndWarnings, errorsFound )
63 import Bag              ( bagToList )
64 import FiniteMap        ( FiniteMap, fmToList, emptyFM, lookupFM, 
65                           addToFM_C, elemFM, addToFM
66                         )
67 import Maybes           ( maybeToBool, catMaybes )
68 import Outputable
69 import IO               ( openFile, IOMode(..) )
70 import HscTypes         -- lots of it
71 import List             ( partition, nub )
72 \end{code}
73
74
75 %*********************************************************
76 %*                                                       *
77 \subsection{The main wrappers}
78 %*                                                       *
79 %*********************************************************
80
81 \begin{code}
82 renameModule :: DynFlags -> GhciMode
83              -> HomeIfaceTable -> HomeSymbolTable
84              -> PersistentCompilerState 
85              -> Module -> RdrNameHsModule 
86              -> IO (PersistentCompilerState, PrintUnqualified,
87                     Maybe (IsExported, ModIface, RnResult))
88         -- Nothing => some error occurred in the renamer
89
90 renameModule dflags ghci_mode hit hst pcs this_module rdr_module
91   = renameSource dflags hit hst pcs this_module $
92     rename ghci_mode this_module rdr_module
93 \end{code}
94
95 \begin{code}
96 renameStmt :: DynFlags
97            -> HomeIfaceTable -> HomeSymbolTable
98            -> PersistentCompilerState 
99            -> InteractiveContext
100            -> RdrNameStmt               -- parsed stmt
101            -> IO ( PersistentCompilerState, 
102                    PrintUnqualified,
103                    Maybe ([Name], (RenamedStmt, [RenamedHsDecl]))
104                  )
105
106 renameStmt dflags hit hst pcs ic stmt
107   = renameSource dflags hit hst pcs iNTERACTIVE $
108
109         -- load the context module
110     let InteractiveContext{ ic_rn_gbl_env   = rdr_env,
111                             ic_print_unqual = print_unqual,
112                             ic_rn_local_env = local_rdr_env,
113                             ic_type_env     = type_env } = ic
114     in
115
116     extendTypeEnvRn type_env  $ 
117
118         -- Rename the stmt
119     initRnMS rdr_env emptyAvailEnv local_rdr_env emptyLocalFixityEnv CmdLineMode (
120         rnStmt stmt     $ \ stmt' ->
121         returnRn (([], stmt'), emptyFVs)
122     )                                   `thenRn` \ ((binders, stmt), fvs) -> 
123
124         -- Bale out if we fail
125     checkErrsRn                         `thenRn` \ no_errs_so_far ->
126     if not no_errs_so_far then
127         doDump dflags [] stmt [] `thenRn_` returnRn (print_unqual, Nothing)
128     else
129
130         -- Add implicit free vars, and close decls
131     getImplicitStmtFVs                          `thenRn` \ implicit_fvs ->
132     slurpImpDecls (fvs `plusFV` implicit_fvs)   `thenRn` \ decls ->
133         -- NB: an earlier version deleted (rdrEnvElts local_env) from
134         --     the fvs.  But (a) that isn't necessary, because previously
135         --     bound things in the local_env will be in the TypeEnv, and 
136         --     the renamer doesn't re-slurp such things, and 
137         -- (b) it's WRONG to delete them. Consider in GHCi:
138         --        Mod> let x = e :: T
139         --        Mod> let y = x + 3
140         --     We need to pass 'x' among the fvs to slurpImpDecls, so that
141         --     the latter can see that T is a gate, and hence import the Num T 
142         --     instance decl.  (See the InTypEnv case in RnIfaces.slurpSourceRefs.)
143
144     doDump dflags binders stmt decls    `thenRn_`
145     returnRn (print_unqual, Just (binders, (stmt, decls)))
146
147   where
148      doDump :: DynFlags -> [Name] -> RenamedStmt -> [RenamedHsDecl]
149          -> RnMG (Either IOError ())
150      doDump dflags bndrs stmt decls
151         = ioToRnM (dumpIfSet_dyn dflags Opt_D_dump_rn "Renamer:" 
152                         (vcat [text "Binders:" <+> ppr bndrs,
153                                ppr stmt, text "",
154                                vcat (map ppr decls)]))
155
156
157 renameRdrName
158            :: DynFlags
159            -> HomeIfaceTable -> HomeSymbolTable
160            -> PersistentCompilerState 
161            -> InteractiveContext
162            -> [RdrName]                 -- name to rename
163            -> IO ( PersistentCompilerState, 
164                    PrintUnqualified,
165                    Maybe ([Name], [RenamedHsDecl])
166                  )
167
168 renameRdrName dflags hit hst pcs ic rdr_names = 
169     renameSource dflags hit hst pcs iNTERACTIVE $
170
171         -- load the context module
172     let InteractiveContext{ ic_rn_gbl_env   = rdr_env,
173                             ic_print_unqual = print_unqual,
174                             ic_rn_local_env = local_rdr_env,
175                             ic_type_env     = type_env } = ic
176     in
177
178     extendTypeEnvRn type_env  $ 
179
180     -- rename the rdr_name
181     initRnMS rdr_env emptyAvailEnv local_rdr_env emptyLocalFixityEnv CmdLineMode
182         (mapRn (tryRn.lookupOccRn) rdr_names)   `thenRn` \ maybe_names ->
183     let 
184         ok_names = [ a | Right a <- maybe_names ]
185     in
186     if null ok_names
187         then let errs = head [ e | Left e <- maybe_names ]
188              in setErrsRn errs            `thenRn_`
189                 doDump dflags ok_names [] `thenRn_` 
190                 returnRn (print_unqual, Nothing)
191         else 
192
193     slurpImpDecls (mkNameSet ok_names)          `thenRn` \ decls ->
194
195     doDump dflags ok_names decls                `thenRn_`
196     returnRn (print_unqual, Just (ok_names, decls))
197  where
198      doDump :: DynFlags -> [Name] -> [RenamedHsDecl] -> RnMG (Either IOError ())
199      doDump dflags names decls
200         = ioToRnM (dumpIfSet_dyn dflags Opt_D_dump_rn "Renamer:" 
201                         (vcat [ppr names, text "",
202                                vcat (map ppr decls)]))
203 \end{code}
204
205 \begin{code}
206 renameExtCore :: DynFlags
207               -> HomeIfaceTable -> HomeSymbolTable
208               -> PersistentCompilerState 
209               -> Module
210               -> RdrNameHsModule 
211               -> IO (PersistentCompilerState, PrintUnqualified,
212                      Maybe (IsExported, ModIface, [RenamedHsDecl]))
213
214         -- Nothing => some error occurred in the renamer
215 renameExtCore dflags hit hst pcs this_module 
216               rdr_module@(HsModule _ _ _ _ local_decls _ loc)
217         -- Rename the (Core) module
218   = renameSource dflags hit hst pcs this_module $
219     pushSrcLocRn loc $  
220
221         -- Rename the source
222     initIfaceRnMS this_module (rnExtCoreDecls local_decls)      `thenRn` \ (rn_local_decls, binders, fvs) ->
223     recordLocalSlurps binders                                   `thenRn_`
224     closeDecls rn_local_decls fvs                               `thenRn` \ final_decls ->                 
225
226         -- Bail out if we fail
227     checkErrsRn                         `thenRn` \ no_errs_so_far ->
228     if not no_errs_so_far then
229         returnRn (print_unqualified, Nothing)
230     else
231     rnDump final_decls []               `thenRn_` 
232     let
233         mod_iface = ModIface {  mi_module   = this_module,
234                                 mi_package  = opt_InPackage,
235                                 mi_version  = initialVersionInfo,
236                                 mi_usages   = [],
237                                 mi_boot     = False,
238                                 mi_orphan   = panic "is_orphan",
239                                  -- ToDo: export the data types also.
240                                 mi_exports  = [(moduleName this_module,
241                                                 map Avail (nameSetToList binders))],
242                                 mi_globals  = Nothing,
243                                 mi_fixities = mkNameEnv [],
244                                 mi_deprecs  = NoDeprecs,
245                                 mi_decls    = panic "mi_decls"
246                     }
247
248         is_exported _ = True
249      in
250      returnRn (print_unqualified, Just (is_exported, mod_iface, final_decls))
251
252   where
253     print_unqualified = const False        -- print everything qualified.
254
255
256 rnExtCoreDecls :: [RdrNameHsDecl] 
257                -> RnMS ([RenamedHsDecl],
258                         NameSet,                -- Binders
259                         FreeVars)               -- Free variables
260
261 rnExtCoreDecls decls
262         -- Renaming external-core decls is rather like renaming an interface file
263         -- All the decls are TyClDecls, and all the names are original names
264   = go [] emptyNameSet emptyNameSet decls
265   where
266     go rn_decls bndrs fvs [] = returnRn (rn_decls, bndrs, fvs)
267
268     go rn_decls bndrs fvs (TyClD decl : decls)
269         = rnTyClDecl decl               `thenRn` \ rn_decl ->
270           go (TyClD rn_decl : rn_decls)
271              (addListToNameSet bndrs (map fst (tyClDeclSysNames rn_decl ++ tyClDeclNames rn_decl)))
272              (fvs `plusFV` tyClDeclFVs rn_decl)
273              decls
274
275     go rn_decls bndrs fvs (decl : decls)
276         = addErrRn (text "Unexpected decl in ExtCore file" $$ ppr decl) `thenRn_`
277           go rn_decls bndrs fvs decls
278 \end{code}
279
280
281 %*********************************************************
282 %*                                                       *
283 \subsection{Make up an interactive context}
284 %*                                                       *
285 %*********************************************************
286
287 \begin{code}
288 mkGlobalContext
289         :: DynFlags -> HomeIfaceTable -> HomeSymbolTable
290         -> PersistentCompilerState
291         -> [Module] -> [Module]
292         -> IO (PersistentCompilerState, PrintUnqualified, Maybe GlobalRdrEnv)
293 mkGlobalContext dflags hit hst pcs toplevs exports
294   = renameSource dflags hit hst pcs iNTERACTIVE $
295
296     mapRn getTopLevScope   toplevs      `thenRn` \ toplev_envs ->
297     mapRn getModuleExports exports      `thenRn` \ export_envs ->
298     let full_env = foldr plusGlobalRdrEnv emptyRdrEnv
299                         (toplev_envs ++ export_envs)
300         print_unqual = unQualInScope full_env
301     in 
302     checkErrsRn                         `thenRn` \ no_errs_so_far ->
303     if not no_errs_so_far then
304         returnRn (print_unqual, Nothing)
305     else
306         returnRn (print_unqual, Just full_env)
307
308 contextDoc = text "context for compiling statements"
309
310 getTopLevScope :: Module -> RnM d GlobalRdrEnv
311 getTopLevScope mod = 
312     loadInterface contextDoc (moduleName mod) ImportByUser `thenRn` \ iface ->
313     case mi_globals iface of
314         Nothing  -> panic "getTopLevScope"
315         Just env -> returnRn env
316
317 getModuleExports :: Module -> RnM d GlobalRdrEnv
318 getModuleExports mod = 
319     loadInterface contextDoc (moduleName mod) ImportByUser `thenRn` \ iface ->
320     returnRn (foldl add emptyRdrEnv (mi_exports iface))
321   where
322     prov_fn n = NonLocalDef ImplicitImport
323     add env (mod,avails) = 
324         plusGlobalRdrEnv env (mkGlobalRdrEnv mod True prov_fn avails NoDeprecs)
325 \end{code}
326
327 %*********************************************************
328 %*                                                       *
329 \subsection{Slurp in a whole module eagerly}
330 %*                                                       *
331 %*********************************************************
332
333 \begin{code}
334 slurpIface
335         :: DynFlags -> HomeIfaceTable -> HomeSymbolTable
336         -> PersistentCompilerState -> Module
337         -> IO (PersistentCompilerState, PrintUnqualified, 
338                Maybe ([Name], [RenamedHsDecl]))
339 slurpIface dflags hit hst pcs mod = 
340   renameSource dflags hit hst pcs iNTERACTIVE $
341
342     let mod_name = moduleName mod
343     in
344     loadInterface contextDoc mod_name ImportByUser `thenRn` \ iface ->
345     let fvs = availsToNameSet [ avail | (mn,avails) <- mi_exports iface, 
346                                         avail <- avails ]
347     in
348     slurpImpDecls fvs   `thenRn` \ rn_imp_decls ->
349     returnRn (alwaysQualify, Just (nameSetToList fvs, rn_imp_decls))
350 \end{code}
351
352 %*********************************************************
353 %*                                                       *
354 \subsection{The main function: rename}
355 %*                                                       *
356 %*********************************************************
357
358 \begin{code}
359 renameSource :: DynFlags
360              -> HomeIfaceTable -> HomeSymbolTable
361              -> PersistentCompilerState 
362              -> Module 
363              -> RnMG (PrintUnqualified, Maybe r)
364              -> IO (PersistentCompilerState, PrintUnqualified, Maybe r)
365         -- Nothing => some error occurred in the renamer
366
367 renameSource dflags hit hst old_pcs this_module thing_inside
368   = do  { showPass dflags "Renamer"
369
370                 -- Initialise the renamer monad
371         ; (new_pcs, msgs, (print_unqual, maybe_rn_stuff)) 
372                 <- initRn dflags hit hst old_pcs this_module thing_inside
373
374                 -- Print errors from renaming
375         ;  printErrorsAndWarnings print_unqual msgs ;
376
377                 -- Return results.  No harm in updating the PCS
378         ; if errorsFound msgs then
379             return (new_pcs, print_unqual, Nothing)
380           else      
381             return (new_pcs, print_unqual, maybe_rn_stuff)
382     }
383 \end{code}
384
385 \begin{code}
386 data RnResult   -- A RenamedModule ia passed from renamer to typechecker
387   = RnResult { rr_mod      :: Module,     -- Same as in the ModIface, 
388                rr_fixities :: FixityEnv,  -- but convenient to have it here
389
390                rr_main :: Maybe Name,     -- Just main, for module Main, 
391                                           -- Nothing for other modules
392
393                rr_decls :: [RenamedHsDecl]      
394                         -- The other declarations of the module
395                         -- Fixity and deprecations have already been slurped out
396     }                   -- and are now in the ModIface for the module
397
398 rename :: GhciMode -> Module -> RdrNameHsModule 
399        -> RnMG (PrintUnqualified, Maybe (IsExported, ModIface, RnResult))
400 rename ghci_mode this_module 
401        contents@(HsModule _ _ exports imports local_decls mod_deprec loc)
402   = pushSrcLocRn loc            $
403
404         -- FIND THE GLOBAL NAME ENVIRONMENT
405     getGlobalNames this_module contents         `thenRn` \ (gbl_env, local_gbl_env, 
406                                                             (mod_avail_env, global_avail_env)) ->
407     let
408         print_unqualified = unQualInScope gbl_env
409
410         full_avail_env :: NameEnv AvailInfo
411                 -- The domain of global_avail_env is just the 'major' things;
412                 -- variables, type constructors, classes.  
413                 --      E.g. Functor |-> Functor( Functor, fmap )
414                 -- The domain of full_avail_env is everything in scope
415                 --      E.g. Functor |-> Functor( Functor, fmap )
416                 --           fmap    |-> Functor( Functor, fmap )
417                 -- 
418                 -- This filled-out avail_env is needed to generate
419                 -- exports (mkExportAvails), and for generating minimal
420                 -- exports (reportUnusedNames)
421         full_avail_env = mkNameEnv [ (name,avail) 
422                                    | avail <- availEnvElts global_avail_env,
423                                      name  <- availNames avail]
424     in
425         -- Exit if we've found any errors
426     checkErrsRn                         `thenRn` \ no_errs_so_far ->
427     if not no_errs_so_far then
428         -- Found errors already, so exit now
429         rnDump [] []            `thenRn_`
430         returnRn (print_unqualified, Nothing)
431     else
432         
433         -- PROCESS EXPORT LIST 
434     exportsFromAvail mod_name exports mod_avail_env 
435                      full_avail_env gbl_env             `thenRn` \ export_avails ->
436         
437     traceRn (text "Local top-level environment" $$ 
438              nest 4 (pprGlobalRdrEnv local_gbl_env))    `thenRn_`
439
440         -- DEAL WITH DEPRECATIONS
441     rnDeprecs local_gbl_env mod_deprec 
442               [d | DeprecD d <- local_decls]            `thenRn` \ my_deprecs ->
443
444         -- DEAL WITH LOCAL FIXITIES
445     fixitiesFromLocalDecls local_gbl_env local_decls    `thenRn` \ local_fixity_env ->
446
447         -- RENAME THE SOURCE
448     rnSourceDecls gbl_env global_avail_env 
449                   local_fixity_env SourceMode local_decls `thenRn` \ (rn_local_decls, source_fvs) ->
450
451         -- GET ANY IMPLICIT FREE VARIALBES
452     getImplicitModuleFVs rn_local_decls   `thenRn` \ implicit_fvs ->
453     checkMain ghci_mode mod_name gbl_env  `thenRn` \ (maybe_main_name, main_fvs, implicit_main_fvs) ->
454     let
455         export_fvs = availsToNameSet export_avails
456         used_fvs   = source_fvs `plusFV` export_fvs `plusFV` main_fvs
457                 -- The export_fvs make the exported names look just as if they
458                 -- occurred in the source program.  For the reasoning, see the
459                 -- comments with RnIfaces.mkImportInfo
460                 -- It also helps reportUnusedNames, which of course must not complain
461                 -- that 'f' isn't mentioned if it is mentioned in the export list
462
463         needed_fvs = implicit_fvs `plusFV` implicit_main_fvs `plusFV` used_fvs
464                 -- It's important to do the "plus" this way round, so that
465                 -- when compiling the prelude, locally-defined (), Bool, etc
466                 -- override the implicit ones. 
467
468     in
469     traceRn (text "Needed FVs:" <+> fsep (map ppr (nameSetToList needed_fvs)))  `thenRn_`
470
471         -- EXIT IF ERRORS FOUND
472         -- We exit here if there are any errors in the source, *before*
473         -- we attempt to slurp the decls from the interfaces, otherwise
474         -- the slurped decls may get lost when we return up the stack
475         -- to hscMain/hscExpr.
476     checkErrsRn                                 `thenRn` \ no_errs_so_far ->
477     if not no_errs_so_far then
478         -- Found errors already, so exit now
479         rnDump [] rn_local_decls                `thenRn_` 
480         returnRn (print_unqualified, Nothing)
481     else
482
483         -- SLURP IN ALL THE NEEDED DECLARATIONS
484     slurpImpDecls needed_fvs                    `thenRn` \ rn_imp_decls ->
485     rnDump rn_imp_decls rn_local_decls          `thenRn_` 
486
487         -- GENERATE THE VERSION/USAGE INFO
488     mkImportInfo mod_name imports               `thenRn` \ my_usages ->
489
490         -- BUILD THE MODULE INTERFACE
491     let
492         -- We record fixities even for things that aren't exported,
493         -- so that we can change into the context of this moodule easily
494         fixities = mkNameEnv [ (name, fixity)
495                              | FixitySig name fixity loc <- nameEnvElts local_fixity_env
496                              ]
497
498         -- Sort the exports to make them easier to compare for versions
499         my_exports = groupAvails this_module export_avails
500         
501         final_decls = rn_local_decls ++ rn_imp_decls
502
503         -- In interactive mode, we don't want to discard any top-level
504         -- entities at all (eg. do not inline them away during
505         -- simplification), and retain them all in the TypeEnv so they are
506         -- available from the command line.
507         --
508         -- isExternalName separates the user-defined top-level names from those
509         -- introduced by the type checker.
510         dont_discard :: Name -> Bool
511         dont_discard | ghci_mode == Interactive = isExternalName
512                      | otherwise                = (`elemNameSet` export_fvs)
513
514         mod_iface = ModIface {  mi_module   = this_module,
515                                 mi_package  = opt_InPackage,
516                                 mi_version  = initialVersionInfo,
517                                 mi_usages   = my_usages,
518                                 mi_boot     = False,
519                                 mi_orphan   = panic "is_orphan",
520                                 mi_exports  = my_exports,
521                                 mi_globals  = Just gbl_env,
522                                 mi_fixities = fixities,
523                                 mi_deprecs  = my_deprecs,
524                                 mi_decls    = panic "mi_decls"
525                     }
526
527         rn_result = RnResult { rr_mod      = this_module,
528                                rr_fixities = fixities,
529                                rr_decls    = final_decls,
530                                rr_main     = maybe_main_name }
531     in
532
533         -- REPORT UNUSED NAMES, AND DEBUG DUMP 
534     reportUnusedNames mod_iface print_unqualified 
535                       imports full_avail_env gbl_env
536                       used_fvs rn_imp_decls             `thenRn_`
537                 -- NB: used_fvs: include exports (else we get bogus 
538                 --     warnings of unused things) but not implicit FVs.
539
540     returnRn (print_unqualified, Just (dont_discard, mod_iface, rn_result))
541   where
542     mod_name = moduleName this_module
543 \end{code}
544
545
546
547 %*********************************************************
548 %*                                                       *
549 \subsection{Fixities}
550 %*                                                       *
551 %*********************************************************
552
553 \begin{code}
554 fixitiesFromLocalDecls :: GlobalRdrEnv -> [RdrNameHsDecl] -> RnMG LocalFixityEnv
555 fixitiesFromLocalDecls gbl_env decls
556   = foldlRn getFixities emptyNameEnv decls                              `thenRn` \ env -> 
557     traceRn (text "fixity env" <+> vcat (map ppr (nameEnvElts env)))    `thenRn_`
558     returnRn env
559   where
560     getFixities :: LocalFixityEnv -> RdrNameHsDecl -> RnMG LocalFixityEnv
561     getFixities acc (FixD fix)
562       = fix_decl acc fix
563
564     getFixities acc (TyClD (ClassDecl { tcdSigs = sigs}))
565       = foldlRn fix_decl acc [sig | FixSig sig <- sigs]
566                 -- Get fixities from class decl sigs too.
567     getFixities acc other_decl
568       = returnRn acc
569
570     fix_decl acc sig@(FixitySig rdr_name fixity loc)
571         =       -- Check for fixity decl for something not declared
572           pushSrcLocRn loc                      $
573           lookupSrcName gbl_env rdr_name        `thenRn` \ name ->
574
575                 -- Check for duplicate fixity decl
576           case lookupNameEnv acc name of
577             Just (FixitySig _ _ loc') -> addErrRn (dupFixityDecl rdr_name loc loc')     `thenRn_`
578                                          returnRn acc ;
579
580             Nothing                   -> returnRn (extendNameEnv acc name (FixitySig name fixity loc))
581 \end{code}
582
583
584 %*********************************************************
585 %*                                                       *
586 \subsection{Deprecations}
587 %*                                                       *
588 %*********************************************************
589
590 For deprecations, all we do is check that the names are in scope.
591 It's only imported deprecations, dealt with in RnIfaces, that we
592 gather them together.
593
594 \begin{code}
595 rnDeprecs :: GlobalRdrEnv -> Maybe DeprecTxt
596            -> [RdrNameDeprecation] -> RnMG Deprecations
597 rnDeprecs gbl_env Nothing []
598  = returnRn NoDeprecs
599
600 rnDeprecs gbl_env (Just txt) decls
601  = mapRn (addErrRn . badDeprec) decls   `thenRn_` 
602    returnRn (DeprecAll txt)
603
604 rnDeprecs gbl_env Nothing decls
605   = mapRn rn_deprec decls       `thenRn` \ pairs ->
606     returnRn (DeprecSome (mkNameEnv (catMaybes pairs)))
607  where
608    rn_deprec (Deprecation rdr_name txt loc)
609      = pushSrcLocRn loc                         $
610        lookupSrcName gbl_env rdr_name           `thenRn` \ name ->
611        returnRn (Just (name, (name,txt)))
612 \end{code}
613
614
615 %************************************************************************
616 %*                                                                      *
617 \subsection{Grabbing the old interface file and checking versions}
618 %*                                                                      *
619 %************************************************************************
620
621 \begin{code}
622 checkOldIface :: GhciMode
623               -> DynFlags
624               -> HomeIfaceTable -> HomeSymbolTable
625               -> PersistentCompilerState
626               -> Module
627               -> FilePath
628               -> Bool                   -- Source unchanged
629               -> Maybe ModIface         -- Old interface from compilation manager, if any
630               -> IO (PersistentCompilerState, Bool, (RecompileRequired, Maybe ModIface))
631                                 -- True <=> errors happened
632
633 checkOldIface ghci_mode dflags hit hst pcs mod iface_path source_unchanged maybe_iface
634     = runRn dflags hit hst pcs (panic "Bogus module") $
635
636         -- CHECK WHETHER THE SOURCE HAS CHANGED
637     ( if not source_unchanged then
638         traceHiDiffsRn (nest 4 (text "Source file changed or recompilation check turned off"))    
639       else returnRn () )   `thenRn_`
640
641      -- If the source has changed and we're in interactive mode, avoid reading
642      -- an interface; just return the one we might have been supplied with.
643     if ghci_mode == Interactive && not source_unchanged then
644          returnRn (outOfDate, maybe_iface)
645     else
646
647     setModuleRn mod $
648     case maybe_iface of
649        Just old_iface -> -- Use the one we already have
650                          check_versions old_iface
651
652        Nothing -- try and read it from a file
653           -> readIface iface_path       `thenRn` \ read_result ->
654              case read_result of
655                Left err -> -- Old interface file not found, or garbled; give up
656                            traceHiDiffsRn (
657                                 text "Cannot read old interface file:"
658                                    $$ nest 4 err) `thenRn_`
659                            returnRn (outOfDate, Nothing)
660
661                Right parsed_iface ->
662                       let read_mod_name = pi_mod parsed_iface
663                           wanted_mod_name = moduleName mod
664                       in
665                       if (wanted_mod_name /= read_mod_name) then
666                          traceHiDiffsRn (
667                             text "Existing interface file has wrong module name: "
668                                  <> quotes (ppr read_mod_name)
669                                 ) `thenRn_`
670                          returnRn (outOfDate, Nothing)
671                       else
672                          loadOldIface mod parsed_iface `thenRn` \ m_iface ->
673                          check_versions m_iface
674     where
675        check_versions :: ModIface -> RnMG (RecompileRequired, Maybe ModIface)
676        check_versions iface
677           | not source_unchanged
678           = returnRn (outOfDate, Just iface)
679           | otherwise
680           = -- Check versions
681             recompileRequired iface_path iface  `thenRn` \ recompile ->
682             returnRn (recompile, Just iface)
683 \end{code}
684
685 I think the following function should now have a more representative name,
686 but what?
687
688 \begin{code}
689 loadOldIface :: Module -> ParsedIface -> RnMG ModIface
690
691 loadOldIface mod parsed_iface
692   = let iface = parsed_iface 
693     in
694     initIfaceRnMS mod (
695         loadHomeDecls (pi_decls iface)  `thenRn` \ decls ->
696         loadHomeRules (pi_rules iface)  `thenRn` \ rules -> 
697         loadHomeInsts (pi_insts iface)  `thenRn` \ insts ->
698         returnRn (decls, rules, insts)
699     )   
700         `thenRn` \ ((decls_vers, new_decls), (rule_vers, new_rules), new_insts) ->
701
702     mapRn loadHomeUsage (pi_usages iface)       `thenRn` \ usages ->
703     loadExports         (pi_exports iface)      `thenRn` \ (export_vers, avails) ->
704     loadFixDecls mod    (pi_fixity iface)       `thenRn` \ fix_env ->
705     loadDeprecs mod     (pi_deprecs iface)      `thenRn` \ deprec_env ->
706     let
707         version = VersionInfo { vers_module  = pi_vers iface, 
708                                 vers_exports = export_vers,
709                                 vers_rules   = rule_vers,
710                                 vers_decls   = decls_vers }
711
712         decls = mkIfaceDecls new_decls new_rules new_insts
713
714         mod_iface = ModIface { mi_module = mod, mi_package = pi_pkg parsed_iface,
715                                mi_version = version,
716                                mi_exports = avails, mi_usages  = usages,
717                                mi_boot = False, mi_orphan = pi_orphan iface, 
718                                mi_fixities = fix_env, mi_deprecs = deprec_env,
719                                mi_decls   = decls,
720                                mi_globals = Nothing
721                     }
722     in
723     returnRn mod_iface
724 \end{code}
725
726 \begin{code}
727 loadHomeDecls :: [(Version, RdrNameTyClDecl)]
728               -> RnMS (NameEnv Version, [RenamedTyClDecl])
729 loadHomeDecls decls = foldlRn loadHomeDecl (emptyNameEnv, []) decls
730
731 loadHomeDecl :: (NameEnv Version, [RenamedTyClDecl])
732              -> (Version, RdrNameTyClDecl)
733              -> RnMS (NameEnv Version, [RenamedTyClDecl])
734 loadHomeDecl (version_map, decls) (version, decl)
735   = rnTyClDecl decl     `thenRn` \ decl' ->
736     returnRn (extendNameEnv version_map (tyClDeclName decl') version, decl':decls)
737
738 ------------------
739 loadHomeRules :: (Version, [RdrNameRuleDecl])
740               -> RnMS (Version, [RenamedRuleDecl])
741 loadHomeRules (version, rules)
742   = mapRn rnIfaceRuleDecl rules `thenRn` \ rules' ->
743     returnRn (version, rules')
744
745 ------------------
746 loadHomeInsts :: [RdrNameInstDecl]
747               -> RnMS [RenamedInstDecl]
748 loadHomeInsts insts = mapRn rnInstDecl insts
749
750 ------------------
751 loadHomeUsage :: ImportVersion OccName
752               -> RnMG (ImportVersion Name)
753 loadHomeUsage (mod_name, orphans, is_boot, whats_imported)
754   = rn_imps whats_imported      `thenRn` \ whats_imported' ->
755     returnRn (mod_name, orphans, is_boot, whats_imported')
756   where
757     rn_imps NothingAtAll                  = returnRn NothingAtAll
758     rn_imps (Everything v)                = returnRn (Everything v)
759     rn_imps (Specifically mv ev items rv) = mapRn rn_imp items  `thenRn` \ items' ->
760                                             returnRn (Specifically mv ev items' rv)
761     rn_imp (occ,vers) = newGlobalName mod_name occ      `thenRn` \ name ->
762                         returnRn (name,vers)
763 \end{code}
764
765
766
767 %*********************************************************
768 %*                                                       *
769 \subsection{Closing up the interface decls}
770 %*                                                       *
771 %*********************************************************
772
773 Suppose we discover we don't need to recompile.   Then we start from the
774 IfaceDecls in the ModIface, and fluff them up by sucking in all the decls they need.
775
776 \begin{code}
777 closeIfaceDecls :: DynFlags
778                 -> HomeIfaceTable -> HomeSymbolTable
779                 -> PersistentCompilerState
780                 -> ModIface     -- Get the decls from here
781                 -> IO (PersistentCompilerState, Bool, [RenamedHsDecl])
782                                 -- True <=> errors happened
783 closeIfaceDecls dflags hit hst pcs
784                 mod_iface@(ModIface { mi_module = mod, mi_decls = iface_decls })
785   = runRn dflags hit hst pcs mod $
786
787     let
788         rule_decls = dcl_rules iface_decls
789         inst_decls = dcl_insts iface_decls
790         tycl_decls = dcl_tycl  iface_decls
791         decls = map RuleD rule_decls ++
792                 map InstD inst_decls ++
793                 map TyClD tycl_decls
794         needed = unionManyNameSets (map ruleDeclFVs rule_decls) `unionNameSets`
795                  unionManyNameSets (map instDeclFVs inst_decls) `unionNameSets`
796                  unionManyNameSets (map tyClDeclFVs tycl_decls)
797         local_names    = foldl add emptyNameSet tycl_decls
798         add names decl = addListToNameSet names (map fst (tyClDeclSysNames decl ++ tyClDeclNames decl))
799     in
800
801     recordLocalSlurps local_names       `thenRn_`
802
803         -- Do the transitive closure
804     closeDecls decls (needed `plusFV` implicit_fvs) `thenRn` \closed_decls ->
805     rnDump [] closed_decls `thenRn_`
806     returnRn closed_decls
807   where
808     implicit_fvs = ubiquitousNames      -- Data type decls with record selectors,
809                                         -- which may appear in the decls, need unpackCString
810                                         -- and friends. It's easier to just grab them right now.
811 \end{code}
812
813 %*********************************************************
814 %*                                                       *
815 \subsection{Unused names}
816 %*                                                       *
817 %*********************************************************
818
819 \begin{code}
820 reportUnusedNames :: ModIface -> PrintUnqualified
821                   -> [RdrNameImportDecl] 
822                   -> AvailEnv
823                   -> GlobalRdrEnv
824                   -> NameSet            -- Used in this module
825                   -> [RenamedHsDecl] 
826                   -> RnMG ()
827 reportUnusedNames my_mod_iface unqual imports avail_env gbl_env
828                   used_names imported_decls
829   = warnUnusedModules unused_imp_mods                           `thenRn_`
830     warnUnusedLocalBinds bad_locals                             `thenRn_`
831     warnUnusedImports bad_imp_names                             `thenRn_`
832     printMinimalImports this_mod unqual minimal_imports
833   where
834     this_mod   = mi_module my_mod_iface
835     
836     -- Now, a use of C implies a use of T,
837     -- if C was brought into scope by T(..) or T(C)
838     really_used_names = used_names `unionNameSets`
839       mkNameSet [ parent_name
840                 | sub_name <- nameSetToList used_names
841     
842                 -- Usually, every used name will appear in avail_env, but there 
843                 -- is one time when it doesn't: tuples and other built in syntax.  When you
844                 -- write (a,b) that gives rise to a *use* of "(,)", so that the
845                 -- instances will get pulled in, but the tycon "(,)" isn't actually
846                 -- in scope.  Also, (-x) gives rise to an implicit use of 'negate'; 
847                 -- similarly,   3.5 gives rise to an implcit use of :%
848                 -- Hence the silent 'False' in all other cases
849               
850                 , Just parent_name <- [case lookupNameEnv avail_env sub_name of
851                                         Just (AvailTC n _) -> Just n
852                                         other              -> Nothing]
853             ]
854     
855         -- Collect the defined names from the in-scope environment
856         -- Look for the qualified ones only, else get duplicates
857     defined_names :: [GlobalRdrElt]
858     defined_names = foldRdrEnv add [] gbl_env
859     add rdr_name ns acc | isQual rdr_name = ns ++ acc
860                         | otherwise       = acc
861
862     defined_and_used, defined_but_not_used :: [GlobalRdrElt]
863     (defined_and_used, defined_but_not_used) = partition used defined_names
864     used (GRE name _ _)                      = name `elemNameSet` really_used_names
865     
866     -- Filter out the ones only defined implicitly
867     bad_locals :: [Name]
868     bad_locals = [n | (GRE n LocalDef _) <- defined_but_not_used]
869     
870     bad_imp_names :: [(Name,Provenance)]
871     bad_imp_names  = [(n,p) | GRE n p@(NonLocalDef (UserImport mod _ True)) _ <- defined_but_not_used,
872                               not (module_unused mod)]
873     
874     -- inst_mods are directly-imported modules that 
875     --  contain instance decl(s) that the renamer decided to suck in
876     -- It's not necessarily redundant to import such modules.
877     --
878     -- NOTE: Consider 
879     --        module This
880     --          import M ()
881     --
882     --   The import M() is not *necessarily* redundant, even if
883     --   we suck in no instance decls from M (e.g. it contains 
884     --   no instance decls, or This contains no code).  It may be 
885     --   that we import M solely to ensure that M's orphan instance 
886     --   decls (or those in its imports) are visible to people who 
887     --   import This.  Sigh. 
888     --   There's really no good way to detect this, so the error message 
889     --   in RnEnv.warnUnusedModules is weakened instead
890     inst_mods :: [ModuleName]
891     inst_mods = [m | InstD (InstDecl _ _ _ (Just dfun) _) <- imported_decls,
892                  let m = moduleName (nameModule dfun),
893                  m `elem` direct_import_mods
894             ]
895     
896     -- To figure out the minimal set of imports, start with the things
897     -- that are in scope (i.e. in gbl_env).  Then just combine them
898     -- into a bunch of avails, so they are properly grouped
899     minimal_imports :: FiniteMap ModuleName AvailEnv
900     minimal_imports0 = emptyFM
901     minimal_imports1 = foldr add_name     minimal_imports0 defined_and_used
902     minimal_imports  = foldr add_inst_mod minimal_imports1 inst_mods
903     
904         -- We've carefully preserved the provenance so that we can
905         -- construct minimal imports that import the name by (one of)
906         -- the same route(s) as the programmer originally did.
907     add_name (GRE n (NonLocalDef (UserImport m _ _)) _) acc = addToFM_C plusAvailEnv acc (moduleName m)
908                                                                         (unitAvailEnv (mk_avail n))
909     add_name (GRE n other_prov _)                       acc = acc
910
911     mk_avail n = case lookupNameEnv avail_env n of
912                 Just (AvailTC m _) | n==m      -> AvailTC n [n]
913                                    | otherwise -> AvailTC m [n,m]
914                 Just avail         -> Avail n
915                 Nothing            -> pprPanic "mk_avail" (ppr n)
916     
917     add_inst_mod m acc 
918       | m `elemFM` acc = acc    -- We import something already
919       | otherwise      = addToFM acc m emptyAvailEnv
920         -- Add an empty collection of imports for a module
921         -- from which we have sucked only instance decls
922    
923     direct_import_mods :: [ModuleName]
924     direct_import_mods = nub [m | ImportDecl m _ _ _ _ _ <- imports]
925
926     -- unused_imp_mods are the directly-imported modules 
927     -- that are not mentioned in minimal_imports
928     unused_imp_mods = [m | m <- direct_import_mods,
929                        not (maybeToBool (lookupFM minimal_imports m)),
930                        m /= pRELUDE_Name]
931     
932     module_unused :: Module -> Bool
933     module_unused mod = moduleName mod `elem` unused_imp_mods
934
935
936 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
937 printMinimalImports :: Module   -- This module
938                     -> PrintUnqualified
939                     -> FiniteMap ModuleName AvailEnv    -- Minimal imports
940                     -> RnMG ()
941 printMinimalImports this_mod unqual imps
942   = ifOptRn Opt_D_dump_minimal_imports          $
943
944     mapRn to_ies (fmToList imps)                `thenRn` \ mod_ies ->
945     ioToRnM (do { h <- openFile filename WriteMode ;
946                   printForUser h unqual (vcat (map ppr_mod_ie mod_ies))
947         })                                      `thenRn_`
948     returnRn ()
949   where
950     filename = moduleNameUserString (moduleName this_mod) ++ ".imports"
951     ppr_mod_ie (mod_name, ies) 
952         | mod_name == pRELUDE_Name 
953         = empty
954         | otherwise
955         = ptext SLIT("import") <+> ppr mod_name <> 
956                             parens (fsep (punctuate comma (map ppr ies)))
957
958     to_ies (mod, avail_env) = mapRn to_ie (availEnvElts avail_env)      `thenRn` \ ies ->
959                               returnRn (mod, ies)
960
961     to_ie :: AvailInfo -> RnMG (IE Name)
962         -- The main trick here is that if we're importing all the constructors
963         -- we want to say "T(..)", but if we're importing only a subset we want
964         -- to say "T(A,B,C)".  So we have to find out what the module exports.
965     to_ie (Avail n)       = returnRn (IEVar n)
966     to_ie (AvailTC n [m]) = ASSERT( n==m ) 
967                             returnRn (IEThingAbs n)
968     to_ie (AvailTC n ns)  
969         = loadInterface (text "Compute minimal imports from" <+> ppr n_mod) 
970                         n_mod ImportBySystem                            `thenRn` \ iface ->
971           case [xs | (m,as) <- mi_exports iface,
972                      m == n_mod,
973                      AvailTC x xs <- as, 
974                      x == n] of
975               [xs] | all (`elem` ns) xs -> returnRn (IEThingAll n)
976                    | otherwise          -> returnRn (IEThingWith n (filter (/= n) ns))
977               other                     -> pprTrace "to_ie" (ppr n <+> ppr (nameModule n) <+> ppr other) $
978                                            returnRn (IEVar n)
979         where
980           n_mod = moduleName (nameModule n)
981
982 rnDump  :: [RenamedHsDecl]      -- Renamed imported decls
983         -> [RenamedHsDecl]      -- Renamed local decls
984         -> RnMG ()
985 rnDump imp_decls local_decls
986   = doptRn Opt_D_dump_rn_trace  `thenRn` \ dump_rn_trace ->
987     doptRn Opt_D_dump_rn_stats  `thenRn` \ dump_rn_stats ->
988     doptRn Opt_D_dump_rn        `thenRn` \ dump_rn ->
989     getIfacesRn                 `thenRn` \ ifaces ->
990
991     ioToRnM (do { dumpIfSet (dump_rn_trace || dump_rn_stats || dump_rn)
992                             "Renamer statistics"
993                             (getRnStats imp_decls ifaces) ;
994
995                   dumpIfSet dump_rn "Renamer:" 
996                             (vcat (map ppr (local_decls ++ imp_decls)))
997     })                          `thenRn_`
998
999     returnRn ()
1000 \end{code}
1001
1002
1003 %*********************************************************
1004 %*                                                      *
1005 \subsection{Statistics}
1006 %*                                                      *
1007 %*********************************************************
1008
1009 \begin{code}
1010 getRnStats :: [RenamedHsDecl] -> Ifaces -> SDoc
1011 getRnStats imported_decls ifaces
1012   = hcat [text "Renamer stats: ", stats]
1013   where
1014     n_mods = length [() | _ <- moduleEnvElts (iPIT ifaces)]
1015         -- This is really only right for a one-shot compile
1016
1017     (decls_map, n_decls_slurped) = iDecls ifaces
1018     
1019     n_decls_left   = length [decl | (avail, True, (_,decl)) <- nameEnvElts decls_map
1020                         -- Data, newtype, and class decls are in the decls_fm
1021                         -- under multiple names; the tycon/class, and each
1022                         -- constructor/class op too.
1023                         -- The 'True' selects just the 'main' decl
1024                      ]
1025     
1026     (insts_left, n_insts_slurped) = iInsts ifaces
1027     n_insts_left  = length (bagToList insts_left)
1028     
1029     (rules_left, n_rules_slurped) = iRules ifaces
1030     n_rules_left  = length (bagToList rules_left)
1031     
1032     stats = vcat 
1033         [int n_mods <+> text "interfaces read",
1034          hsep [ int n_decls_slurped, text "type/class/variable imported, out of", 
1035                 int (n_decls_slurped + n_decls_left), text "read"],
1036          hsep [ int n_insts_slurped, text "instance decls imported, out of",  
1037                 int (n_insts_slurped + n_insts_left), text "read"],
1038          hsep [ int n_rules_slurped, text "rule decls imported, out of",  
1039                 int (n_rules_slurped + n_rules_left), text "read"]
1040         ]
1041 \end{code}    
1042
1043
1044 %************************************************************************
1045 %*                                                                      *
1046 \subsection{Errors and warnings}
1047 %*                                                                      *
1048 %************************************************************************
1049
1050 \begin{code}
1051 dupFixityDecl rdr_name loc1 loc2
1052   = vcat [ptext SLIT("Multiple fixity declarations for") <+> quotes (ppr rdr_name),
1053           ptext SLIT("at ") <+> ppr loc1,
1054           ptext SLIT("and") <+> ppr loc2]
1055
1056 badDeprec d
1057   = sep [ptext SLIT("Illegal deprecation when whole module is deprecated"),
1058          nest 4 (ppr d)]
1059 \end{code}
1060
1061