2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnNames]{Extracting imported and top-level names in scope}
8 rnImports, importsFromLocalDecls, exportsFromAvail,
9 reportUnusedNames, mkModDeps
12 #include "HsVersions.h"
14 import {-# SOURCE #-} RnHiFiles ( loadInterface )
16 import CmdLineOpts ( DynFlag(..) )
18 import HsSyn ( IE(..), ieName, ImportDecl(..),
19 ForeignDecl(..), HsGroup(..),
20 collectLocatedHsBinders, tyClDeclNames
22 import RdrHsSyn ( RdrNameIE, RdrNameImportDecl, main_RDR_Unqual )
27 import PrelNames ( pRELUDE_Name, isBuiltInSyntaxName )
28 import Module ( Module, ModuleName, ModuleEnv, moduleName,
29 moduleNameUserString, isHomeModule,
30 emptyModuleEnv, unitModuleEnvByName, unitModuleEnv,
31 lookupModuleEnvByName, extendModuleEnvByName, moduleEnvElts )
32 import Name ( Name, nameSrcLoc, nameOccName, nameModule, isExternalName )
35 import OccName ( OccName, srcDataName, isTcOcc )
36 import HscTypes ( Provenance(..), ImportReason(..), GlobalRdrEnv,
37 GenAvailInfo(..), AvailInfo, Avails, GhciMode(..),
39 availName, availNames, availsToNameSet,
40 Deprecations(..), ModIface(..), Dependencies(..),
41 GlobalRdrElt(..), unQualInScope, isLocalGRE, pprNameProvenance
43 import RdrName ( RdrName, rdrNameOcc, setRdrNameSpace, lookupRdrEnv, rdrEnvToList,
44 emptyRdrEnv, foldRdrEnv, rdrEnvElts, mkRdrUnqual, isQual )
46 import Maybe ( isJust, isNothing, catMaybes )
47 import Maybes ( orElse )
48 import ListSetOps ( removeDups )
49 import Util ( sortLt, notNull )
50 import List ( partition, insert )
51 import IO ( openFile, IOMode(..) )
56 %************************************************************************
60 %************************************************************************
63 rnImports :: [RdrNameImportDecl]
64 -> TcRn m (GlobalRdrEnv, ImportAvails)
67 = -- PROCESS IMPORT DECLS
68 -- Do the non {- SOURCE -} ones first, so that we get a helpful
69 -- warning for {- SOURCE -} ones that are unnecessary
70 getModule `thenM` \ this_mod ->
71 getSrcLocM `thenM` \ loc ->
72 doptM Opt_NoImplicitPrelude `thenM` \ opt_no_prelude ->
74 all_imports = mk_prel_imports this_mod loc opt_no_prelude ++ imports
75 (source, ordinary) = partition is_source_import all_imports
76 is_source_import (ImportDecl _ is_boot _ _ _ _) = is_boot
78 get_imports = importsFromImportDecl this_mod
80 mappM get_imports ordinary `thenM` \ stuff1 ->
81 mappM get_imports source `thenM` \ stuff2 ->
85 (imp_gbl_envs, imp_avails) = unzip (stuff1 ++ stuff2)
86 gbl_env :: GlobalRdrEnv
87 gbl_env = foldr plusGlobalRdrEnv emptyRdrEnv imp_gbl_envs
89 all_avails :: ImportAvails
90 all_avails = foldr plusImportAvails emptyImportAvails imp_avails
93 returnM (gbl_env, all_avails)
95 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
96 -- because the former doesn't even look at Prelude.hi for instance
97 -- declarations, whereas the latter does.
98 mk_prel_imports this_mod loc no_prelude
99 | moduleName this_mod == pRELUDE_Name
100 || explicit_prelude_import
104 | otherwise = [preludeImportDecl loc]
106 explicit_prelude_import
107 = notNull [ () | (ImportDecl mod _ _ _ _ _) <- imports,
108 mod == pRELUDE_Name ]
110 preludeImportDecl loc
111 = ImportDecl pRELUDE_Name
112 False {- Not a boot interface -}
113 False {- Not qualified -}
114 Nothing {- No "as" -}
115 Nothing {- No import list -}
120 importsFromImportDecl :: Module
122 -> TcRn m (GlobalRdrEnv, ImportAvails)
124 importsFromImportDecl this_mod
125 (ImportDecl imp_mod_name is_boot qual_only as_mod imp_spec iloc)
128 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
131 -- If there's an error in loadInterface, (e.g. interface
132 -- file not found) we get lots of spurious errors from 'filterImports'
133 tryM (loadInterface doc imp_mod_name (ImportByUser is_boot)) `thenM` \ mb_iface ->
136 Left exn -> returnM (emptyRdrEnv, emptyImportAvails ) ;
140 imp_mod = mi_module iface
141 avails_by_module = mi_exports iface
142 deprecs = mi_deprecs iface
143 is_orph = mi_orphan iface
147 avails = [ avail | (mod_name, avails) <- avails_by_module,
148 mod_name /= this_mod_name,
150 this_mod_name = moduleName this_mod
151 -- If the module exports anything defined in this module, just ignore it.
152 -- Reason: otherwise it looks as if there are two local definition sites
153 -- for the thing, and an error gets reported. Easiest thing is just to
154 -- filter them out up front. This situation only arises if a module
155 -- imports itself, or another module that imported it. (Necessarily,
156 -- this invoves a loop.)
158 -- Tiresome consequence: if you say
163 -- module B( AType ) where
164 -- import {-# SOURCE #-} A( AType )
166 -- then you'll get a 'B does not export AType' message. Oh well.
169 -- Filter the imports according to the import list
170 filterImports imp_mod is_boot imp_spec avails `thenM` \ (filtered_avails, explicits) ->
173 -- Compute new transitive dependencies
174 orphans | is_orph = insert imp_mod_name (dep_orphs deps)
175 | otherwise = dep_orphs deps
177 (dependent_mods, dependent_pkgs)
178 | isHomeModule imp_mod
179 = -- Imported module is from the home package
180 -- Take its dependent modules and
181 -- (a) remove this_mod (might be there as a hi-boot)
182 -- (b) add imp_mod itself
183 -- Take its dependent packages unchanged
184 ((imp_mod_name, is_boot) : filter not_self (dep_mods deps), dep_pkgs deps)
187 = -- Imported module is from another package
188 -- Dump the dependent modules
189 -- Add the package imp_mod comes from to the dependent packages
191 ([], insert (mi_package iface) (dep_pkgs deps))
193 not_self (m, _) = m /= this_mod_name
195 import_all = case imp_spec of
196 Just (isHid, ls) -- Imports are spec'd explicitly
197 | not isHid -> Just (not (null ls))
198 _ -> Nothing -- Everything is imported,
199 -- (or almost everything [hiding])
201 qual_mod_name = case as_mod of
202 Nothing -> imp_mod_name
203 Just another_name -> another_name
205 -- unqual_avails is the Avails that are visible in *unqualified* form
206 -- We need to know this so we know what to export when we see
207 -- module M ( module P ) where ...
208 -- Then we must export whatever came from P unqualified.
209 avail_env = mkAvailEnv filtered_avails
211 mk_prov name = NonLocalDef (UserImport imp_mod iloc (name `elemNameSet` explicits))
212 gbl_env = mkGlobalRdrEnv qual_mod_name (not qual_only)
213 mk_prov filtered_avails deprecs
214 imports = ImportAvails {
215 imp_qual = unitModuleEnvByName qual_mod_name avail_env,
217 imp_mods = unitModuleEnv imp_mod (imp_mod, import_all),
219 imp_dep_mods = mkModDeps dependent_mods,
220 imp_dep_pkgs = dependent_pkgs }
223 -- Complain if we import a deprecated module
224 ifOptM Opt_WarnDeprecations (
226 DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
230 returnM (gbl_env, imports)
233 mkModDeps :: [(ModuleName, IsBootInterface)]
234 -> ModuleEnv (ModuleName, IsBootInterface)
235 mkModDeps deps = foldl add emptyModuleEnv deps
237 add env elt@(m,_) = extendModuleEnvByName env m elt
241 %************************************************************************
243 importsFromLocalDecls
245 %************************************************************************
247 From the top-level declarations of this module produce
248 * the lexical environment
250 created by its bindings.
252 Complain about duplicate bindings
255 importsFromLocalDecls :: HsGroup RdrName
256 -> TcRn m (GlobalRdrEnv, ImportAvails)
257 importsFromLocalDecls group
258 = getModule `thenM` \ this_mod ->
259 getLocalDeclBinders this_mod group `thenM` \ avails ->
260 -- The avails that are returned don't include the "system" names
262 all_names :: [Name] -- All the defns; no dups eliminated
263 all_names = [name | avail <- avails, name <- availNames avail]
266 (_, dups) = removeDups compare all_names
268 -- Check for duplicate definitions
269 -- The complaint will come out as "Multiple declarations of Foo.f" because
270 -- since 'f' is in the env twice, the unQualInScope used by the error-msg
271 -- printer returns False. It seems awkward to fix, unfortunately.
272 mappM_ (addErr . dupDeclErr) dups `thenM_`
274 doptM Opt_NoImplicitPrelude `thenM` \ implicit_prelude ->
276 mod_name = moduleName this_mod
277 mk_prov n = LocalDef -- Provenance is local
279 unqual_imp = True -- Want unqualified names in scope
280 gbl_env = mkGlobalRdrEnv mod_name unqual_imp mk_prov avails NoDeprecs
281 -- NoDeprecs: don't complain about locally defined names
282 -- For a start, we may be exporting a deprecated thing
283 -- Also we may use a deprecated thing in the defn of another
284 -- deprecated things. We may even use a deprecated thing in
285 -- the defn of a non-deprecated thing, when changing a module's
289 -- Optimisation: filter out names for built-in syntax
290 -- They just clutter up the environment (esp tuples), and the parser
291 -- will generate Exact RdrNames for them, so the cluttered
292 -- envt is no use. To avoid doing this filter all the time,
293 -- we use -fno-implicit-prelude as a clue that the filter is
294 -- worth while. Really, it's only useful for GHC.Base and GHC.Tuple.
296 -- It's worth doing because it makes the environment smaller for
297 -- every module that imports the Prelude
299 -- Note: don't filter the gbl_env (hence avails, not avails' in
300 -- defn of gbl_env above). Stupid reason: when parsing
301 -- data type decls, the constructors start as Exact tycon-names,
302 -- and then get turned into data con names by zapping the name space;
303 -- but that stops them being Exact, so they get looked up. Sigh.
304 -- It doesn't matter because it only affects the Data.Tuple really.
305 -- The important thing is to trim down the exports.
307 avails' | implicit_prelude = filter not_built_in_syntax avails
309 not_built_in_syntax a = not (all isBuiltInSyntaxName (availNames a))
310 -- Only filter it if all the names of the avail are built-in
311 -- In particular, lists have (:) which is not built in syntax
312 -- so we don't filter it out.
314 avail_env = mkAvailEnv avails'
315 imports = emptyImportAvails {
316 imp_qual = unitModuleEnv this_mod avail_env,
320 returnM (gbl_env, imports)
324 %*********************************************************
326 \subsection{Getting binders out of a declaration}
328 %*********************************************************
330 @getLocalDeclBinders@ returns the names for a @RdrNameHsDecl@. It's
331 used for both source code (from @importsFromLocalDecls@) and interface
332 files (@loadDecl@ calls @getTyClDeclBinders@).
334 *** See "THE NAMING STORY" in HsDecls ****
337 getLocalDeclBinders :: Module -> HsGroup RdrName -> TcRn m [AvailInfo]
338 getLocalDeclBinders mod (HsGroup {hs_valds = val_decls,
339 hs_tyclds = tycl_decls,
340 hs_fords = foreign_decls })
341 = -- For type and class decls, we generate Global names, with
342 -- no export indicator. They need to be global because they get
343 -- permanently bound into the TyCons and Classes. They don't need
344 -- an export indicator because they are all implicitly exported.
346 mappM new_tc tycl_decls `thenM` \ tc_avails ->
347 mappM new_bndr (for_hs_bndrs ++ val_hs_bndrs) `thenM` \ simple_bndrs ->
349 returnM (tc_avails ++ map Avail simple_bndrs)
351 new_bndr (rdr_name,loc) = newTopBinder mod rdr_name loc
353 val_hs_bndrs = collectLocatedHsBinders val_decls
354 for_hs_bndrs = [(nm,loc) | ForeignImport nm _ _ _ loc <- foreign_decls]
356 new_tc tc_decl = mappM new_bndr (tyClDeclNames tc_decl) `thenM` \ names@(main_name:_) ->
357 returnM (AvailTC main_name names)
361 %************************************************************************
363 \subsection{Filtering imports}
365 %************************************************************************
367 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
368 available, and filters it through the import spec (if any).
371 filterImports :: Module -- The module being imported
372 -> IsBootInterface -- Tells whether it's a {-# SOURCE #-} import
373 -> Maybe (Bool, [RdrNameIE]) -- Import spec; True => hiding
374 -> [AvailInfo] -- What's available
375 -> TcRn m ([AvailInfo], -- What's imported
376 NameSet) -- What was imported explicitly
378 -- Complains if import spec mentions things that the module doesn't export
379 -- Warns/informs if import spec contains duplicates.
380 filterImports mod from Nothing imports
381 = returnM (imports, emptyNameSet)
383 filterImports mod from (Just (want_hiding, import_items)) total_avails
384 = mappM get_item import_items `thenM` \ avails_w_explicits_s ->
386 (item_avails, explicits_s) = unzip (concat avails_w_explicits_s)
387 explicits = foldl addListToNameSet emptyNameSet explicits_s
390 let -- All imported; item_avails to be hidden
391 hidden = availsToNameSet item_avails
392 keep n = not (n `elemNameSet` hidden)
394 returnM (pruneAvails keep total_avails, emptyNameSet)
396 -- Just item_avails imported; nothing to be hidden
397 returnM (item_avails, explicits)
399 import_fm :: FiniteMap OccName AvailInfo
400 import_fm = listToFM [ (nameOccName name, avail)
401 | avail <- total_avails,
402 name <- availNames avail]
403 -- Even though availNames returns data constructors too,
404 -- they won't make any difference because naked entities like T
405 -- in an import list map to TcOccs, not VarOccs.
407 bale_out item = addErr (badImportItemErr mod from item) `thenM_`
410 get_item :: RdrNameIE -> TcRn m [(AvailInfo, [Name])]
411 -- Empty list for a bad item.
412 -- Singleton is typical case.
413 -- Can have two when we are hiding, and mention C which might be
414 -- both a class and a data constructor.
415 -- The [Name] is the list of explicitly-mentioned names
416 get_item item@(IEModuleContents _) = bale_out item
418 get_item item@(IEThingAll _)
419 = case check_item item of
420 Nothing -> bale_out item
421 Just avail@(AvailTC _ [n]) -> -- This occurs when you import T(..), but
422 -- only export T abstractly. The single [n]
423 -- in the AvailTC is the type or class itself
424 ifOptM Opt_WarnMisc (addWarn (dodgyImportWarn mod item)) `thenM_`
425 returnM [(avail, [availName avail])]
426 Just avail -> returnM [(avail, [availName avail])]
428 get_item item@(IEThingAbs n)
429 | want_hiding -- hiding( C )
430 -- Here the 'C' can be a data constructor *or* a type/class
431 = case catMaybes [check_item item, check_item (IEVar data_n)] of
433 avails -> returnM [(a, []) | a <- avails]
434 -- The 'explicits' list is irrelevant when hiding
436 data_n = setRdrNameSpace n srcDataName
439 = case check_item item of
440 Nothing -> bale_out item
441 Just avail -> returnM [(avail, availNames avail)]
444 | isNothing maybe_in_import_avails ||
445 isNothing maybe_filtered_avail
449 = Just filtered_avail
452 wanted_occ = rdrNameOcc (ieName item)
453 maybe_in_import_avails = lookupFM import_fm wanted_occ
455 Just avail = maybe_in_import_avails
456 maybe_filtered_avail = filterAvail item avail
457 Just filtered_avail = maybe_filtered_avail
461 filterAvail :: RdrNameIE -- Wanted
462 -> AvailInfo -- Available
463 -> Maybe AvailInfo -- Resulting available;
464 -- Nothing if (any of the) wanted stuff isn't there
466 filterAvail ie@(IEThingWith want wants) avail@(AvailTC n ns)
467 | sub_names_ok = Just (AvailTC n (filter is_wanted ns))
468 | otherwise = Nothing
470 is_wanted name = nameOccName name `elem` wanted_occs
471 sub_names_ok = all (`elem` avail_occs) wanted_occs
472 avail_occs = map nameOccName ns
473 wanted_occs = map rdrNameOcc (want:wants)
475 filterAvail (IEThingAbs _) (AvailTC n ns) = ASSERT( n `elem` ns )
478 filterAvail (IEThingAbs _) avail@(Avail n) = Just avail -- Type synonyms
480 filterAvail (IEVar _) avail@(Avail n) = Just avail
481 filterAvail (IEVar v) avail@(AvailTC n ns) = Just (AvailTC n (filter wanted ns))
483 wanted n = nameOccName n == occ
485 -- The second equation happens if we import a class op, thus
487 -- where op is a class operation
489 filterAvail (IEThingAll _) avail@(AvailTC _ _) = Just avail
490 -- We don't complain even if the IE says T(..), but
491 -- no constrs/class ops of T are available
492 -- Instead that's caught with a warning by the caller
494 filterAvail ie avail = Nothing
498 %************************************************************************
500 \subsection{Export list processing}
502 %************************************************************************
504 Processing the export list.
506 You might think that we should record things that appear in the export
507 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
508 wrong. We do check (here) that they are in scope, but there is no
509 need to slurp in their actual declaration (which is what
510 @addOccurrenceName@ forces).
512 Indeed, doing so would big trouble when compiling @PrelBase@, because
513 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
514 @ConcBase.StateAndSynchVar#@, and so on...
517 type ExportAccum -- The type of the accumulating parameter of
518 -- the main worker function in exportsFromAvail
519 = ([ModuleName], -- 'module M's seen so far
520 ExportOccMap, -- Tracks exported occurrence names
521 AvailEnv) -- The accumulated exported stuff, kept in an env
522 -- so we can common-up related AvailInfos
523 emptyExportAccum = ([], emptyFM, emptyAvailEnv)
525 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
526 -- Tracks what a particular exported OccName
527 -- in an export list refers to, and which item
528 -- it came from. It's illegal to export two distinct things
529 -- that have the same occurrence name
532 exportsFromAvail :: Maybe Module -- Nothing => no 'module M(..) where' header at all
533 -> Maybe [RdrNameIE] -- Nothing => no explicit export list
535 -- Complains if two distinct exports have same OccName
536 -- Warns about identical exports.
537 -- Complains about exports items not in scope
539 exportsFromAvail maybe_mod exports
540 = do { TcGblEnv { tcg_rdr_env = rdr_env,
541 tcg_imports = imports } <- getGblEnv ;
543 -- If the module header is omitted altogether, then behave
544 -- as if the user had written "module Main(main) where..."
545 -- EXCEPT in interactive mode, when we behave as if he had
546 -- written "module Main where ..."
547 -- Reason: don't want to complain about 'main' not in scope
548 -- in interactive mode
549 ghci_mode <- getGhciMode ;
553 Nothing | ghci_mode == Interactive -> Nothing
554 | otherwise -> Just [IEVar main_RDR_Unqual] } ;
556 exports_from_avail exports rdr_env imports }
558 exports_from_avail Nothing rdr_env
559 imports@(ImportAvails { imp_env = entity_avail_env })
560 = -- Export all locally-defined things
561 -- We do this by filtering the global RdrEnv,
562 -- keeping only things that are (a) qualified,
563 -- (b) locally defined, (c) a 'main' name
564 -- Then we look up in the entity-avail-env
565 return [ lookupAvailEnv entity_avail_env name
566 | (rdr_name, gres) <- rdrEnvToList rdr_env,
567 isQual rdr_name, -- Avoid duplicates
568 GRE { gre_name = name,
569 gre_parent = Nothing, -- Main things only
570 gre_prov = LocalDef } <- gres
573 exports_from_avail (Just export_items) rdr_env
574 (ImportAvails { imp_qual = mod_avail_env,
575 imp_env = entity_avail_env })
576 = foldlM exports_from_item emptyExportAccum
577 export_items `thenM` \ (_, _, export_avail_map) ->
578 returnM (nameEnvElts export_avail_map)
581 exports_from_item :: ExportAccum -> RdrNameIE -> TcRn m ExportAccum
583 exports_from_item acc@(mods, occs, avails) ie@(IEModuleContents mod)
584 | mod `elem` mods -- Duplicate export of M
585 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
586 warnIf warn_dup_exports (dupModuleExport mod) ;
590 = case lookupModuleEnvByName mod_avail_env mod of
591 Nothing -> addErr (modExportErr mod) `thenM_`
596 mod_avails = [ filtered_avail
597 | avail <- availEnvElts avail_env,
598 let mb_avail = filter_unqual rdr_env avail,
600 let Just filtered_avail = mb_avail]
602 avails' = foldl addAvail avails mod_avails
604 -- This check_occs not only finds conflicts between this item
605 -- and others, but also internally within this item. That is,
606 -- if 'M.x' is in scope in several ways, we'll have several
607 -- members of mod_avails with the same OccName.
609 foldlM (check_occs ie) occs mod_avails `thenM` \ occs' ->
610 returnM (mod:mods, occs', avails')
612 exports_from_item acc@(mods, occs, avails) ie
613 = lookupGRE (ieName ie) `thenM` \ mb_gre ->
615 Nothing -> addErr (unknownNameErr (ieName ie)) `thenM_`
619 -- Get the AvailInfo for the parent of the specified name
621 parent = gre_parent gre `orElse` gre_name gre
622 avail = lookupAvailEnv entity_avail_env parent
624 -- Filter out the bits we want
625 case filterAvail ie avail of {
626 Nothing -> -- Not enough availability
627 addErr (exportItemErr ie) `thenM_`
632 -- Phew! It's OK! Now to check the occurrence stuff!
633 warnIf (not (ok_item ie avail)) (dodgyExportWarn ie) `thenM_`
634 check_occs ie occs export_avail `thenM` \ occs' ->
635 returnM (mods, occs', addAvail avails export_avail)
639 -------------------------------
640 filter_unqual :: GlobalRdrEnv -> AvailInfo -> Maybe AvailInfo
641 -- Filter the Avail by what's in scope unqualified
642 filter_unqual env (Avail n)
643 | in_scope env n = Just (Avail n)
644 | otherwise = Nothing
645 filter_unqual env (AvailTC n ns)
646 | not (null ns') = Just (AvailTC n ns')
647 | otherwise = Nothing
649 ns' = filter (in_scope env) ns
651 in_scope :: GlobalRdrEnv -> Name -> Bool
652 -- Checks whether the Name is in scope unqualified,
653 -- regardless of whether it's ambiguous or not
655 = case lookupRdrEnv env (mkRdrUnqual (nameOccName n)) of
657 Just gres -> or [n == gre_name g | g <- gres]
660 -------------------------------
661 ok_item (IEThingAll _) (AvailTC _ [n]) = False
662 -- This occurs when you import T(..), but
663 -- only export T abstractly. The single [n]
664 -- in the AvailTC is the type or class itself
667 -------------------------------
668 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> TcRn m ExportOccMap
669 check_occs ie occs avail
670 = foldlM check occs (availNames avail)
673 = case lookupFM occs name_occ of
674 Nothing -> returnM (addToFM occs name_occ (name, ie))
677 | name == name' -- Duplicate export
678 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
679 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
682 | otherwise -- Same occ name but different names: an error
683 -> do { global_env <- getGlobalRdrEnv ;
684 addErr (exportClashErr global_env name name' ie ie') ;
687 name_occ = nameOccName name
690 %*********************************************************
692 \subsection{Unused names}
694 %*********************************************************
697 reportUnusedNames :: TcGblEnv -> DefUses -> TcRn m ()
698 reportUnusedNames gbl_env dus
699 = warnUnusedModules unused_imp_mods `thenM_`
700 warnUnusedTopBinds bad_locals `thenM_`
701 warnUnusedImports bad_imports `thenM_`
702 printMinimalImports minimal_imports
704 used_names :: NameSet
705 used_names = findUses dus emptyNameSet
707 -- Collect the defined names from the in-scope environment
708 -- Look for the qualified ones only, else get duplicates
709 defined_names :: [GlobalRdrElt]
710 defined_names = foldRdrEnv add [] (tcg_rdr_env gbl_env)
711 add rdr_name ns acc | isQual rdr_name = ns ++ acc
714 defined_and_used, defined_but_not_used :: [GlobalRdrElt]
715 (defined_and_used, defined_but_not_used) = partition is_used defined_names
717 is_used gre = n `elemNameSet` used_names || any (`elemNameSet` used_names) kids
718 -- The 'kids' part is because a use of C implies a use of T,
719 -- if C was brought into scope by T(..) or T(C)
722 kids = case lookupAvailEnv_maybe avail_env n of
723 Just (AvailTC n ns) -> ns
724 other -> [] -- Ids, class ops and datacons
725 -- (The latter two give Nothing)
727 -- Filter out the ones that are
728 -- (a) defined in this module, and
729 -- (b) not defined by a 'deriving' clause
730 -- The latter have an Internal Name, so we can filter them out easily
731 bad_locals :: [GlobalRdrElt]
732 bad_locals = filter is_bad defined_but_not_used
733 is_bad :: GlobalRdrElt -> Bool
734 is_bad gre = isLocalGRE gre && isExternalName (gre_name gre)
736 bad_imports :: [GlobalRdrElt]
737 bad_imports = filter bad_imp defined_but_not_used
738 bad_imp (GRE {gre_prov = NonLocalDef (UserImport mod _ True)}) = not (module_unused mod)
739 bad_imp other = False
741 -- To figure out the minimal set of imports, start with the things
742 -- that are in scope (i.e. in gbl_env). Then just combine them
743 -- into a bunch of avails, so they are properly grouped
744 minimal_imports :: FiniteMap ModuleName AvailEnv
745 minimal_imports0 = emptyFM
746 minimal_imports1 = foldr add_name minimal_imports0 defined_and_used
747 minimal_imports = foldr add_inst_mod minimal_imports1 direct_import_mods
748 -- The last line makes sure that we retain all direct imports
749 -- even if we import nothing explicitly.
750 -- It's not necessarily redundant to import such modules. Consider
754 -- The import M() is not *necessarily* redundant, even if
755 -- we suck in no instance decls from M (e.g. it contains
756 -- no instance decls, or This contains no code). It may be
757 -- that we import M solely to ensure that M's orphan instance
758 -- decls (or those in its imports) are visible to people who
759 -- import This. Sigh.
760 -- There's really no good way to detect this, so the error message
761 -- in RnEnv.warnUnusedModules is weakened instead
764 -- We've carefully preserved the provenance so that we can
765 -- construct minimal imports that import the name by (one of)
766 -- the same route(s) as the programmer originally did.
767 add_name (GRE {gre_name = n, gre_parent = p,
768 gre_prov = NonLocalDef (UserImport m _ _)}) acc
769 = addToFM_C plusAvailEnv acc (moduleName m)
770 (unitAvailEnv (mk_avail n p))
774 -- n is the name of the thing, p is the name of its parent
775 mk_avail n (Just p) = AvailTC p [p,n]
776 mk_avail n Nothing | isTcOcc (nameOccName n) = AvailTC n [n]
777 | otherwise = Avail n
780 | m `elemFM` acc = acc -- We import something already
781 | otherwise = addToFM acc m emptyAvailEnv
782 -- Add an empty collection of imports for a module
783 -- from which we have sucked only instance decls
785 imports = tcg_imports gbl_env
786 avail_env = imp_env imports
788 direct_import_mods :: [ModuleName]
789 direct_import_mods = map (moduleName . fst)
790 (moduleEnvElts (imp_mods imports))
792 hasEmptyImpList :: ModuleName -> Bool
794 case lookupModuleEnvByName (imp_mods imports) m of
795 Just (_,Just x) -> not x
798 -- unused_imp_mods are the directly-imported modules
799 -- that are not mentioned in minimal_imports1
800 -- [Note: not 'minimal_imports', because that includes direcly-imported
801 -- modules even if we use nothing from them; see notes above]
802 unused_imp_mods = [m | m <- direct_import_mods,
803 isNothing (lookupFM minimal_imports1 m),
805 not (hasEmptyImpList m)]
807 module_unused :: Module -> Bool
808 module_unused mod = moduleName mod `elem` unused_imp_mods
811 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
812 printMinimalImports :: FiniteMap ModuleName AvailEnv -- Minimal imports
814 printMinimalImports imps
815 = ifOptM Opt_D_dump_minimal_imports $ do {
817 mod_ies <- mappM to_ies (fmToList imps) ;
818 this_mod <- getModule ;
819 rdr_env <- getGlobalRdrEnv ;
820 ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
821 printForUser h (unQualInScope rdr_env)
822 (vcat (map ppr_mod_ie mod_ies)) })
825 mkFilename this_mod = moduleNameUserString (moduleName this_mod) ++ ".imports"
826 ppr_mod_ie (mod_name, ies)
827 | mod_name == pRELUDE_Name
829 | null ies -- Nothing except instances comes from here
830 = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("() -- Instances only")
832 = ptext SLIT("import") <+> ppr mod_name <>
833 parens (fsep (punctuate comma (map ppr ies)))
835 to_ies (mod, avail_env) = mappM to_ie (availEnvElts avail_env) `thenM` \ ies ->
838 to_ie :: AvailInfo -> TcRn m (IE Name)
839 -- The main trick here is that if we're importing all the constructors
840 -- we want to say "T(..)", but if we're importing only a subset we want
841 -- to say "T(A,B,C)". So we have to find out what the module exports.
842 to_ie (Avail n) = returnM (IEVar n)
843 to_ie (AvailTC n [m]) = ASSERT( n==m )
844 returnM (IEThingAbs n)
846 = loadInterface (text "Compute minimal imports from" <+> ppr n_mod)
847 n_mod ImportBySystem `thenM` \ iface ->
848 case [xs | (m,as) <- mi_exports iface,
852 [xs] | all (`elem` ns) xs -> returnM (IEThingAll n)
853 | otherwise -> returnM (IEThingWith n (filter (/= n) ns))
854 other -> pprTrace "to_ie" (ppr n <+> ppr (nameModule n) <+> ppr other) $
857 n_mod = moduleName (nameModule n)
861 %************************************************************************
865 %************************************************************************
868 badImportItemErr mod from ie
869 = sep [ptext SLIT("Module"), quotes (ppr mod), source_import,
870 ptext SLIT("does not export"), quotes (ppr ie)]
872 source_import = case from of
873 True -> ptext SLIT("(hi-boot interface)")
876 dodgyImportWarn mod item = dodgyMsg (ptext SLIT("import")) item
877 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
879 dodgyMsg kind item@(IEThingAll tc)
880 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr item),
881 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
882 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
885 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
887 exportItemErr export_item
888 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
889 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
891 exportClashErr global_env name1 name2 ie1 ie2
892 = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
893 , ppr_export ie1 name1
894 , ppr_export ie2 name2 ]
896 occ = nameOccName name1
897 ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+>
898 quotes (ppr name) <+> pprNameProvenance (get_gre name))
900 -- get_gre finds a GRE for the Name, in a very inefficient way
901 -- There isn't a more efficient way to do it, because we don't necessarily
902 -- know the RdrName under which this Name is in scope. So we just
903 -- search linearly. Shouldn't matter because this only happens
904 -- in an error message.
906 = case [gre | gres <- rdrEnvElts global_env,
908 gre_name gre == name] of
910 [] -> pprPanic "exportClashErr" (ppr name)
913 = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
914 nest 4 (vcat (map ppr sorted_locs))]
916 sorted_locs = sortLt occ'ed_before (map nameSrcLoc (n:ns))
917 occ'ed_before a b = LT == compare a b
919 dupExportWarn occ_name ie1 ie2
920 = hsep [quotes (ppr occ_name),
921 ptext SLIT("is exported by"), quotes (ppr ie1),
922 ptext SLIT("and"), quotes (ppr ie2)]
925 = hsep [ptext SLIT("Duplicate"),
926 quotes (ptext SLIT("Module") <+> ppr mod),
927 ptext SLIT("in export list")]
930 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),