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, reportDeprecations,
10 mkModDeps, exportsToAvails
13 #include "HsVersions.h"
15 import CmdLineOpts ( DynFlag(..) )
16 import HsSyn ( IE(..), ieName, ImportDecl(..), LImportDecl,
17 ForeignDecl(..), HsGroup(..),
18 collectGroupBinders, tyClDeclNames
21 import IfaceEnv ( lookupOrig, newGlobalBinder )
22 import LoadIface ( loadSrcInterface )
26 import PrelNames ( pRELUDE_Name, isBuiltInSyntaxName, isUnboundName,
28 import Module ( Module, ModuleName, moduleName, mkPackageModule,
29 moduleNameUserString, isHomeModule,
30 unitModuleEnvByName, unitModuleEnv,
31 lookupModuleEnvByName, moduleEnvElts )
32 import Name ( Name, nameSrcLoc, nameOccName, nameModuleName,
33 nameParent, nameParent_maybe, isExternalName, nameModule )
36 import OccName ( srcDataName, isTcOcc, occNameFlavour, OccEnv,
37 mkOccEnv, lookupOccEnv, emptyOccEnv, extendOccEnv )
38 import HscTypes ( GenAvailInfo(..), AvailInfo, Avails, GhciMode(..),
39 IfaceExport, HomePackageTable, PackageIfaceTable,
40 availName, availNames, availsToNameSet, unQualInScope,
41 Deprecs(..), ModIface(..), Dependencies(..), lookupIface,
42 ExternalPackageState(..)
44 import RdrName ( RdrName, rdrNameOcc, setRdrNameSpace,
45 GlobalRdrEnv, mkGlobalRdrEnv, GlobalRdrElt(..),
46 emptyGlobalRdrEnv, plusGlobalRdrEnv, globalRdrEnvElts,
47 unQualOK, lookupGRE_Name,
48 Provenance(..), ImportSpec(..),
49 isLocalGRE, pprNameProvenance )
51 import Maybes ( isJust, isNothing, catMaybes, mapCatMaybes, seqMaybe )
52 import SrcLoc ( noSrcLoc, Located(..), mkGeneralSrcSpan,
53 unLoc, noLoc, srcLocSpan )
54 import BasicTypes ( DeprecTxt )
55 import ListSetOps ( removeDups )
56 import Util ( sortLt, notNull, isSingleton )
57 import List ( partition )
58 import IO ( openFile, IOMode(..) )
63 %************************************************************************
67 %************************************************************************
70 rnImports :: [LImportDecl RdrName]
71 -> RnM (GlobalRdrEnv, ImportAvails)
74 = -- PROCESS IMPORT DECLS
75 -- Do the non {- SOURCE -} ones first, so that we get a helpful
76 -- warning for {- SOURCE -} ones that are unnecessary
77 getModule `thenM` \ this_mod ->
78 doptM Opt_NoImplicitPrelude `thenM` \ opt_no_prelude ->
80 all_imports = mk_prel_imports this_mod opt_no_prelude ++ imports
81 (source, ordinary) = partition is_source_import all_imports
82 is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot
84 get_imports = importsFromImportDecl this_mod
86 mappM get_imports ordinary `thenM` \ stuff1 ->
87 mappM get_imports source `thenM` \ stuff2 ->
91 (imp_gbl_envs, imp_avails) = unzip (stuff1 ++ stuff2)
92 gbl_env :: GlobalRdrEnv
93 gbl_env = foldr plusGlobalRdrEnv emptyGlobalRdrEnv imp_gbl_envs
95 all_avails :: ImportAvails
96 all_avails = foldr plusImportAvails emptyImportAvails imp_avails
99 returnM (gbl_env, all_avails)
101 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
102 -- because the former doesn't even look at Prelude.hi for instance
103 -- declarations, whereas the latter does.
104 mk_prel_imports this_mod no_prelude
105 | moduleName this_mod == pRELUDE_Name
106 || explicit_prelude_import
110 | otherwise = [preludeImportDecl]
112 explicit_prelude_import
113 = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- imports,
114 unLoc mod == pRELUDE_Name ]
118 ImportDecl (L loc pRELUDE_Name)
119 False {- Not a boot interface -}
120 False {- Not qualified -}
121 Nothing {- No "as" -}
122 Nothing {- No import list -}
124 loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")
128 importsFromImportDecl :: Module
129 -> LImportDecl RdrName
130 -> RnM (GlobalRdrEnv, ImportAvails)
132 importsFromImportDecl this_mod
133 (L loc (ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
137 -- If there's an error in loadInterface, (e.g. interface
138 -- file not found) we get lots of spurious errors from 'filterImports'
140 imp_mod_name = unLoc loc_imp_mod_name
141 this_mod_name = moduleName this_mod
142 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
144 loadSrcInterface doc imp_mod_name want_boot `thenM` \ iface ->
146 -- Compiler sanity check: if the import didn't say
147 -- {-# SOURCE #-} we should not get a hi-boot file
148 WARN( not want_boot && mi_boot iface, ppr imp_mod_name )
150 -- Issue a user warning for a redundant {- SOURCE -} import
151 -- NB that we arrange to read all the ordinary imports before
152 -- any of the {- SOURCE -} imports
153 warnIf (want_boot && not (mi_boot iface))
154 (warnRedundantSourceImport imp_mod_name) `thenM_`
157 imp_mod = mi_module iface
158 deprecs = mi_deprecs iface
159 is_orph = mi_orphan iface
162 filtered_exports = filter not_this_mod (mi_exports iface)
163 not_this_mod (mod,_) = mod /= this_mod_name
164 -- If the module exports anything defined in this module, just ignore it.
165 -- Reason: otherwise it looks as if there are two local definition sites
166 -- for the thing, and an error gets reported. Easiest thing is just to
167 -- filter them out up front. This situation only arises if a module
168 -- imports itself, or another module that imported it. (Necessarily,
169 -- this invoves a loop.)
171 -- Tiresome consequence: if you say
176 -- module B( AType ) where
177 -- import {-# SOURCE #-} A( AType )
179 -- then you'll get a 'B does not export AType' message. Oh well.
181 qual_mod_name = case as_mod of
182 Nothing -> imp_mod_name
183 Just another_name -> another_name
184 imp_spec = ImportSpec { is_mod = imp_mod_name, is_qual = qual_only,
185 is_loc = loc, is_as = qual_mod_name }
188 -- Get the total imports, and filter them according to the import list
189 exportsToAvails filtered_exports `thenM` \ total_avails ->
190 filterImports iface imp_spec
191 imp_details total_avails `thenM` \ (avail_env, gbl_env) ->
194 -- Compute new transitive dependencies
196 orphans | is_orph = ASSERT( not (imp_mod_name `elem` dep_orphs deps) )
197 imp_mod_name : dep_orphs deps
198 | otherwise = dep_orphs deps
200 (dependent_mods, dependent_pkgs)
201 | isHomeModule imp_mod
202 = -- Imported module is from the home package
203 -- Take its dependent modules and
204 -- (a) remove this_mod (might be there as a hi-boot)
205 -- (b) add imp_mod itself
206 -- Take its dependent packages unchanged
207 ((imp_mod_name, want_boot) : filter not_self (dep_mods deps), dep_pkgs deps)
210 = -- Imported module is from another package
211 -- Dump the dependent modules
212 -- Add the package imp_mod comes from to the dependent packages
213 ASSERT( not (mi_package iface `elem` dep_pkgs deps) )
214 ([], mi_package iface : dep_pkgs deps)
216 not_self (m, _) = m /= this_mod_name
218 import_all = case imp_details of
219 Just (is_hiding, ls) -- Imports are spec'd explicitly
220 | not is_hiding -> Just (not (null ls))
221 _ -> Nothing -- Everything is imported,
222 -- (or almost everything [hiding])
224 -- unqual_avails is the Avails that are visible in *unqualified* form
225 -- We need to know this so we know what to export when we see
226 -- module M ( module P ) where ...
227 -- Then we must export whatever came from P unqualified.
228 imports = ImportAvails {
229 imp_qual = unitModuleEnvByName qual_mod_name avail_env,
231 imp_mods = unitModuleEnv imp_mod (imp_mod, import_all),
233 imp_dep_mods = mkModDeps dependent_mods,
234 imp_dep_pkgs = dependent_pkgs }
237 -- Complain if we import a deprecated module
238 ifOptM Opt_WarnDeprecations (
240 DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
244 returnM (gbl_env, imports)
246 exportsToAvails :: [IfaceExport] -> TcRnIf gbl lcl Avails
247 exportsToAvails exports
248 = do { avails_by_module <- mappM do_one exports
249 ; return (concat avails_by_module) }
251 do_one (mod_name, exports) = mapM (do_avail mod_name) exports
252 do_avail mod_nm (Avail n) = do { n' <- lookupOrig mod_nm n;
253 ; return (Avail n') }
254 do_avail mod_nm (AvailTC n ns) = do { n' <- lookupOrig mod_nm n
255 ; ns' <- mappM (lookup_sub n') ns
256 ; return (AvailTC n' ns') }
258 mod = mkPackageModule mod_nm -- Not necessarily right yet
259 lookup_sub parent occ = newGlobalBinder mod occ (Just parent) noSrcLoc
260 -- Hack alert! Notice the newGlobalBinder. It ensures that the subordinate
261 -- names record their parent; and that in turn ensures that the GlobalRdrEnv
262 -- has the correct parent for all the names in its range.
263 -- For imported things, we only suck in the binding site later, if ever.
264 -- Reason for all this:
265 -- Suppose module M exports type A.T, and constructor A.MkT
266 -- Then, we know that A.MkT is a subordinate name of A.T,
267 -- even though we aren't at the binding site of A.T
268 -- And it's important, because we may simply re-export A.T
269 -- without ever sucking in the declaration itself.
271 warnRedundantSourceImport mod_name
272 = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
273 <+> quotes (ppr mod_name)
277 %************************************************************************
279 importsFromLocalDecls
281 %************************************************************************
283 From the top-level declarations of this module produce
284 * the lexical environment
286 created by its bindings.
288 Complain about duplicate bindings
291 importsFromLocalDecls :: HsGroup RdrName
292 -> RnM (GlobalRdrEnv, ImportAvails)
293 importsFromLocalDecls group
294 = getModule `thenM` \ this_mod ->
295 getLocalDeclBinders this_mod group `thenM` \ avails ->
296 -- The avails that are returned don't include the "system" names
298 all_names :: [Name] -- All the defns; no dups eliminated
299 all_names = [name | avail <- avails, name <- availNames avail]
302 (_, dups) = removeDups compare all_names
304 -- Check for duplicate definitions
305 -- The complaint will come out as "Multiple declarations of Foo.f" because
306 -- since 'f' is in the env twice, the unQualInScope used by the error-msg
307 -- printer returns False. It seems awkward to fix, unfortunately.
308 mappM_ addDupDeclErr dups `thenM_`
310 doptM Opt_NoImplicitPrelude `thenM` \ implicit_prelude ->
312 mod_name = moduleName this_mod
313 prov = LocalDef mod_name
314 gbl_env = mkGlobalRdrEnv gres
315 gres = [ GRE { gre_name = name, gre_prov = prov}
318 -- Optimisation: filter out names for built-in syntax
319 -- They just clutter up the environment (esp tuples), and the parser
320 -- will generate Exact RdrNames for them, so the cluttered
321 -- envt is no use. To avoid doing this filter all the time,
322 -- we use -fno-implicit-prelude as a clue that the filter is
323 -- worth while. Really, it's only useful for GHC.Base and GHC.Tuple.
325 -- It's worth doing because it makes the environment smaller for
326 -- every module that imports the Prelude
328 -- Note: don't filter the gbl_env (hence avails, not avails' in
329 -- defn of gbl_env above). Stupid reason: when parsing
330 -- data type decls, the constructors start as Exact tycon-names,
331 -- and then get turned into data con names by zapping the name space;
332 -- but that stops them being Exact, so they get looked up.
333 -- Ditto in fixity decls; e.g. infix 5 :
334 -- Sigh. It doesn't matter because it only affects the Data.Tuple really.
335 -- The important thing is to trim down the exports.
337 avails' | implicit_prelude = filter not_built_in_syntax avails
339 not_built_in_syntax a = not (all isBuiltInSyntaxName (availNames a))
340 -- Only filter it if all the names of the avail are built-in
341 -- In particular, lists have (:) which is not built in syntax
342 -- so we don't filter it out. [Sept 03: wrong: see isBuiltInSyntaxName]
344 avail_env = mkAvailEnv avails'
345 imports = emptyImportAvails {
346 imp_qual = unitModuleEnv this_mod avail_env,
350 returnM (gbl_env, imports)
354 %*********************************************************
356 \subsection{Getting binders out of a declaration}
358 %*********************************************************
360 @getLocalDeclBinders@ returns the names for an @HsDecl@. It's
361 used for source code.
363 *** See "THE NAMING STORY" in HsDecls ****
366 getLocalDeclBinders :: Module -> HsGroup RdrName -> RnM [AvailInfo]
367 getLocalDeclBinders mod (HsGroup {hs_valds = val_decls,
368 hs_tyclds = tycl_decls,
369 hs_fords = foreign_decls })
370 = -- For type and class decls, we generate Global names, with
371 -- no export indicator. They need to be global because they get
372 -- permanently bound into the TyCons and Classes. They don't need
373 -- an export indicator because they are all implicitly exported.
375 mappM new_tc tycl_decls `thenM` \ tc_avails ->
376 mappM new_simple (for_hs_bndrs ++ val_hs_bndrs) `thenM` \ simple_avails ->
377 returnM (tc_avails ++ simple_avails)
379 new_simple rdr_name = newTopSrcBinder mod Nothing rdr_name `thenM` \ name ->
382 val_hs_bndrs = collectGroupBinders val_decls
383 for_hs_bndrs = [nm | L _ (ForeignImport nm _ _ _) <- foreign_decls]
386 = newTopSrcBinder mod Nothing main_rdr `thenM` \ main_name ->
387 mappM (newTopSrcBinder mod (Just main_name)) sub_rdrs `thenM` \ sub_names ->
388 returnM (AvailTC main_name (main_name : sub_names))
390 (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
394 %************************************************************************
396 \subsection{Filtering imports}
398 %************************************************************************
400 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
401 available, and filters it through the import spec (if any).
404 filterImports :: ModIface
405 -> ImportSpec -- The span for the entire import decl
406 -> Maybe (Bool, [Located (IE RdrName)]) -- Import spec; True => hiding
407 -> [AvailInfo] -- What's available
408 -> RnM (AvailEnv, -- What's imported (qualified or unqualified)
409 GlobalRdrEnv) -- Same again, but in GRE form
411 -- Complains if import spec mentions things that the module doesn't export
412 -- Warns/informs if import spec contains duplicates.
414 mkGenericRdrEnv imp_spec avails
415 = mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = Imported [imp_spec] False }
416 | avail <- avails, name <- availNames avail ]
418 filterImports iface imp_spec Nothing total_avails
419 = returnM (mkAvailEnv total_avails,
420 mkGenericRdrEnv imp_spec total_avails)
422 filterImports iface imp_spec (Just (want_hiding, import_items)) total_avails
423 = mapAndUnzipM (addLocM get_item) import_items `thenM` \ (avails_s, gres) ->
425 avails = concat avails_s
427 if not want_hiding then
428 return (mkAvailEnv avails,
429 foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres)
432 hidden = availsToNameSet avails
433 keep n = not (n `elemNameSet` hidden)
434 pruned_avails = pruneAvails keep total_avails
436 return (mkAvailEnv pruned_avails,
437 mkGenericRdrEnv imp_spec pruned_avails)
440 import_fm :: OccEnv AvailInfo
441 import_fm = mkOccEnv [ (nameOccName name, avail)
442 | avail <- total_avails,
443 name <- availNames avail]
444 -- Even though availNames returns data constructors too,
445 -- they won't make any difference because naked entities like T
446 -- in an import list map to TcOccs, not VarOccs.
448 bale_out item = addErr (badImportItemErr iface imp_spec item) `thenM_`
449 returnM ([], emptyGlobalRdrEnv)
451 succeed_with :: Bool -> AvailInfo -> RnM ([AvailInfo], GlobalRdrEnv)
452 succeed_with all_explicit avail
453 = do { loc <- getSrcSpanM
455 mkGlobalRdrEnv (map (mk_gre loc) (availNames avail))) }
457 mk_gre loc name = GRE { gre_name = name,
458 gre_prov = Imported [this_imp_spec loc] (explicit name) }
459 this_imp_spec loc = imp_spec { is_loc = loc }
460 explicit name = all_explicit || name == main_name
461 main_name = availName avail
463 get_item :: IE RdrName -> RnM ([AvailInfo], GlobalRdrEnv)
464 -- Empty result for a bad item.
465 -- Singleton result is typical case.
466 -- Can have two when we are hiding, and mention C which might be
467 -- both a class and a data constructor.
468 get_item item@(IEModuleContents _)
471 get_item item@(IEThingAll tc)
472 = case check_item item of
473 Nothing -> bale_out item
474 Just avail@(AvailTC _ [n]) -> -- This occurs when you import T(..), but
475 -- only export T abstractly. The single [n]
476 -- in the AvailTC is the type or class itself
477 ifOptM Opt_WarnMisc (addWarn (dodgyImportWarn tc)) `thenM_`
478 succeed_with False avail
479 Just avail -> succeed_with False avail
481 get_item item@(IEThingAbs n)
482 | want_hiding -- hiding( C )
483 -- Here the 'C' can be a data constructor
484 -- *or* a type/class, or even both
485 = case catMaybes [check_item item, check_item (IEVar data_n)] of
487 avails -> returnM (avails, emptyGlobalRdrEnv)
488 -- The GlobalRdrEnv result is irrelevant when hiding
490 data_n = setRdrNameSpace n srcDataName
493 = case check_item item of
494 Nothing -> bale_out item
495 Just avail -> succeed_with True avail
498 | isNothing maybe_in_import_avails ||
499 isNothing maybe_filtered_avail
503 = Just filtered_avail
506 wanted_occ = rdrNameOcc (ieName item)
507 maybe_in_import_avails = lookupOccEnv import_fm wanted_occ
509 Just avail = maybe_in_import_avails
510 maybe_filtered_avail = filterAvail item avail
511 Just filtered_avail = maybe_filtered_avail
515 filterAvail :: IE RdrName -- Wanted
516 -> AvailInfo -- Available
517 -> Maybe AvailInfo -- Resulting available;
518 -- Nothing if (any of the) wanted stuff isn't there
520 filterAvail ie@(IEThingWith want wants) avail@(AvailTC n ns)
521 | sub_names_ok = Just (AvailTC n (filter is_wanted ns))
522 | otherwise = Nothing
524 is_wanted name = nameOccName name `elem` wanted_occs
525 sub_names_ok = all (`elem` avail_occs) wanted_occs
526 avail_occs = map nameOccName ns
527 wanted_occs = map rdrNameOcc (want:wants)
529 filterAvail (IEThingAbs _) (AvailTC n ns) = ASSERT( n `elem` ns )
532 filterAvail (IEThingAbs _) avail@(Avail n) = Just avail -- Type synonyms
534 filterAvail (IEVar _) avail@(Avail n) = Just avail
535 filterAvail (IEVar v) avail@(AvailTC n ns) = Just (AvailTC n (filter wanted ns))
537 wanted n = nameOccName n == occ
539 -- The second equation happens if we import a class op, thus
541 -- where op is a class operation
543 filterAvail (IEThingAll _) avail@(AvailTC _ _) = Just avail
544 -- We don't complain even if the IE says T(..), but
545 -- no constrs/class ops of T are available
546 -- Instead that's caught with a warning by the caller
548 filterAvail ie avail = Nothing
552 %************************************************************************
554 \subsection{Export list processing}
556 %************************************************************************
558 Processing the export list.
560 You might think that we should record things that appear in the export
561 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
562 wrong. We do check (here) that they are in scope, but there is no
563 need to slurp in their actual declaration (which is what
564 @addOccurrenceName@ forces).
566 Indeed, doing so would big trouble when compiling @PrelBase@, because
567 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
568 @ConcBase.StateAndSynchVar#@, and so on...
571 type ExportAccum -- The type of the accumulating parameter of
572 -- the main worker function in exportsFromAvail
573 = ([ModuleName], -- 'module M's seen so far
574 ExportOccMap, -- Tracks exported occurrence names
575 NameSet) -- The accumulated exported stuff
576 emptyExportAccum = ([], emptyOccEnv, emptyNameSet)
578 type ExportOccMap = OccEnv (Name, IE RdrName)
579 -- Tracks what a particular exported OccName
580 -- in an export list refers to, and which item
581 -- it came from. It's illegal to export two distinct things
582 -- that have the same occurrence name
585 exportsFromAvail :: Bool -- False => no 'module M(..) where' header at all
586 -> Maybe [Located (IE RdrName)] -- Nothing => no explicit export list
588 -- Complains if two distinct exports have same OccName
589 -- Warns about identical exports.
590 -- Complains about exports items not in scope
592 exportsFromAvail explicit_mod exports
593 = do { TcGblEnv { tcg_rdr_env = rdr_env,
594 tcg_imports = imports } <- getGblEnv ;
596 -- If the module header is omitted altogether, then behave
597 -- as if the user had written "module Main(main) where..."
598 -- EXCEPT in interactive mode, when we behave as if he had
599 -- written "module Main where ..."
600 -- Reason: don't want to complain about 'main' not in scope
601 -- in interactive mode
602 ghci_mode <- getGhciMode ;
604 | explicit_mod = exports
605 | ghci_mode == Interactive = Nothing
606 | otherwise = Just [noLoc (IEVar main_RDR_Unqual)] } ;
607 exports_from_avail real_exports rdr_env imports }
610 exports_from_avail Nothing rdr_env imports
611 = -- Export all locally-defined things
612 -- We do this by filtering the global RdrEnv,
613 -- keeping only things that are locally-defined
614 return (mkNameSet [ gre_name gre
615 | gre <- globalRdrEnvElts rdr_env,
618 exports_from_avail (Just export_items) rdr_env
619 (ImportAvails { imp_qual = mod_avail_env,
620 imp_env = entity_avail_env })
621 = foldlM (exports_from_litem) emptyExportAccum
622 export_items `thenM` \ (_, _, exports) ->
626 exports_from_litem :: ExportAccum -> Located (IE RdrName) -> RnM ExportAccum
627 exports_from_litem acc = addLocM (exports_from_item acc)
629 exports_from_item :: ExportAccum -> IE RdrName -> RnM ExportAccum
630 exports_from_item acc@(mods, occs, exports) ie@(IEModuleContents mod)
631 | mod `elem` mods -- Duplicate export of M
632 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
633 warnIf warn_dup_exports (dupModuleExport mod) ;
637 = case lookupModuleEnvByName mod_avail_env mod of
638 Nothing -> addErr (modExportErr mod) `thenM_`
643 new_exports = [ name | avail <- availEnvElts avail_env,
644 name <- availNames avail,
645 inScopeUnqual rdr_env name ]
648 -- This check_occs not only finds conflicts between this item
649 -- and others, but also internally within this item. That is,
650 -- if 'M.x' is in scope in several ways, we'll have several
651 -- members of mod_avails with the same OccName.
652 check_occs ie occs new_exports `thenM` \ occs' ->
653 returnM (mod:mods, occs', addListToNameSet exports new_exports)
655 exports_from_item acc@(mods, occs, exports) ie
656 = lookupGlobalOccRn (ieName ie) `thenM` \ name ->
657 if isUnboundName name then
658 returnM acc -- Avoid error cascade
660 -- Get the AvailInfo for the parent of the specified name
662 parent = nameParent name
663 avail = lookupAvailEnv entity_avail_env parent
665 -- Filter out the bits we want
666 case filterAvail ie avail of {
667 Nothing -> -- Not enough availability
668 addErr (exportItemErr ie) `thenM_`
673 -- Phew! It's OK! Now to check the occurrence stuff!
676 new_exports = availNames export_avail
678 checkForDodgyExport ie new_exports `thenM_`
679 check_occs ie occs new_exports `thenM` \ occs' ->
680 returnM (mods, occs', addListToNameSet exports new_exports)
684 -------------------------------
685 inScopeUnqual :: GlobalRdrEnv -> Name -> Bool
686 -- Checks whether the Name is in scope unqualified,
687 -- regardless of whether it's ambiguous or not
688 inScopeUnqual env n = any unQualOK (lookupGRE_Name env n)
690 -------------------------------
691 checkForDodgyExport :: IE RdrName -> [Name] -> RnM ()
692 checkForDodgyExport (IEThingAll tc) [n] = addWarn (dodgyExportWarn tc)
693 -- This occurs when you import T(..), but
694 -- only export T abstractly. The single [n]
695 -- in the AvailTC is the type or class itself
696 checkForDodgyExport _ _ = return ()
698 -------------------------------
699 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
700 check_occs ie occs names
701 = foldlM check occs names
704 = case lookupOccEnv occs name_occ of
705 Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
708 | name == name' -- Duplicate export
709 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
710 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
713 | otherwise -- Same occ name but different names: an error
714 -> do { global_env <- getGlobalRdrEnv ;
715 addErr (exportClashErr global_env name name' ie ie') ;
718 name_occ = nameOccName name
721 %*********************************************************
725 %*********************************************************
728 reportDeprecations :: TcGblEnv -> RnM ()
729 reportDeprecations tcg_env
730 = ifOptM Opt_WarnDeprecations $
733 ; mapM_ (check hpt (eps_PIT eps)) all_gres }
735 used_names = findUses (tcg_dus tcg_env) emptyNameSet
736 all_gres = globalRdrEnvElts (tcg_rdr_env tcg_env)
738 check hpt pit (GRE {gre_name = name, gre_prov = Imported (imp_spec:_) _})
739 | name `elemNameSet` used_names
740 , Just deprec_txt <- lookupDeprec hpt pit name
741 = addSrcSpan (is_loc imp_spec) $
742 addWarn (sep [ptext SLIT("Deprecated use of") <+>
743 text (occNameFlavour (nameOccName name)) <+>
748 name_mod = nameModuleName name
749 imp_mod = is_mod imp_spec
750 imp_msg = ptext SLIT("imported from") <+> ppr imp_mod <> extra
751 extra | imp_mod == name_mod = empty
752 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
754 check hpt pit ok_gre = returnM () -- Local, or not used, or not deprectated
755 -- The Imported pattern-match: don't deprecate locally defined names
756 -- For a start, we may be exporting a deprecated thing
757 -- Also we may use a deprecated thing in the defn of another
758 -- deprecated things. We may even use a deprecated thing in
759 -- the defn of a non-deprecated thing, when changing a module's
762 lookupDeprec :: HomePackageTable -> PackageIfaceTable
763 -> Name -> Maybe DeprecTxt
764 lookupDeprec hpt pit n
765 = case lookupIface hpt pit (nameModule n) of
766 Just iface -> mi_dep_fn iface n `seqMaybe` -- Bleat if the thing, *or
767 mi_dep_fn iface (nameParent n) -- its parent*, is deprec'd
768 Nothing -> pprPanic "lookupDeprec" (ppr n)
769 -- By now all the interfaces should have been loaded
771 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
772 gre_is_used used_names gre = gre_name gre `elemNameSet` used_names
775 %*********************************************************
779 %*********************************************************
782 reportUnusedNames :: TcGblEnv -> RnM ()
783 reportUnusedNames gbl_env
784 = do { warnUnusedTopBinds unused_locals
785 ; warnUnusedModules unused_imp_mods
786 ; warnUnusedImports unused_imports
787 ; warnDuplicateImports dup_imps
788 ; printMinimalImports minimal_imports }
790 used_names, all_used_names :: NameSet
791 used_names = findUses (tcg_dus gbl_env) emptyNameSet
792 all_used_names = used_names `unionNameSets`
793 mkNameSet (mapCatMaybes nameParent_maybe (nameSetToList used_names))
794 -- A use of C implies a use of T,
795 -- if C was brought into scope by T(..) or T(C)
797 -- Collect the defined names from the in-scope environment
798 defined_names :: [GlobalRdrElt]
799 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
801 -- Note that defined_and_used, defined_but_not_used
802 -- are both [GRE]; that's why we need defined_and_used
803 -- rather than just all_used_names
804 defined_and_used, defined_but_not_used :: [GlobalRdrElt]
805 (defined_and_used, defined_but_not_used)
806 = partition (gre_is_used all_used_names) defined_names
808 -- Find the duplicate imports
809 dup_imps = filter is_dup defined_and_used
810 is_dup (GRE {gre_prov = Imported imp_spec True}) = not (isSingleton imp_spec)
813 -- Filter out the ones that are
814 -- (a) defined in this module, and
815 -- (b) not defined by a 'deriving' clause
816 -- The latter have an Internal Name, so we can filter them out easily
817 unused_locals :: [GlobalRdrElt]
818 unused_locals = filter is_unused_local defined_but_not_used
819 is_unused_local :: GlobalRdrElt -> Bool
820 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
822 unused_imports :: [GlobalRdrElt]
823 unused_imports = filter unused_imp defined_but_not_used
824 unused_imp (GRE {gre_prov = Imported imp_specs True})
825 = not (all (module_unused . is_mod) imp_specs)
826 -- Don't complain about unused imports if we've already said the
827 -- entire import is unused
828 unused_imp other = False
830 -- To figure out the minimal set of imports, start with the things
831 -- that are in scope (i.e. in gbl_env). Then just combine them
832 -- into a bunch of avails, so they are properly grouped
833 minimal_imports :: FiniteMap ModuleName AvailEnv
834 minimal_imports0 = emptyFM
835 minimal_imports1 = foldr add_name minimal_imports0 defined_and_used
836 minimal_imports = foldr add_inst_mod minimal_imports1 direct_import_mods
837 -- The last line makes sure that we retain all direct imports
838 -- even if we import nothing explicitly.
839 -- It's not necessarily redundant to import such modules. Consider
843 -- The import M() is not *necessarily* redundant, even if
844 -- we suck in no instance decls from M (e.g. it contains
845 -- no instance decls, or This contains no code). It may be
846 -- that we import M solely to ensure that M's orphan instance
847 -- decls (or those in its imports) are visible to people who
848 -- import This. Sigh.
849 -- There's really no good way to detect this, so the error message
850 -- in RnEnv.warnUnusedModules is weakened instead
852 -- We've carefully preserved the provenance so that we can
853 -- construct minimal imports that import the name by (one of)
854 -- the same route(s) as the programmer originally did.
855 add_name (GRE {gre_name = n,
856 gre_prov = Imported imp_specs _}) acc
857 = addToFM_C plusAvailEnv acc (is_mod (head imp_specs))
858 (unitAvailEnv (mk_avail n (nameParent_maybe n)))
862 -- n is the name of the thing, p is the name of its parent
863 mk_avail n (Just p) = AvailTC p [p,n]
864 mk_avail n Nothing | isTcOcc (nameOccName n) = AvailTC n [n]
865 | otherwise = Avail n
868 | m `elemFM` acc = acc -- We import something already
869 | otherwise = addToFM acc m emptyAvailEnv
870 -- Add an empty collection of imports for a module
871 -- from which we have sucked only instance decls
873 imports = tcg_imports gbl_env
875 direct_import_mods :: [ModuleName]
876 direct_import_mods = map (moduleName . fst)
877 (moduleEnvElts (imp_mods imports))
879 hasEmptyImpList :: ModuleName -> Bool
881 case lookupModuleEnvByName (imp_mods imports) m of
882 Just (_,Just x) -> not x
885 -- unused_imp_mods are the directly-imported modules
886 -- that are not mentioned in minimal_imports1
887 -- [Note: not 'minimal_imports', because that includes directly-imported
888 -- modules even if we use nothing from them; see notes above]
889 unused_imp_mods = [m | m <- direct_import_mods,
890 isNothing (lookupFM minimal_imports1 m),
892 not (hasEmptyImpList m)]
893 -- hasEmptyImpList arranges not to complain about
894 -- import M (), which is an idiom for importing
895 -- instance declarations
897 module_unused :: ModuleName -> Bool
898 module_unused mod = mod `elem` unused_imp_mods
900 ---------------------
901 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
902 warnDuplicateImports gres
903 = ifOptM Opt_WarnUnusedImports (mapM_ warn gres)
905 warn (GRE { gre_name = name, gre_prov = Imported imps _ })
906 = addWarn ((quotes (ppr name) <+> ptext SLIT("is imported more than once:"))
907 $$ nest 2 (vcat (map ppr imps)))
910 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
911 printMinimalImports :: FiniteMap ModuleName AvailEnv -- Minimal imports
913 printMinimalImports imps
914 = ifOptM Opt_D_dump_minimal_imports $ do {
916 mod_ies <- mappM to_ies (fmToList imps) ;
917 this_mod <- getModule ;
918 rdr_env <- getGlobalRdrEnv ;
919 ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
920 printForUser h (unQualInScope rdr_env)
921 (vcat (map ppr_mod_ie mod_ies)) })
924 mkFilename this_mod = moduleNameUserString (moduleName this_mod) ++ ".imports"
925 ppr_mod_ie (mod_name, ies)
926 | mod_name == pRELUDE_Name
928 | null ies -- Nothing except instances comes from here
929 = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("() -- Instances only")
931 = ptext SLIT("import") <+> ppr mod_name <>
932 parens (fsep (punctuate comma (map ppr ies)))
934 to_ies (mod, avail_env) = mappM to_ie (availEnvElts avail_env) `thenM` \ ies ->
937 to_ie :: AvailInfo -> RnM (IE Name)
938 -- The main trick here is that if we're importing all the constructors
939 -- we want to say "T(..)", but if we're importing only a subset we want
940 -- to say "T(A,B,C)". So we have to find out what the module exports.
941 to_ie (Avail n) = returnM (IEVar n)
942 to_ie (AvailTC n [m]) = ASSERT( n==m )
943 returnM (IEThingAbs n)
945 = loadSrcInterface doc n_mod False `thenM` \ iface ->
946 case [xs | (m,as) <- mi_exports iface,
949 x == nameOccName n] of
950 [xs] | all_used xs -> returnM (IEThingAll n)
951 | otherwise -> returnM (IEThingWith n (filter (/= n) ns))
952 other -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
955 all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
956 doc = text "Compute minimal imports from" <+> ppr n
957 n_mod = nameModuleName n
961 %************************************************************************
965 %************************************************************************
968 badImportItemErr iface imp_spec ie
969 = sep [ptext SLIT("Module"), quotes (ppr (is_mod imp_spec)), source_import,
970 ptext SLIT("does not export"), quotes (ppr ie)]
972 source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
975 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
976 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
979 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
980 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
981 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
984 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
986 exportItemErr export_item
987 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
988 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
990 exportClashErr global_env name1 name2 ie1 ie2
991 = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
992 , ppr_export ie1 name1
993 , ppr_export ie2 name2 ]
995 occ = nameOccName name1
996 ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+>
997 quotes (ppr name) <+> pprNameProvenance (get_gre name))
999 -- get_gre finds a GRE for the Name, so that we can show its provenance
1001 = case lookupGRE_Name global_env name of
1003 [] -> pprPanic "exportClashErr" (ppr name)
1005 addDupDeclErr :: [Name] -> TcRn ()
1006 addDupDeclErr (n:ns)
1007 = addErrAt (srcLocSpan (nameSrcLoc n)) $
1008 vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
1009 nest 2 (ptext SLIT("other declarations at:")),
1010 nest 4 (vcat (map ppr sorted_locs))]
1012 sorted_locs = sortLt occ'ed_before (map nameSrcLoc ns)
1013 occ'ed_before a b = LT == compare a b
1015 dupExportWarn occ_name ie1 ie2
1016 = hsep [quotes (ppr occ_name),
1017 ptext SLIT("is exported by"), quotes (ppr ie1),
1018 ptext SLIT("and"), quotes (ppr ie2)]
1021 = hsep [ptext SLIT("Duplicate"),
1022 quotes (ptext SLIT("Module") <+> ppr mod),
1023 ptext SLIT("in export list")]
1025 moduleDeprec mod txt
1026 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),