2 % (c) The GRASP Project, Glasgow University, 1992-1998
4 \section[Rename]{Renaming and dependency analysis passes}
7 module Rename ( renameModule, renameExpr, closeIfaceDecls, checkOldIface ) where
9 #include "HsVersions.h"
12 import RdrHsSyn ( RdrNameHsModule, RdrNameHsDecl, RdrNameDeprecation, RdrNameHsExpr,
13 RdrNameTyClDecl, RdrNameRuleDecl, RdrNameInstDecl, RdrNameImportDecl
15 import RnHsSyn ( RenamedHsDecl, RenamedTyClDecl, RenamedRuleDecl, RenamedInstDecl,
16 extractHsTyNames, RenamedHsExpr,
17 instDeclFVs, tyClDeclFVs, ruleDeclFVs
20 import CmdLineOpts ( DynFlags, DynFlag(..) )
22 import RnExpr ( rnExpr )
23 import RnNames ( getGlobalNames, exportsFromAvail )
24 import RnSource ( rnSourceDecls, rnTyClDecl, rnIfaceRuleDecl, rnInstDecl )
25 import RnIfaces ( slurpImpDecls, mkImportInfo, recordLocalSlurps,
26 getInterfaceExports, closeDecls,
27 RecompileRequired, outOfDate, recompileRequired
29 import RnHiFiles ( readIface, removeContext, loadInterface,
30 loadExports, loadFixDecls, loadDeprecs,
32 import RnEnv ( availsToNameSet, availName, mkIfaceGlobalRdrEnv,
33 emptyAvailEnv, unitAvailEnv, availEnvElts,
34 plusAvailEnv, groupAvails, warnUnusedImports,
35 warnUnusedLocalBinds, warnUnusedModules,
36 lookupOrigNames, lookupSrcName,
37 newGlobalName, unQualInScope
39 import Module ( Module, ModuleName, WhereFrom(..),
40 moduleNameUserString, moduleName,
43 import Name ( Name, NamedThing(..), getSrcLoc,
44 nameIsLocalOrFrom, nameOccName, nameModule,
46 import Name ( mkNameEnv, nameEnvElts, extendNameEnv )
47 import RdrName ( foldRdrEnv, isQual )
48 import OccName ( occNameFlavour )
50 import TysWiredIn ( unitTyCon, intTyCon, boolTyCon )
51 import PrelNames ( mAIN_Name, pREL_MAIN_Name, pRELUDE_Name,
52 ioTyConName, printName,
53 unpackCStringName, unpackCStringFoldrName, unpackCStringUtf8Name,
56 import PrelInfo ( derivingOccurrences )
57 import Type ( funTyCon )
58 import ErrUtils ( dumpIfSet, dumpIfSet_dyn, showPass,
59 printErrorsAndWarnings, errorsFound )
60 import Bag ( bagToList )
61 import FiniteMap ( FiniteMap, fmToList, emptyFM, lookupFM,
62 addToFM_C, elemFM, addToFM
64 import UniqFM ( lookupWithDefaultUFM )
65 import Maybes ( maybeToBool, catMaybes )
67 import IO ( openFile, IOMode(..) )
68 import HscTypes ( PersistentCompilerState, HomeIfaceTable, HomeSymbolTable,
69 ModIface(..), WhatsImported(..),
70 VersionInfo(..), ImportVersion, IsExported,
71 IfaceDecls, mkIfaceDecls, dcl_tycl, dcl_rules, dcl_insts,
72 GlobalRdrEnv, pprGlobalRdrEnv,
73 AvailEnv, GenAvailInfo(..), AvailInfo, Avails,
74 Provenance(..), ImportReason(..), initialVersionInfo,
75 Deprecations(..), lookupDeprec, lookupIface
77 import CmStaticInfo ( GhciMode(..) )
78 import List ( partition, nub )
84 %*********************************************************
86 \subsection{The two main wrappers}
88 %*********************************************************
91 renameModule :: DynFlags
92 -> HomeIfaceTable -> HomeSymbolTable
93 -> PersistentCompilerState
94 -> Module -> RdrNameHsModule
95 -> IO (PersistentCompilerState, Maybe (PrintUnqualified, (IsExported, ModIface, [RenamedHsDecl])))
96 -- Nothing => some error occurred in the renamer
98 renameModule dflags hit hst pcs this_module rdr_module
99 = renameSource dflags hit hst pcs this_module $
100 rename this_module rdr_module
105 renameExpr :: DynFlags
106 -> HomeIfaceTable -> HomeSymbolTable
107 -> PersistentCompilerState
108 -> Module -> RdrNameHsExpr
109 -> IO ( PersistentCompilerState,
110 Maybe (PrintUnqualified, (RenamedHsExpr, [RenamedHsDecl]))
113 renameExpr dflags hit hst pcs this_module expr
114 = do { renameSource dflags hit hst pcs this_module $
115 tryLoadInterface doc (moduleName this_module) ImportByUser
116 `thenRn` \ (iface, maybe_err) ->
118 Just msg -> ioToRnM (printErrs alwaysQualify
119 (ptext SLIT("failed to load interface for")
120 <+> quotes (ppr this_module)
121 <> char ':' <+> msg)) `thenRn_`
125 let rdr_env = mi_globals iface
126 print_unqual = unQualInScope rdr_env
129 initRnMS rdr_env emptyLocalFixityEnv CmdLineMode (rnExpr expr)
130 `thenRn` \ (e,fvs) ->
132 checkErrsRn `thenRn` \ no_errs_so_far ->
133 if not no_errs_so_far then
134 -- Found errors already, so exit now
135 doDump e [] `thenRn_`
140 implicit_fvs = fvs `plusFV` string_names
141 `plusFV` default_tycon_names
142 `plusFV` unitFV printName
143 -- print :: a -> IO () may be needed later
145 slurpImpDecls (fvs `plusFV` implicit_fvs) `thenRn` \ decls ->
147 doDump e decls `thenRn_`
148 returnRn (Just (print_unqual, (e, decls)))
151 doc = text "context for compiling expression"
153 doDump :: RenamedHsExpr -> [RenamedHsDecl] -> RnMG (Either IOError ())
155 getDOptsRn `thenRn` \ dflags ->
156 ioToRnM (dumpIfSet_dyn dflags Opt_D_dump_rn "Renamer:"
157 (vcat (ppr e : map ppr decls)))
161 %*********************************************************
163 \subsection{The main function: rename}
165 %*********************************************************
168 renameSource :: DynFlags
169 -> HomeIfaceTable -> HomeSymbolTable
170 -> PersistentCompilerState
172 -> RnMG (Maybe (PrintUnqualified, r))
173 -> IO (PersistentCompilerState, Maybe (PrintUnqualified, r))
174 -- Nothing => some error occurred in the renamer
176 renameSource dflags hit hst old_pcs this_module thing_inside
177 = do { showPass dflags "Renamer"
179 -- Initialise the renamer monad
180 ; (new_pcs, msgs, maybe_rn_stuff) <- initRn dflags hit hst old_pcs this_module thing_inside
182 -- Print errors from renaming
183 ; let print_unqual = case maybe_rn_stuff of
184 Just (unqual, _) -> unqual
185 Nothing -> alwaysQualify
187 ; printErrorsAndWarnings print_unqual msgs ;
189 -- Return results. No harm in updating the PCS
190 ; if errorsFound msgs then
191 return (new_pcs, Nothing)
193 return (new_pcs, maybe_rn_stuff)
198 rename :: Module -> RdrNameHsModule -> RnMG (Maybe (PrintUnqualified, (IsExported, ModIface, [RenamedHsDecl])))
199 rename this_module contents@(HsModule _ _ exports imports local_decls mod_deprec loc)
202 -- FIND THE GLOBAL NAME ENVIRONMENT
203 getGlobalNames this_module contents `thenRn` \ (gbl_env, local_gbl_env, all_avails@(_, global_avail_env)) ->
205 -- Exit if we've found any errors
206 checkErrsRn `thenRn` \ no_errs_so_far ->
207 if not no_errs_so_far then
208 -- Found errors already, so exit now
209 rnDump [] [] `thenRn_`
213 -- PROCESS EXPORT LIST
214 exportsFromAvail mod_name exports all_avails gbl_env `thenRn` \ export_avails ->
216 traceRn (text "Local top-level environment" $$
217 nest 4 (pprGlobalRdrEnv local_gbl_env)) `thenRn_`
219 -- DEAL WITH DEPRECATIONS
220 rnDeprecs local_gbl_env mod_deprec
221 [d | DeprecD d <- local_decls] `thenRn` \ my_deprecs ->
223 -- DEAL WITH LOCAL FIXITIES
224 fixitiesFromLocalDecls local_gbl_env local_decls `thenRn` \ local_fixity_env ->
227 rnSourceDecls gbl_env local_fixity_env local_decls `thenRn` \ (rn_local_decls, source_fvs) ->
229 -- EXIT IF ERRORS FOUND
230 -- We exit here if there are any errors in the source, *before*
231 -- we attempt to slurp the decls from the interfaces, otherwise
232 -- the slurped decls may get lost when we return up the stack
233 -- to hscMain/hscExpr.
234 checkErrsRn `thenRn` \ no_errs_so_far ->
235 if not no_errs_so_far then
236 -- Found errors already, so exit now
237 rnDump [] rn_local_decls `thenRn_`
241 -- SLURP IN ALL THE NEEDED DECLARATIONS
242 implicitFVs mod_name rn_local_decls `thenRn` \ implicit_fvs ->
244 slurp_fvs = implicit_fvs `plusFV` source_fvs
245 -- It's important to do the "plus" this way round, so that
246 -- when compiling the prelude, locally-defined (), Bool, etc
247 -- override the implicit ones.
249 traceRn (text "Source FVs:" <+> fsep (map ppr (nameSetToList slurp_fvs))) `thenRn_`
250 slurpImpDecls slurp_fvs `thenRn` \ rn_imp_decls ->
252 rnDump rn_imp_decls rn_local_decls `thenRn_`
254 -- GENERATE THE VERSION/USAGE INFO
255 mkImportInfo mod_name imports `thenRn` \ my_usages ->
257 -- BUILD THE MODULE INTERFACE
259 -- We record fixities even for things that aren't exported,
260 -- so that we can change into the context of this moodule easily
261 fixities = mkNameEnv [ (name, fixity)
262 | FixitySig name fixity loc <- nameEnvElts local_fixity_env
265 -- Sort the exports to make them easier to compare for versions
266 my_exports = groupAvails this_module export_avails
268 final_decls = rn_local_decls ++ rn_imp_decls
269 is_orphan = any (isOrphanDecl this_module) rn_local_decls
271 mod_iface = ModIface { mi_module = this_module,
272 mi_version = initialVersionInfo,
273 mi_usages = my_usages,
275 mi_orphan = is_orphan,
276 mi_exports = my_exports,
277 mi_globals = gbl_env,
278 mi_fixities = fixities,
279 mi_deprecs = my_deprecs,
280 mi_decls = panic "mi_decls"
283 print_unqualified = unQualInScope gbl_env
284 is_exported name = name `elemNameSet` exported_names
285 exported_names = availsToNameSet export_avails
288 -- REPORT UNUSED NAMES, AND DEBUG DUMP
289 reportUnusedNames mod_iface print_unqualified
290 imports global_avail_env
291 source_fvs export_avails rn_imp_decls `thenRn_`
293 returnRn (Just (print_unqualified, (is_exported, mod_iface, final_decls)))
295 mod_name = moduleName this_module
298 @implicitFVs@ forces the renamer to slurp in some things which aren't
299 mentioned explicitly, but which might be needed by the type checker.
302 implicitFVs mod_name decls
303 = lookupOrigNames deriv_occs `thenRn` \ deriving_names ->
304 returnRn (default_tycon_names `plusFV`
305 string_names `plusFV`
306 deriving_names `plusFV`
310 -- Add occurrences for IO or PrimIO
311 implicit_main | mod_name == mAIN_Name
312 || mod_name == pREL_MAIN_Name = unitFV ioTyConName
313 | otherwise = emptyFVs
315 deriv_occs = [occ | TyClD (TyData {tcdDerivs = Just deriv_classes}) <- decls,
316 cls <- deriv_classes,
317 occ <- lookupWithDefaultUFM derivingOccurrences [] cls ]
319 -- Virtually every program has error messages in it somewhere
320 string_names = mkFVs [unpackCStringName, unpackCStringFoldrName,
321 unpackCStringUtf8Name, eqStringName]
323 -- Add occurrences for Int, and (), because they
324 -- are the types to which ambigious type variables may be defaulted by
325 -- the type checker; so they won't always appear explicitly.
326 -- [The () one is a GHC extension for defaulting CCall results.]
327 -- ALSO: funTyCon, since it occurs implicitly everywhere!
328 -- (we don't want to be bothered with making funTyCon a
329 -- free var at every function application!)
330 -- Double is dealt with separately in getGates
331 default_tycon_names = mkFVs (map getName [unitTyCon, funTyCon, boolTyCon, intTyCon])
335 isOrphanDecl this_mod (InstD (InstDecl inst_ty _ _ _ _))
336 = not (foldNameSet ((||) . nameIsLocalOrFrom this_mod) False
337 (extractHsTyNames (removeContext inst_ty)))
338 -- The 'removeContext' is because of
339 -- instance Foo a => Baz T where ...
340 -- The decl is an orphan if Baz and T are both not locally defined,
341 -- even if Foo *is* locally defined
343 isOrphanDecl this_mod (RuleD (HsRule _ _ _ lhs _ _))
346 -- At the moment we just check for common LHS forms
347 -- Expand as necessary. Getting it wrong just means
348 -- more orphans than necessary
349 check (HsVar v) = not (nameIsLocalOrFrom this_mod v)
350 check (HsApp f a) = check f && check a
351 check (HsLit _) = False
352 check (HsOverLit _) = False
353 check (OpApp l o _ r) = check l && check o && check r
354 check (NegApp e _) = check e
355 check (HsPar e) = check e
356 check (SectionL e o) = check e && check o
357 check (SectionR o e) = check e && check o
359 check other = True -- Safe fall through
361 isOrphanDecl _ _ = False
365 %*********************************************************
367 \subsection{Fixities}
369 %*********************************************************
372 fixitiesFromLocalDecls :: GlobalRdrEnv -> [RdrNameHsDecl] -> RnMG LocalFixityEnv
373 fixitiesFromLocalDecls gbl_env decls
374 = foldlRn getFixities emptyNameEnv decls `thenRn` \ env ->
375 traceRn (text "fixity env" <+> vcat (map ppr (nameEnvElts env))) `thenRn_`
378 getFixities :: LocalFixityEnv -> RdrNameHsDecl -> RnMG LocalFixityEnv
379 getFixities acc (FixD fix)
382 getFixities acc (TyClD (ClassDecl { tcdSigs = sigs}))
383 = foldlRn fix_decl acc [sig | FixSig sig <- sigs]
384 -- Get fixities from class decl sigs too.
385 getFixities acc other_decl
388 fix_decl acc sig@(FixitySig rdr_name fixity loc)
389 = -- Check for fixity decl for something not declared
391 lookupSrcName gbl_env rdr_name `thenRn` \ name ->
393 -- Check for duplicate fixity decl
394 case lookupNameEnv acc name of
395 Just (FixitySig _ _ loc') -> addErrRn (dupFixityDecl rdr_name loc loc') `thenRn_`
398 Nothing -> returnRn (extendNameEnv acc name (FixitySig name fixity loc))
402 %*********************************************************
404 \subsection{Deprecations}
406 %*********************************************************
408 For deprecations, all we do is check that the names are in scope.
409 It's only imported deprecations, dealt with in RnIfaces, that we
410 gather them together.
413 rnDeprecs :: GlobalRdrEnv -> Maybe DeprecTxt
414 -> [RdrNameDeprecation] -> RnMG Deprecations
415 rnDeprecs gbl_env Nothing []
418 rnDeprecs gbl_env (Just txt) decls
419 = mapRn (addErrRn . badDeprec) decls `thenRn_`
420 returnRn (DeprecAll txt)
422 rnDeprecs gbl_env Nothing decls
423 = mapRn rn_deprec decls `thenRn` \ pairs ->
424 returnRn (DeprecSome (mkNameEnv (catMaybes pairs)))
426 rn_deprec (Deprecation rdr_name txt loc)
428 lookupSrcName gbl_env rdr_name `thenRn` \ name ->
429 returnRn (Just (name, (name,txt)))
433 %************************************************************************
435 \subsection{Grabbing the old interface file and checking versions}
437 %************************************************************************
440 checkOldIface :: GhciMode
442 -> HomeIfaceTable -> HomeSymbolTable
443 -> PersistentCompilerState
445 -> Bool -- Source unchanged
446 -> Maybe ModIface -- Old interface from compilation manager, if any
447 -> IO (PersistentCompilerState, Bool, (RecompileRequired, Maybe ModIface))
448 -- True <=> errors happened
450 checkOldIface ghci_mode dflags hit hst pcs iface_path source_unchanged maybe_iface
452 -- If the source has changed and we're in interactive mode, avoid reading
453 -- an interface; just return the one we might have been supplied with.
454 | ghci_mode == Interactive && not source_unchanged
455 = return (pcs, False, (outOfDate, maybe_iface))
458 = runRn dflags hit hst pcs (panic "Bogus module") $
460 Just old_iface -> -- Use the one we already have
461 setModuleRn (mi_module old_iface) (check_versions old_iface)
463 Nothing -- try and read it from a file
464 -> readIface iface_path `thenRn` \ read_result ->
466 Left err -> -- Old interface file not found, or garbled; give up
467 traceRn (text "Bad old interface file" $$ nest 4 err) `thenRn_`
468 returnRn (outOfDate, Nothing)
471 -> setModuleRn (pi_mod parsed_iface) $
472 loadOldIface parsed_iface `thenRn` \ m_iface ->
473 check_versions m_iface
475 check_versions :: ModIface -> RnMG (RecompileRequired, Maybe ModIface)
478 recompileRequired iface_path source_unchanged iface
479 `thenRn` \ recompile ->
480 returnRn (recompile, Just iface)
483 I think the following function should now have a more representative name,
487 loadOldIface :: ParsedIface -> RnMG ModIface
489 loadOldIface parsed_iface
490 = let iface = parsed_iface
494 loadHomeDecls (pi_decls iface) `thenRn` \ decls ->
495 loadHomeRules (pi_rules iface) `thenRn` \ rules ->
496 loadHomeInsts (pi_insts iface) `thenRn` \ insts ->
497 returnRn (decls, rules, insts)
499 `thenRn` \ ((decls_vers, new_decls), (rule_vers, new_rules), new_insts) ->
501 mapRn loadHomeUsage (pi_usages iface) `thenRn` \ usages ->
502 loadExports (pi_exports iface) `thenRn` \ (export_vers, avails) ->
503 loadFixDecls mod (pi_fixity iface) `thenRn` \ fix_env ->
504 loadDeprecs mod (pi_deprecs iface) `thenRn` \ deprec_env ->
506 version = VersionInfo { vers_module = pi_vers iface,
507 vers_exports = export_vers,
508 vers_rules = rule_vers,
509 vers_decls = decls_vers }
511 decls = mkIfaceDecls new_decls new_rules new_insts
513 mod_iface = ModIface { mi_module = mod, mi_version = version,
514 mi_exports = avails, mi_usages = usages,
515 mi_boot = False, mi_orphan = pi_orphan iface,
516 mi_fixities = fix_env, mi_deprecs = deprec_env,
518 mi_globals = mkIfaceGlobalRdrEnv avails
525 loadHomeDecls :: [(Version, RdrNameTyClDecl)]
526 -> RnMS (NameEnv Version, [RenamedTyClDecl])
527 loadHomeDecls decls = foldlRn loadHomeDecl (emptyNameEnv, []) decls
529 loadHomeDecl :: (NameEnv Version, [RenamedTyClDecl])
530 -> (Version, RdrNameTyClDecl)
531 -> RnMS (NameEnv Version, [RenamedTyClDecl])
532 loadHomeDecl (version_map, decls) (version, decl)
533 = rnTyClDecl decl `thenRn` \ decl' ->
534 returnRn (extendNameEnv version_map (tyClDeclName decl') version, decl':decls)
537 loadHomeRules :: (Version, [RdrNameRuleDecl])
538 -> RnMS (Version, [RenamedRuleDecl])
539 loadHomeRules (version, rules)
540 = mapRn rnIfaceRuleDecl rules `thenRn` \ rules' ->
541 returnRn (version, rules')
544 loadHomeInsts :: [RdrNameInstDecl]
545 -> RnMS [RenamedInstDecl]
546 loadHomeInsts insts = mapRn rnInstDecl insts
549 loadHomeUsage :: ImportVersion OccName
550 -> RnMG (ImportVersion Name)
551 loadHomeUsage (mod_name, orphans, is_boot, whats_imported)
552 = rn_imps whats_imported `thenRn` \ whats_imported' ->
553 returnRn (mod_name, orphans, is_boot, whats_imported')
555 rn_imps NothingAtAll = returnRn NothingAtAll
556 rn_imps (Everything v) = returnRn (Everything v)
557 rn_imps (Specifically mv ev items rv) = mapRn rn_imp items `thenRn` \ items' ->
558 returnRn (Specifically mv ev items' rv)
559 rn_imp (occ,vers) = newGlobalName mod_name occ `thenRn` \ name ->
565 %*********************************************************
567 \subsection{Closing up the interface decls}
569 %*********************************************************
571 Suppose we discover we don't need to recompile. Then we start from the
572 IfaceDecls in the ModIface, and fluff them up by sucking in all the decls they need.
575 closeIfaceDecls :: DynFlags
576 -> HomeIfaceTable -> HomeSymbolTable
577 -> PersistentCompilerState
578 -> ModIface -- Get the decls from here
579 -> IO (PersistentCompilerState, Bool, [RenamedHsDecl])
580 -- True <=> errors happened
581 closeIfaceDecls dflags hit hst pcs
582 mod_iface@(ModIface { mi_module = mod, mi_decls = iface_decls })
583 = runRn dflags hit hst pcs mod $
586 rule_decls = dcl_rules iface_decls
587 inst_decls = dcl_insts iface_decls
588 tycl_decls = dcl_tycl iface_decls
589 decls = map RuleD rule_decls ++
590 map InstD inst_decls ++
592 needed = unionManyNameSets (map ruleDeclFVs rule_decls) `unionNameSets`
593 unionManyNameSets (map instDeclFVs inst_decls) `unionNameSets`
594 unionManyNameSets (map tyClDeclFVs tycl_decls)
595 local_names = foldl add emptyNameSet tycl_decls
596 add names decl = addListToNameSet names (map fst (tyClDeclSysNames decl ++ tyClDeclNames decl))
599 recordLocalSlurps local_names `thenRn_`
601 -- Do the transitive closure
602 closeDecls decls (needed `plusFV` implicit_fvs) `thenRn` \closed_decls ->
603 rnDump [] closed_decls `thenRn_`
604 returnRn closed_decls
606 implicit_fvs = string_names -- Data type decls with record selectors,
607 -- which may appear in the decls, need unpackCString
608 -- and friends. It's easier to just grab them right now.
611 %*********************************************************
613 \subsection{Unused names}
615 %*********************************************************
618 reportUnusedNames :: ModIface -> PrintUnqualified
619 -> [RdrNameImportDecl]
621 -> NameSet -- Used in this module
622 -> Avails -- Exported by this module
625 reportUnusedNames my_mod_iface unqual imports avail_env
626 source_fvs export_avails imported_decls
627 = warnUnusedModules unused_imp_mods `thenRn_`
628 warnUnusedLocalBinds bad_locals `thenRn_`
629 warnUnusedImports bad_imp_names `thenRn_`
630 printMinimalImports this_mod unqual minimal_imports `thenRn_`
631 warnDeprecations this_mod export_avails my_deprecs
635 this_mod = mi_module my_mod_iface
636 gbl_env = mi_globals my_mod_iface
637 my_deprecs = mi_deprecs my_mod_iface
639 -- The export_fvs make the exported names look just as if they
640 -- occurred in the source program.
641 export_fvs = availsToNameSet export_avails
642 used_names = source_fvs `plusFV` export_fvs
644 -- Now, a use of C implies a use of T,
645 -- if C was brought into scope by T(..) or T(C)
646 really_used_names = used_names `unionNameSets`
647 mkNameSet [ parent_name
648 | sub_name <- nameSetToList used_names
650 -- Usually, every used name will appear in avail_env, but there
651 -- is one time when it doesn't: tuples and other built in syntax. When you
652 -- write (a,b) that gives rise to a *use* of "(,)", so that the
653 -- instances will get pulled in, but the tycon "(,)" isn't actually
654 -- in scope. Also, (-x) gives rise to an implicit use of 'negate';
655 -- similarly, 3.5 gives rise to an implcit use of :%
656 -- Hence the silent 'False' in all other cases
658 , Just parent_name <- [case lookupNameEnv avail_env sub_name of
659 Just (AvailTC n _) -> Just n
663 -- Collect the defined names from the in-scope environment
664 -- Look for the qualified ones only, else get duplicates
665 defined_names :: [(Name,Provenance)]
666 defined_names = foldRdrEnv add [] gbl_env
667 add rdr_name ns acc | isQual rdr_name = ns ++ acc
670 defined_and_used, defined_but_not_used :: [(Name,Provenance)]
671 (defined_and_used, defined_but_not_used) = partition used defined_names
672 used (name,_) = name `elemNameSet` really_used_names
674 -- Filter out the ones only defined implicitly
676 bad_locals = [n | (n,LocalDef) <- defined_but_not_used]
678 bad_imp_names :: [(Name,Provenance)]
679 bad_imp_names = [(n,p) | (n,p@(NonLocalDef (UserImport mod _ True))) <- defined_but_not_used,
680 not (module_unused mod)]
682 -- inst_mods are directly-imported modules that
683 -- contain instance decl(s) that the renamer decided to suck in
684 -- It's not necessarily redundant to import such modules.
690 -- The import M() is not *necessarily* redundant, even if
691 -- we suck in no instance decls from M (e.g. it contains
692 -- no instance decls, or This contains no code). It may be
693 -- that we import M solely to ensure that M's orphan instance
694 -- decls (or those in its imports) are visible to people who
695 -- import This. Sigh.
696 -- There's really no good way to detect this, so the error message
697 -- in RnEnv.warnUnusedModules is weakened instead
698 inst_mods :: [ModuleName]
699 inst_mods = [m | InstD (InstDecl _ _ _ (Just dfun) _) <- imported_decls,
700 let m = moduleName (nameModule dfun),
701 m `elem` direct_import_mods
704 -- To figure out the minimal set of imports, start with the things
705 -- that are in scope (i.e. in gbl_env). Then just combine them
706 -- into a bunch of avails, so they are properly grouped
707 minimal_imports :: FiniteMap ModuleName AvailEnv
708 minimal_imports0 = emptyFM
709 minimal_imports1 = foldr add_name minimal_imports0 defined_and_used
710 minimal_imports = foldr add_inst_mod minimal_imports1 inst_mods
712 -- We've carefully preserved the provenance so that we can
713 -- construct minimal imports that import the name by (one of)
714 -- the same route(s) as the programmer originally did.
715 add_name (n,NonLocalDef (UserImport m _ _)) acc = addToFM_C plusAvailEnv acc (moduleName m)
716 (unitAvailEnv (mk_avail n))
717 add_name (n,other_prov) acc = acc
719 mk_avail n = case lookupNameEnv avail_env n of
720 Just (AvailTC m _) | n==m -> AvailTC n [n]
721 | otherwise -> AvailTC m [n,m]
722 Just avail -> Avail n
723 Nothing -> pprPanic "mk_avail" (ppr n)
726 | m `elemFM` acc = acc -- We import something already
727 | otherwise = addToFM acc m emptyAvailEnv
728 -- Add an empty collection of imports for a module
729 -- from which we have sucked only instance decls
731 direct_import_mods :: [ModuleName]
732 direct_import_mods = nub [m | ImportDecl m _ _ _ _ _ <- imports]
734 -- unused_imp_mods are the directly-imported modules
735 -- that are not mentioned in minimal_imports
736 unused_imp_mods = [m | m <- direct_import_mods,
737 not (maybeToBool (lookupFM minimal_imports m)),
740 module_unused :: Module -> Bool
741 module_unused mod = moduleName mod `elem` unused_imp_mods
743 warnDeprecations this_mod export_avails my_deprecs used_names
744 = doptRn Opt_WarnDeprecations `thenRn` \ warn_drs ->
745 if not warn_drs then returnRn () else
747 -- The home modules for things in the export list
748 -- may not have been loaded yet; do it now, so
749 -- that we can see their deprecations, if any
750 mapRn_ load_home export_mods `thenRn_`
752 getIfacesRn `thenRn` \ ifaces ->
753 getHomeIfaceTableRn `thenRn` \ hit ->
757 | n <- nameSetToList used_names,
758 not (nameIsLocalOrFrom this_mod n),
759 Just txt <- [lookup_deprec hit pit n] ]
760 -- nameIsLocalOrFrom: don't complain about locally defined names
761 -- For a start, we may be exporting a deprecated thing
762 -- Also we may use a deprecated thing in the defn of another
763 -- deprecated things. We may even use a deprecated thing in
764 -- the defn of a non-deprecated thing, when changing a module's
767 mapRn_ warnDeprec deprecs
770 export_mods = nub [ moduleName mod
771 | avail <- export_avails,
772 let mod = nameModule (availName avail),
775 load_home m = loadInterface (text "Check deprecations for" <+> ppr m) m ImportBySystem
777 lookup_deprec hit pit n
778 = case lookupIface hit pit n of
779 Just iface -> lookupDeprec (mi_deprecs iface) n
780 Nothing -> pprPanic "warnDeprecations:" (ppr n)
782 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
783 printMinimalImports this_mod unqual imps
784 = doptRn Opt_D_dump_minimal_imports `thenRn` \ dump_minimal ->
785 if not dump_minimal then returnRn () else
787 mapRn to_ies (fmToList imps) `thenRn` \ mod_ies ->
788 ioToRnM (do { h <- openFile filename WriteMode ;
789 printForUser h unqual (vcat (map ppr_mod_ie mod_ies))
793 filename = moduleNameUserString (moduleName this_mod) ++ ".imports"
794 ppr_mod_ie (mod_name, ies)
795 | mod_name == pRELUDE_Name
798 = ptext SLIT("import") <+> ppr mod_name <>
799 parens (fsep (punctuate comma (map ppr ies)))
801 to_ies (mod, avail_env) = mapRn to_ie (availEnvElts avail_env) `thenRn` \ ies ->
804 to_ie :: AvailInfo -> RnMG (IE Name)
805 to_ie (Avail n) = returnRn (IEVar n)
806 to_ie (AvailTC n [m]) = ASSERT( n==m )
807 returnRn (IEThingAbs n)
809 = getInterfaceExports n_mod ImportBySystem `thenRn` \ (_, avails_by_module) ->
810 case [xs | (m,as) <- avails_by_module,
814 [xs] | all (`elem` ns) xs -> returnRn (IEThingAll n)
815 | otherwise -> returnRn (IEThingWith n (filter (/= n) ns))
816 other -> pprTrace "to_ie" (ppr n <+> ppr (nameModule n) <+> ppr other) $
819 n_mod = moduleName (nameModule n)
821 rnDump :: [RenamedHsDecl] -- Renamed imported decls
822 -> [RenamedHsDecl] -- Renamed local decls
824 rnDump imp_decls local_decls
825 = doptRn Opt_D_dump_rn_trace `thenRn` \ dump_rn_trace ->
826 doptRn Opt_D_dump_rn_stats `thenRn` \ dump_rn_stats ->
827 doptRn Opt_D_dump_rn `thenRn` \ dump_rn ->
828 getIfacesRn `thenRn` \ ifaces ->
830 ioToRnM (do { dumpIfSet (dump_rn_trace || dump_rn_stats || dump_rn)
832 (getRnStats imp_decls ifaces) ;
834 dumpIfSet dump_rn "Renamer:"
835 (vcat (map ppr (local_decls ++ imp_decls)))
842 %*********************************************************
844 \subsection{Statistics}
846 %*********************************************************
849 getRnStats :: [RenamedHsDecl] -> Ifaces -> SDoc
850 getRnStats imported_decls ifaces
851 = hcat [text "Renamer stats: ", stats]
853 n_mods = length [() | _ <- moduleEnvElts (iPIT ifaces)]
854 -- This is really only right for a one-shot compile
856 (decls_map, n_decls_slurped) = iDecls ifaces
858 n_decls_left = length [decl | (avail, True, (_,decl)) <- nameEnvElts decls_map
859 -- Data, newtype, and class decls are in the decls_fm
860 -- under multiple names; the tycon/class, and each
861 -- constructor/class op too.
862 -- The 'True' selects just the 'main' decl
865 (insts_left, n_insts_slurped) = iInsts ifaces
866 n_insts_left = length (bagToList insts_left)
868 (rules_left, n_rules_slurped) = iRules ifaces
869 n_rules_left = length (bagToList rules_left)
872 [int n_mods <+> text "interfaces read",
873 hsep [ int n_decls_slurped, text "type/class/variable imported, out of",
874 int (n_decls_slurped + n_decls_left), text "read"],
875 hsep [ int n_insts_slurped, text "instance decls imported, out of",
876 int (n_insts_slurped + n_insts_left), text "read"],
877 hsep [ int n_rules_slurped, text "rule decls imported, out of",
878 int (n_rules_slurped + n_rules_left), text "read"]
883 %************************************************************************
885 \subsection{Errors and warnings}
887 %************************************************************************
890 warnDeprec :: (Name, DeprecTxt) -> RnM d ()
891 warnDeprec (name, txt)
892 = pushSrcLocRn (getSrcLoc name) $
894 sep [ text (occNameFlavour (nameOccName name)) <+> ppr name <+>
895 text "is deprecated:", nest 4 (ppr txt) ]
898 dupFixityDecl rdr_name loc1 loc2
899 = vcat [ptext SLIT("Multiple fixity declarations for") <+> quotes (ppr rdr_name),
900 ptext SLIT("at ") <+> ppr loc1,
901 ptext SLIT("and") <+> ppr loc2]
904 = sep [ptext SLIT("Illegal deprecation when whole module is deprecated"),