2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnNames]{Extracting imported and top-level names in scope}
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
15 rnImports, importsFromLocalDecls,
17 getLocalDeclBinders, extendRdrEnvRn,
18 reportUnusedNames, finishDeprecations,
21 #include "HsVersions.h"
24 import HsSyn ( IE(..), ieName, ImportDecl(..), LImportDecl,
25 ForeignDecl(..), HsGroup(..), HsValBindsLR(..),
26 Sig(..), collectHsBindLocatedBinders, tyClDeclNames,
27 instDeclATs, isFamInstDecl,
30 import RnHsDoc ( rnHsDoc )
31 import IfaceEnv ( ifaceExportNames )
32 import LoadIface ( loadSrcInterface, loadSysInterface )
33 import TcRnMonad hiding (LIE)
49 import BasicTypes ( DeprecTxt, Fixity )
50 import DriverPhases ( isHsBoot )
53 import Data.List ( partition, concatMap, (\\), delete )
54 import IO ( openFile, IOMode(..) )
60 %************************************************************************
64 %************************************************************************
67 rnImports :: [LImportDecl RdrName]
68 -> RnM ([LImportDecl Name], GlobalRdrEnv, ImportAvails,AnyHpcUsage)
71 -- PROCESS IMPORT DECLS
72 -- Do the non {- SOURCE -} ones first, so that we get a helpful
73 -- warning for {- SOURCE -} ones that are unnecessary
74 = do this_mod <- getModule
75 implicit_prelude <- doptM Opt_ImplicitPrelude
76 let prel_imports = mkPrelImports this_mod implicit_prelude imports
77 (source, ordinary) = partition is_source_import imports
78 is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot
80 ifOptM Opt_WarnImplicitPrelude (
81 when (notNull prel_imports) $ addWarn (implicitPreludeWarn)
84 stuff1 <- mapM (rnImportDecl this_mod) (prel_imports ++ ordinary)
85 stuff2 <- mapM (rnImportDecl this_mod) source
86 let (decls, rdr_env, imp_avails,hpc_usage) = combine (stuff1 ++ stuff2)
87 return (decls, rdr_env, imp_avails,hpc_usage)
90 combine :: [(LImportDecl Name, GlobalRdrEnv, ImportAvails,AnyHpcUsage)]
91 -> ([LImportDecl Name], GlobalRdrEnv, ImportAvails,AnyHpcUsage)
92 combine = foldr plus ([], emptyGlobalRdrEnv, emptyImportAvails,False)
93 where plus (decl, gbl_env1, imp_avails1,hpc_usage1)
94 (decls, gbl_env2, imp_avails2,hpc_usage2)
96 gbl_env1 `plusGlobalRdrEnv` gbl_env2,
97 imp_avails1 `plusImportAvails` imp_avails2,
98 hpc_usage1 || hpc_usage2)
100 mkPrelImports :: Module -> Bool -> [LImportDecl RdrName] -> [LImportDecl RdrName]
101 -- Consruct the implicit declaration "import Prelude" (or not)
103 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
104 -- because the former doesn't even look at Prelude.hi for instance
105 -- declarations, whereas the latter does.
106 mkPrelImports this_mod implicit_prelude import_decls
107 | this_mod == pRELUDE
108 || explicit_prelude_import
109 || not implicit_prelude
111 | otherwise = [preludeImportDecl]
113 explicit_prelude_import
114 = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- import_decls,
115 unLoc mod == pRELUDE_NAME ]
117 preludeImportDecl :: LImportDecl RdrName
120 ImportDecl (L loc pRELUDE_NAME)
121 False {- Not a boot interface -}
122 False {- Not qualified -}
123 Nothing {- No "as" -}
124 Nothing {- No import list -}
126 loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")
129 rnImportDecl :: Module
130 -> LImportDecl RdrName
131 -> RnM (LImportDecl Name, GlobalRdrEnv, ImportAvails,AnyHpcUsage)
133 rnImportDecl this_mod (L loc (ImportDecl loc_imp_mod_name want_boot
134 qual_only as_mod imp_details))
138 -- If there's an error in loadInterface, (e.g. interface
139 -- file not found) we get lots of spurious errors from 'filterImports'
141 imp_mod_name = unLoc loc_imp_mod_name
142 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
144 iface <- loadSrcInterface doc imp_mod_name want_boot
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 ) (do
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)
157 imp_mod = mi_module iface
158 deprecs = mi_deprecs iface
159 orph_iface = mi_orphan iface
160 has_finsts = mi_finsts iface
163 filtered_exports = filter not_this_mod (mi_exports iface)
164 not_this_mod (mod,_) = mod /= this_mod
165 -- If the module exports anything defined in this module, just
166 -- ignore it. Reason: otherwise it looks as if there are two
167 -- local definition sites for the thing, and an error gets
168 -- reported. Easiest thing is just to filter them out up
169 -- front. This situation only arises if a module imports
170 -- itself, or another module that imported it. (Necessarily,
171 -- this invoves a loop.)
173 -- Tiresome consequence: if you say
178 -- module B( AType ) where
179 -- import {-# SOURCE #-} A( AType )
181 -- then you'll get a 'B does not export AType' message. Oh well.
183 qual_mod_name = case as_mod of
184 Nothing -> imp_mod_name
185 Just another_name -> another_name
186 imp_spec = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,
187 is_dloc = loc, is_as = qual_mod_name }
190 -- Get the total exports from this module
191 total_avails <- ifaceExportNames filtered_exports
193 -- filter the imports according to the import declaration
194 (new_imp_details, gbl_env) <-
195 filterImports iface imp_spec imp_details total_avails
200 -- Compute new transitive dependencies
202 orphans | orph_iface = ASSERT( not (imp_mod `elem` dep_orphs deps) )
203 imp_mod : dep_orphs deps
204 | otherwise = dep_orphs deps
206 finsts | has_finsts = ASSERT( not (imp_mod `elem` dep_finsts deps) )
207 imp_mod : dep_finsts deps
208 | otherwise = dep_finsts deps
210 pkg = modulePackageId (mi_module iface)
212 (dependent_mods, dependent_pkgs)
213 | pkg == thisPackage dflags =
214 -- Imported module is from the home package
215 -- Take its dependent modules and add imp_mod itself
216 -- Take its dependent packages unchanged
218 -- NB: (dep_mods deps) might include a hi-boot file
219 -- for the module being compiled, CM. Do *not* filter
220 -- this out (as we used to), because when we've
221 -- finished dealing with the direct imports we want to
222 -- know if any of them depended on CM.hi-boot, in
223 -- which case we should do the hi-boot consistency
224 -- check. See LoadIface.loadHiBootInterface
225 ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)
228 -- Imported module is from another package
229 -- Dump the dependent modules
230 -- Add the package imp_mod comes from to the dependent packages
231 ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
232 ([], pkg : dep_pkgs deps)
234 -- True <=> import M ()
235 import_all = case imp_details of
236 Just (is_hiding, ls) -> not is_hiding && null ls
239 imports = ImportAvails {
240 imp_mods = unitModuleEnv imp_mod (imp_mod, [(qual_mod_name, import_all, loc)]),
243 imp_dep_mods = mkModDeps dependent_mods,
244 imp_dep_pkgs = dependent_pkgs
247 -- Complain if we import a deprecated module
248 ifOptM Opt_WarnDeprecations (
250 DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
254 let new_imp_decl = L loc (ImportDecl loc_imp_mod_name want_boot
255 qual_only as_mod new_imp_details)
257 returnM (new_imp_decl, gbl_env, imports, mi_hpc iface)
260 warnRedundantSourceImport mod_name
261 = ptext SLIT("Unnecessary {-# SOURCE #-} in the import of module")
262 <+> quotes (ppr mod_name)
266 %************************************************************************
268 importsFromLocalDecls
270 %************************************************************************
272 From the top-level declarations of this module produce
273 * the lexical environment
275 created by its bindings.
278 -- Bool determines shadowing:
279 -- true: names in the group should shadow other UnQuals
280 -- with the same OccName (used in Template Haskell)
281 -- false: duplicates should be reported as an error
283 -- The UniqFM (OccName -> FixItem) associates a Name's OccName's
284 -- FastString with a fixity declaration (that needs the actual OccName
285 -- to be plugged in). This fixity must be brought into scope when such
287 importsFromLocalDecls :: Bool -> HsGroup RdrName -> UniqFM (Located Fixity) -> RnM TcGblEnv
288 importsFromLocalDecls shadowP group fixities
289 = do { gbl_env <- getGblEnv
291 ; avails <- getLocalDeclBinders gbl_env group
293 ; (rdr_env', fix_env') <- extendRdrEnvRn shadowP (tcg_rdr_env gbl_env,
297 ; traceRn (text "local avails: " <> ppr avails)
299 ; returnM (gbl_env { tcg_rdr_env = rdr_env',
300 tcg_fix_env = fix_env'})
303 -- Bool determines shadowing as in importsFromLocalDecls.
304 -- UniqFM FixItem is the same as in importsFromLocalDecls.
306 -- Add the new locally-bound names one by one, checking for duplicates as
307 -- we do so. Remember that in Template Haskell the duplicates
308 -- might *already be* in the GlobalRdrEnv from higher up the module.
310 -- Also update the FixityEnv with the fixities for the names brought into scope.
312 -- Note that the return values are the extensions of the two inputs,
313 -- not the extras relative to them.
314 extendRdrEnvRn :: Bool -> (GlobalRdrEnv, NameEnv FixItem)
315 -> [AvailInfo] -> UniqFM (Located Fixity) -> RnM (GlobalRdrEnv, NameEnv FixItem)
316 extendRdrEnvRn shadowP (rdr_env, fix_env) avails fixities =
317 let -- if there is a fixity decl for the gre,
318 -- add it to the fixity env
319 extendFixEnv env gre =
320 let name = gre_name gre
321 occ = nameOccName name
322 curKey = occNameFS occ in
323 case lookupUFM fixities curKey of
325 Just (L _ fi) -> extendNameEnv env name (FixItem occ fi)
327 (rdr_env_to_extend, extender) =
329 then -- when shadowing is on,
330 -- (1) we need to remove the existing Unquals for the
331 -- names we're extending the env with
332 -- (2) but extending the env is simple
333 let names = concatMap availNames avails
334 new_occs = map nameOccName names
335 trimmed_rdr_env = hideSomeUnquals rdr_env new_occs
338 \(cur_rdr_env, cur_fix_env) -> \gre ->
339 return (extendGlobalRdrEnv cur_rdr_env gre,
340 extendFixEnv cur_fix_env gre))
341 else -- when shadowing is off,
342 -- (1) we don't munge the incoming env
343 -- (2) but we need to check for dups when extending
345 \(cur_rdr_env, cur_fix_env) -> \gre ->
346 let gres = lookupGlobalRdrEnv cur_rdr_env (nameOccName (gre_name gre))
347 in case filter isLocalGRE gres of -- Check for existing *local* defns
348 dup_gre:_ -> do { addDupDeclErr (gre_name dup_gre) (gre_name gre)
349 ; return (cur_rdr_env, cur_fix_env) }
350 [] -> return (extendGlobalRdrEnv cur_rdr_env gre,
351 extendFixEnv cur_fix_env gre))
352 in foldlM extender (rdr_env_to_extend, fix_env) (gresFromAvails LocalDef avails)
355 @getLocalDeclBinders@ returns the names for an @HsDecl@. It's
356 used for source code.
358 *** See "THE NAMING STORY" in HsDecls ****
360 Instances of type families
361 ~~~~~~~~~~~~~~~~~~~~~~~~~~
362 Indexed data/newtype instances contain data constructors that we need to
363 collect, too. Moreover, we need to descend into the data/newtypes instances
364 of associated families.
366 We need to be careful with the handling of the type constructor of each type
367 instance as the family constructor is already defined, and we want to avoid
368 raising a duplicate declaration error. So, we make a new name for it, but
369 don't return it in the 'AvailInfo'.
372 -- Note: this function does NOT get the binders of the ValBinds that
373 -- will be bound during renaming
374 getLocalDeclBinders :: TcGblEnv -> HsGroup RdrName -> RnM [AvailInfo]
375 getLocalDeclBinders gbl_env (HsGroup {hs_valds = ValBindsIn val_decls val_sigs,
376 hs_tyclds = tycl_decls,
377 hs_instds = inst_decls,
378 hs_fords = foreign_decls })
379 = do { tc_names_s <- mappM new_tc tycl_decls
380 ; at_names_s <- mappM inst_ats inst_decls
381 ; val_names <- mappM new_simple val_bndrs
382 ; return (val_names ++ tc_names_s ++ concat at_names_s) }
384 mod = tcg_mod gbl_env
385 is_hs_boot = isHsBoot (tcg_src gbl_env) ;
387 for_hs_bndrs = [nm | L _ (ForeignImport nm _ _) <- foreign_decls]
389 -- In a hs-boot file, the value binders come from the
390 -- *signatures*, and there should be no foreign binders
391 val_bndrs | is_hs_boot = [nm | L _ (TypeSig nm _) <- val_sigs]
392 | otherwise = for_hs_bndrs
394 new_simple rdr_name = do
395 nm <- newTopSrcBinder mod rdr_name
399 | isFamInstDecl (unLoc tc_decl)
400 = do { main_name <- lookupFamInstDeclBndr mod main_rdr
401 ; sub_names <- mappM (newTopSrcBinder mod) sub_rdrs
402 ; return (AvailTC main_name sub_names) }
403 -- main_name is not bound here!
405 = do { main_name <- newTopSrcBinder mod main_rdr
406 ; sub_names <- mappM (newTopSrcBinder mod) sub_rdrs
407 ; return (AvailTC main_name (main_name : sub_names)) }
409 (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
412 = mappM new_tc (instDeclATs (unLoc inst_decl))
414 getLocalDeclBinders _ _ = panic "getLocalDeclBinders" -- ValBindsOut can't happen
418 %************************************************************************
420 \subsection{Filtering imports}
422 %************************************************************************
424 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
425 available, and filters it through the import spec (if any).
428 filterImports :: ModIface
429 -> ImpDeclSpec -- The span for the entire import decl
430 -> Maybe (Bool, [LIE RdrName]) -- Import spec; True => hiding
431 -> [AvailInfo] -- What's available
432 -> RnM (Maybe (Bool, [LIE Name]), -- Import spec w/ Names
433 GlobalRdrEnv) -- Same again, but in GRE form
435 filterImports iface decl_spec Nothing all_avails
436 = return (Nothing, mkGlobalRdrEnv (gresFromAvails prov all_avails))
438 prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
441 filterImports iface decl_spec (Just (want_hiding, import_items)) all_avails
442 = do -- check for errors, convert RdrNames to Names
443 opt_typeFamilies <- doptM Opt_TypeFamilies
444 items1 <- mapM (lookup_lie opt_typeFamilies) import_items
446 let items2 :: [(LIE Name, AvailInfo)]
447 items2 = concat items1
448 -- NB the AvailInfo may have duplicates, and several items
449 -- for the same parent; e.g N(x) and N(y)
451 names = availsToNameSet (map snd items2)
452 keep n = not (n `elemNameSet` names)
453 pruned_avails = filterAvails keep all_avails
454 hiding_prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
456 gres | want_hiding = gresFromAvails hiding_prov pruned_avails
457 | otherwise = concatMap (gresFromIE decl_spec) items2
459 return (Just (want_hiding, map fst items2), mkGlobalRdrEnv gres)
461 -- This environment is how we map names mentioned in the import
462 -- list to the actual Name they correspond to, and the name family
463 -- that the Name belongs to (the AvailInfo). The situation is
464 -- complicated by associated families, which introduce a three-level
465 -- hierachy, where class = grand parent, assoc family = parent, and
466 -- data constructors = children. The occ_env entries for associated
467 -- families needs to capture all this information; hence, we have the
468 -- third component of the environment that gives the class name (=
469 -- grand parent) in case of associated families.
471 -- This env will have entries for data constructors too,
472 -- they won't make any difference because naked entities like T
473 -- in an import list map to TcOccs, not VarOccs.
474 occ_env :: OccEnv (Name, -- the name
475 AvailInfo, -- the export item providing the name
476 Maybe Name) -- the parent of associated types
477 occ_env = mkOccEnv_C combine [ (nameOccName n, (n, a, Nothing))
478 | a <- all_avails, n <- availNames a]
480 -- we know that (1) there are at most entries for one name, (2) their
481 -- first component is identical, (3) they are for tys/cls, and (4) one
482 -- entry has the name in its parent position (the other doesn't)
483 combine (name, AvailTC p1 subs1, Nothing)
484 (_ , AvailTC p2 subs2, Nothing)
486 (parent, subs) = if p1 == name then (p2, subs1) else (p1, subs2)
488 (name, AvailTC name subs, Just parent)
490 lookup_lie :: Bool -> LIE RdrName -> TcRn [(LIE Name, AvailInfo)]
491 lookup_lie opt_typeFamilies (L loc ieRdr)
493 stuff <- setSrcSpan loc $
494 case lookup_ie opt_typeFamilies ieRdr of
495 Failed err -> addErr err >> return []
496 Succeeded a -> return a
497 checkDodgyImport stuff
498 return [ (L loc ie, avail) | (ie,avail) <- stuff ]
500 -- Warn when importing T(..) if T was exported abstractly
501 checkDodgyImport stuff
502 | IEThingAll n <- ieRdr, (_, AvailTC _ [one]):_ <- stuff
503 = ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn n))
504 -- NB. use the RdrName for reporting the warning
508 -- For each import item, we convert its RdrNames to Names,
509 -- and at the same time construct an AvailInfo corresponding
510 -- to what is actually imported by this item.
511 -- Returns Nothing on error.
512 -- We return a list here, because in the case of an import
513 -- item like C, if we are hiding, then C refers to *both* a
514 -- type/class and a data constructor. Moreover, when we import
515 -- data constructors of an associated family, we need separate
516 -- AvailInfos for the data constructors and the family (as they have
517 -- different parents). See the discussion at occ_env.
518 lookup_ie :: Bool -> IE RdrName -> MaybeErr Message [(IE Name,AvailInfo)]
519 lookup_ie opt_typeFamilies ie
520 = let bad_ie = Failed (badImportItemErr iface decl_spec ie)
522 lookup_name rdrName =
523 case lookupOccEnv occ_env (rdrNameOcc rdrName) of
529 (name, avail, _) <- lookup_name n
530 return [(IEVar name, trimAvail avail name)]
533 (name, avail@(AvailTC name2 subs), mb_parent) <- lookup_name tc
535 -- non-associated ty/cls
536 Nothing -> return [(IEThingAll name, avail)]
538 Just parent -> return [(IEThingAll name,
539 AvailTC name2 (subs \\ [name])),
540 (IEThingAll name, AvailTC parent [name])]
543 | want_hiding -- hiding ( C )
544 -- Here the 'C' can be a data constructor
545 -- *or* a type/class, or even both
546 -> let tc_name = lookup_name tc
547 dc_name = lookup_name (setRdrNameSpace tc srcDataName)
549 case catMaybeErr [ tc_name, dc_name ] of
551 names -> return [mkIEThingAbs name | name <- names]
553 -> do nameAvail <- lookup_name tc
554 return [mkIEThingAbs nameAvail]
556 IEThingWith tc ns -> do
557 (name, AvailTC name2 subnames, mb_parent) <- lookup_name tc
559 env = mkOccEnv [(nameOccName s, s) | s <- subnames]
560 mb_children = map (lookupOccEnv env . rdrNameOcc) ns
561 children <- if any isNothing mb_children
563 else return (catMaybes mb_children)
564 -- check for proper import of type families
565 when (not opt_typeFamilies && any isTyConName children) $
566 Failed (typeItemErr (head . filter isTyConName $ children)
567 (text "in import list"))
569 -- non-associated ty/cls
570 Nothing -> return [(IEThingWith name children,
571 AvailTC name (name:children))]
573 Just parent -> return [(IEThingWith name children,
574 AvailTC name children),
575 (IEThingWith name children,
576 AvailTC parent [name])]
578 _other -> Failed illegalImportItemErr
579 -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed
583 mkIEThingAbs (n, av, Nothing ) = (IEThingAbs n, trimAvail av n)
584 mkIEThingAbs (n, av, Just parent) = (IEThingAbs n, AvailTC parent [n])
587 catMaybeErr :: [MaybeErr err a] -> [a]
588 catMaybeErr ms = [ a | Succeeded a <- ms ]
591 %************************************************************************
595 %************************************************************************
598 -- | make a 'GlobalRdrEnv' where all the elements point to the same
599 -- import declaration (useful for "hiding" imports, or imports with
601 gresFromAvails :: Provenance -> [AvailInfo] -> [GlobalRdrElt]
602 gresFromAvails prov avails
603 = concatMap (gresFromAvail (const prov)) avails
605 gresFromAvail :: (Name -> Provenance) -> AvailInfo -> [GlobalRdrElt]
606 gresFromAvail prov_fn avail
607 = [ GRE {gre_name = n,
608 gre_par = availParent n avail,
609 gre_prov = prov_fn n}
610 | n <- availNames avail ]
612 greAvail :: GlobalRdrElt -> AvailInfo
613 greAvail gre = mkUnitAvail (gre_name gre) (gre_par gre)
615 mkUnitAvail :: Name -> Parent -> AvailInfo
616 mkUnitAvail me (ParentIs p) = AvailTC p [me]
617 mkUnitAvail me NoParent | isTyConName me = AvailTC me [me]
618 | otherwise = Avail me
620 plusAvail (Avail n1) (Avail n2) = Avail n1
621 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
622 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
624 availParent :: Name -> AvailInfo -> Parent
625 availParent n (Avail _) = NoParent
626 availParent n (AvailTC m ms) | n==m = NoParent
627 | otherwise = ParentIs m
629 trimAvail :: AvailInfo -> Name -> AvailInfo
630 trimAvail (Avail n) m = Avail n
631 trimAvail (AvailTC n ns) m = ASSERT( m `elem` ns) AvailTC n [m]
633 -- | filters 'AvailInfo's by the given predicate
634 filterAvails :: (Name -> Bool) -> [AvailInfo] -> [AvailInfo]
635 filterAvails keep avails = foldr (filterAvail keep) [] avails
637 -- | filters an 'AvailInfo' by the given predicate
638 filterAvail :: (Name -> Bool) -> AvailInfo -> [AvailInfo] -> [AvailInfo]
639 filterAvail keep ie rest =
641 Avail n | keep n -> ie : rest
644 let left = filter keep ns in
645 if null left then rest else AvailTC tc left : rest
647 -- | Given an import/export spec, construct the appropriate 'GlobalRdrElt's.
648 gresFromIE :: ImpDeclSpec -> (LIE Name, AvailInfo) -> [GlobalRdrElt]
649 gresFromIE decl_spec (L loc ie, avail)
650 = gresFromAvail prov_fn avail
652 is_explicit = case ie of
653 IEThingAll name -> \n -> n==name
655 prov_fn name = Imported [imp_spec]
657 imp_spec = ImpSpec { is_decl = decl_spec, is_item = item_spec }
658 item_spec = ImpSome { is_explicit = is_explicit name, is_iloc = loc }
660 mkChildEnv :: [GlobalRdrElt] -> NameEnv [Name]
661 mkChildEnv gres = foldr add emptyNameEnv gres
663 add (GRE { gre_name = n, gre_par = ParentIs p }) env = extendNameEnv_C (++) env p [n]
664 add other_gre env = env
666 findChildren :: NameEnv [Name] -> Name -> [Name]
667 findChildren env n = lookupNameEnv env n `orElse` []
670 ---------------------------------------
673 All this AvailEnv stuff is hardly used; only in a very small
674 part of RnNames. Todo: remove?
675 ---------------------------------------
678 type AvailEnv = NameEnv AvailInfo -- Maps a Name to the AvailInfo that contains it
680 emptyAvailEnv :: AvailEnv
681 emptyAvailEnv = emptyNameEnv
683 unitAvailEnv :: AvailInfo -> AvailEnv
684 unitAvailEnv a = unitNameEnv (availName a) a
686 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
687 plusAvailEnv = plusNameEnv_C plusAvail
689 availEnvElts :: AvailEnv -> [AvailInfo]
690 availEnvElts = nameEnvElts
692 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
693 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
695 mkAvailEnv :: [AvailInfo] -> AvailEnv
696 -- 'avails' may have several items with the same availName
697 -- E.g import Ix( Ix(..), index )
698 -- will give Ix(Ix,index,range) and Ix(index)
699 -- We want to combine these; addAvail does that
700 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
702 -- After combining the avails, we need to ensure that the parent name is the
703 -- first entry in the list of subnames, if it is included at all. (Subsequent
704 -- functions rely on that.)
705 normaliseAvail :: AvailInfo -> AvailInfo
706 normaliseAvail avail@(Avail _) = avail
707 normaliseAvail (AvailTC name subs) = AvailTC name subs'
709 subs' = if name `elem` subs then name : (delete name subs) else subs
711 -- | combines 'AvailInfo's from the same family
712 nubAvails :: [AvailInfo] -> [AvailInfo]
713 nubAvails avails = map normaliseAvail . nameEnvElts . mkAvailEnv $ avails
717 %************************************************************************
719 \subsection{Export list processing}
721 %************************************************************************
723 Processing the export list.
725 You might think that we should record things that appear in the export
726 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
727 wrong. We do check (here) that they are in scope, but there is no
728 need to slurp in their actual declaration (which is what
729 @addOccurrenceName@ forces).
731 Indeed, doing so would big trouble when compiling @PrelBase@, because
732 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
733 @ConcBase.StateAndSynchVar#@, and so on...
736 type ExportAccum -- The type of the accumulating parameter of
737 -- the main worker function in rnExports
738 = ([LIE Name], -- Export items with Names
739 ExportOccMap, -- Tracks exported occurrence names
740 [AvailInfo]) -- The accumulated exported stuff
743 emptyExportAccum = ([], emptyOccEnv, [])
745 type ExportOccMap = OccEnv (Name, IE RdrName)
746 -- Tracks what a particular exported OccName
747 -- in an export list refers to, and which item
748 -- it came from. It's illegal to export two distinct things
749 -- that have the same occurrence name
751 rnExports :: Bool -- False => no 'module M(..) where' header at all
752 -> Maybe [LIE RdrName] -- Nothing => no explicit export list
756 -- Complains if two distinct exports have same OccName
757 -- Warns about identical exports.
758 -- Complains about exports items not in scope
760 rnExports explicit_mod exports
761 tcg_env@(TcGblEnv { tcg_mod = this_mod,
762 tcg_rdr_env = rdr_env,
763 tcg_imports = imports })
765 -- If the module header is omitted altogether, then behave
766 -- as if the user had written "module Main(main) where..."
767 -- EXCEPT in interactive mode, when we behave as if he had
768 -- written "module Main where ..."
769 -- Reason: don't want to complain about 'main' not in scope
770 -- in interactive mode
773 | explicit_mod = exports
774 | ghcLink dflags == LinkInMemory = Nothing
775 | otherwise = Just ([noLoc (IEVar main_RDR_Unqual)])
776 -- ToDo: the 'noLoc' here is unhelpful if 'main'
777 -- turns out to be out of scope
779 ; (rn_exports, avails) <- exports_from_avail real_exports rdr_env imports this_mod
780 ; let final_avails = nubAvails avails -- Combine families
782 ; return (tcg_env { tcg_exports = final_avails,
783 tcg_rn_exports = case tcg_rn_exports tcg_env of
785 Just _ -> rn_exports,
786 tcg_dus = tcg_dus tcg_env `plusDU`
787 usesOnly (availsToNameSet final_avails) }) }
790 exports_from_avail :: Maybe [LIE RdrName]
791 -- Nothing => no explicit export list
795 -> RnM (Maybe [LIE Name], [AvailInfo])
797 exports_from_avail Nothing rdr_env imports this_mod
798 = -- The same as (module M) where M is the current module name,
799 -- so that's how we handle it.
801 avails = [ greAvail gre | gre <- globalRdrEnvElts rdr_env,
804 return (Nothing, avails)
806 exports_from_avail (Just rdr_items) rdr_env imports this_mod
807 = do (ie_names, _, exports) <- foldlM do_litem emptyExportAccum rdr_items
809 return (Just ie_names, exports)
811 do_litem :: ExportAccum -> LIE RdrName -> RnM ExportAccum
812 do_litem acc lie = setSrcSpan (getLoc lie) (exports_from_item acc lie)
814 kids_env :: NameEnv [Name] -- Maps a parent to its in-scope children
815 kids_env = mkChildEnv (globalRdrEnvElts rdr_env)
817 imported_modules = [ qual_name
818 | (_, xs) <- moduleEnvElts $ imp_mods imports,
819 (qual_name, _, _) <- xs ]
821 exports_from_item :: ExportAccum -> LIE RdrName -> RnM ExportAccum
822 exports_from_item acc@(ie_names, occs, exports)
823 (L loc ie@(IEModuleContents mod))
824 | let earlier_mods = [ mod | (L _ (IEModuleContents mod)) <- ie_names ]
825 , mod `elem` earlier_mods -- Duplicate export of M
826 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
827 warnIf warn_dup_exports (dupModuleExport mod) ;
831 = do { implicit_prelude <- doptM Opt_ImplicitPrelude
832 ; let { exportValid = (mod `elem` imported_modules)
833 || (moduleName this_mod == mod)
834 ; gres = filter (isModuleExported implicit_prelude mod)
835 (globalRdrEnvElts rdr_env)
838 ; checkErr exportValid (moduleNotImported mod)
839 ; warnIf (exportValid && null gres) (nullModuleExport mod)
841 ; occs' <- check_occs ie occs (map gre_name gres)
842 -- This check_occs not only finds conflicts
843 -- between this item and others, but also
844 -- internally within this item. That is, if
845 -- 'M.x' is in scope in several ways, we'll have
846 -- several members of mod_avails with the same
848 ; return (L loc (IEModuleContents mod) : ie_names,
849 occs', map greAvail gres ++ exports) }
851 exports_from_item acc@(lie_names, occs, exports) (L loc ie)
853 = do new_ie <- lookup_doc_ie ie
854 return (L loc new_ie : lie_names, occs, exports)
857 = do (new_ie, avail) <- lookup_ie ie
858 if isUnboundName (ieName new_ie)
859 then return acc -- Avoid error cascade
862 occs' <- check_occs ie occs (availNames avail)
864 return (L loc new_ie : lie_names, occs', avail : exports)
867 lookup_ie :: IE RdrName -> RnM (IE Name, AvailInfo)
868 lookup_ie (IEVar rdr)
869 = do gre <- lookupGreRn rdr
870 return (IEVar (gre_name gre), greAvail gre)
872 lookup_ie (IEThingAbs rdr)
873 = do gre <- lookupGreRn rdr
874 let name = gre_name gre
876 NoParent -> return (IEThingAbs name,
878 ParentIs p -> return (IEThingAbs name,
881 lookup_ie ie@(IEThingAll rdr)
882 = do name <- lookupGlobalOccRn rdr
883 let kids = findChildren kids_env name
885 (if (isTyConName name) then addWarn (dodgyExportWarn name)
886 -- This occurs when you export T(..), but
887 -- only import T abstractly, or T is a synonym.
888 else addErr (exportItemErr ie))
890 return (IEThingAll name, AvailTC name (name:kids))
892 lookup_ie ie@(IEThingWith rdr sub_rdrs)
893 = do name <- lookupGlobalOccRn rdr
894 if isUnboundName name
895 then return (IEThingWith name [], AvailTC name [name])
897 let env = mkOccEnv [ (nameOccName s, s)
898 | s <- findChildren kids_env name ]
899 mb_names = map (lookupOccEnv env . rdrNameOcc) sub_rdrs
900 if any isNothing mb_names
901 then do addErr (exportItemErr ie)
902 return (IEThingWith name [], AvailTC name [name])
903 else do let names = catMaybes mb_names
904 optTyFam <- doptM Opt_TypeFamilies
905 when (not optTyFam && any isTyConName names) $
906 addErr (typeItemErr ( head
909 (text "in export list"))
910 return (IEThingWith name names, AvailTC name (name:names))
912 lookup_ie ie = panic "lookup_ie" -- Other cases covered earlier
915 lookup_doc_ie :: IE RdrName -> RnM (IE Name)
916 lookup_doc_ie (IEGroup lev doc) = do rn_doc <- rnHsDoc doc
917 return (IEGroup lev rn_doc)
918 lookup_doc_ie (IEDoc doc) = do rn_doc <- rnHsDoc doc
919 return (IEDoc rn_doc)
920 lookup_doc_ie (IEDocNamed str) = return (IEDocNamed str)
921 lookup_doc_ie ie = panic "lookup_doc_ie" -- Other cases covered earlier
924 isDoc (IEDoc _) = True
925 isDoc (IEDocNamed _) = True
926 isDoc (IEGroup _ _) = True
929 -------------------------------
930 isModuleExported :: Bool -> ModuleName -> GlobalRdrElt -> Bool
931 -- True if the thing is in scope *both* unqualified, *and* with qualifier M
932 isModuleExported implicit_prelude mod (GRE { gre_name = name, gre_prov = prov })
933 | implicit_prelude && isBuiltInSyntax name = False
934 -- Optimisation: filter out names for built-in syntax
935 -- They just clutter up the environment (esp tuples), and the parser
936 -- will generate Exact RdrNames for them, so the cluttered
937 -- envt is no use. To avoid doing this filter all the time,
938 -- we use -fno-implicit-prelude as a clue that the filter is
939 -- worth while. Really, it's only useful for GHC.Base and GHC.Tuple.
941 -- It's worth doing because it makes the environment smaller for
942 -- every module that imports the Prelude
945 LocalDef -> moduleName (nameModule name) == mod
946 Imported is -> any unQualSpecOK is && any (qualSpecOK mod) is
948 -------------------------------
949 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
950 check_occs ie occs names
951 = foldlM check occs names
954 = case lookupOccEnv occs name_occ of
955 Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
958 | name == name' -- Duplicate export
959 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
960 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
963 | otherwise -- Same occ name but different names: an error
964 -> do { global_env <- getGlobalRdrEnv ;
965 addErr (exportClashErr global_env name' name ie' ie) ;
968 name_occ = nameOccName name
971 %*********************************************************
975 %*********************************************************
978 finishDeprecations :: DynFlags -> Maybe DeprecTxt
979 -> TcGblEnv -> RnM TcGblEnv
980 -- (a) Report usasge of deprecated imports
981 -- (b) If the whole module is deprecated, update tcg_deprecs
982 -- All this happens only once per module
983 finishDeprecations dflags mod_deprec tcg_env
984 = do { (eps,hpt) <- getEpsAndHpt
985 ; ifOptM Opt_WarnDeprecations $
986 mapM_ (check hpt (eps_PIT eps)) all_gres
987 -- By this time, typechecking is complete,
988 -- so the PIT is fully populated
990 -- Deal with a module deprecation; it overrides all existing deprecs
991 ; let new_deprecs = case mod_deprec of
992 Just txt -> DeprecAll txt
993 Nothing -> tcg_deprecs tcg_env
994 ; return (tcg_env { tcg_deprecs = new_deprecs }) }
996 used_names = allUses (tcg_dus tcg_env)
997 -- Report on all deprecated uses; hence allUses
998 all_gres = globalRdrEnvElts (tcg_rdr_env tcg_env)
1000 check hpt pit gre@(GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
1001 | name `elemNameSet` used_names
1002 , Just deprec_txt <- lookupImpDeprec dflags hpt pit gre
1003 = addWarnAt (importSpecLoc imp_spec)
1004 (sep [ptext SLIT("Deprecated use of") <+>
1005 pprNonVarNameSpace (occNameSpace (nameOccName name)) <+>
1007 (parens imp_msg) <> colon,
1010 name_mod = nameModule name
1011 imp_mod = importSpecModule imp_spec
1012 imp_msg = ptext SLIT("imported from") <+> ppr imp_mod <> extra
1013 extra | imp_mod == moduleName name_mod = empty
1014 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
1016 check hpt pit ok_gre = returnM () -- Local, or not used, or not deprectated
1017 -- The Imported pattern-match: don't deprecate locally defined names
1018 -- For a start, we may be exporting a deprecated thing
1019 -- Also we may use a deprecated thing in the defn of another
1020 -- deprecated things. We may even use a deprecated thing in
1021 -- the defn of a non-deprecated thing, when changing a module's
1024 lookupImpDeprec :: DynFlags -> HomePackageTable -> PackageIfaceTable
1025 -> GlobalRdrElt -> Maybe DeprecTxt
1026 -- The name is definitely imported, so look in HPT, PIT
1027 lookupImpDeprec dflags hpt pit gre
1028 = case lookupIfaceByModule dflags hpt pit (nameModule name) of
1029 Just iface -> mi_dep_fn iface name `seqMaybe` -- Bleat if the thing, *or
1031 ParentIs p -> mi_dep_fn iface p -- its parent*, is deprec'd
1034 Nothing -> Nothing -- See Note [Used names with interface not loaded]
1039 Note [Used names with interface not loaded]
1040 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1041 By now all the interfaces should have been loaded,
1042 because reportDeprecations happens after typechecking.
1043 However, it's still (just) possible to to find a used
1044 Name whose interface hasn't been loaded:
1046 a) It might be a WiredInName; in that case we may not load
1047 its interface (although we could).
1049 b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
1050 These are seen as "used" by the renamer (if -fno-implicit-prelude)
1051 is on), but the typechecker may discard their uses
1052 if in fact the in-scope fromRational is GHC.Read.fromRational,
1053 (see tcPat.tcOverloadedLit), and the typechecker sees that the type
1054 is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
1055 In that obscure case it won't force the interface in.
1057 In both cases we simply don't permit deprecations;
1058 this is, after all, wired-in stuff.
1061 %*********************************************************
1065 %*********************************************************
1068 reportUnusedNames :: Maybe [LIE RdrName] -- Export list
1069 -> TcGblEnv -> RnM ()
1070 reportUnusedNames export_decls gbl_env
1071 = do { traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env)))
1072 ; warnUnusedTopBinds unused_locals
1073 ; warnUnusedModules unused_imp_mods
1074 ; warnUnusedImports unused_imports
1075 ; warnDuplicateImports defined_and_used
1076 ; printMinimalImports minimal_imports }
1078 used_names :: NameSet
1079 used_names = findUses (tcg_dus gbl_env) emptyNameSet
1080 -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
1083 -- Collect the defined names from the in-scope environment
1084 defined_names :: [GlobalRdrElt]
1085 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
1087 -- Note that defined_and_used, defined_but_not_used
1088 -- are both [GRE]; that's why we need defined_and_used
1089 -- rather than just used_names
1090 defined_and_used, defined_but_not_used :: [GlobalRdrElt]
1091 (defined_and_used, defined_but_not_used)
1092 = partition (gre_is_used used_names) defined_names
1094 kids_env = mkChildEnv defined_names
1095 -- This is done in mkExports too; duplicated work
1097 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
1098 gre_is_used used_names (GRE {gre_name = name})
1099 = name `elemNameSet` used_names
1100 || any (`elemNameSet` used_names) (findChildren kids_env name)
1101 -- A use of C implies a use of T,
1102 -- if C was brought into scope by T(..) or T(C)
1104 -- Filter out the ones that are
1105 -- (a) defined in this module, and
1106 -- (b) not defined by a 'deriving' clause
1107 -- The latter have an Internal Name, so we can filter them out easily
1108 unused_locals :: [GlobalRdrElt]
1109 unused_locals = filter is_unused_local defined_but_not_used
1110 is_unused_local :: GlobalRdrElt -> Bool
1111 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
1113 unused_imports :: [GlobalRdrElt]
1114 unused_imports = mapCatMaybes unused_imp defined_but_not_used
1115 unused_imp :: GlobalRdrElt -> Maybe GlobalRdrElt -- Result has trimmed Imported provenances
1116 unused_imp gre@(GRE {gre_prov = LocalDef}) = Nothing
1117 unused_imp gre@(GRE {gre_prov = Imported imp_specs})
1118 | null trimmed_specs = Nothing
1119 | otherwise = Just (gre {gre_prov = Imported trimmed_specs})
1121 trimmed_specs = filter report_if_unused imp_specs
1123 -- To figure out the minimal set of imports, start with the things
1124 -- that are in scope (i.e. in gbl_env). Then just combine them
1125 -- into a bunch of avails, so they are properly grouped
1127 -- BUG WARNING: this does not deal properly with qualified imports!
1128 minimal_imports :: FiniteMap ModuleName AvailEnv
1129 minimal_imports0 = foldr add_expall emptyFM expall_mods
1130 minimal_imports1 = foldr add_name minimal_imports0 defined_and_used
1131 minimal_imports = foldr add_inst_mod minimal_imports1 direct_import_mods
1132 -- The last line makes sure that we retain all direct imports
1133 -- even if we import nothing explicitly.
1134 -- It's not necessarily redundant to import such modules. Consider
1138 -- The import M() is not *necessarily* redundant, even if
1139 -- we suck in no instance decls from M (e.g. it contains
1140 -- no instance decls, or This contains no code). It may be
1141 -- that we import M solely to ensure that M's orphan instance
1142 -- decls (or those in its imports) are visible to people who
1143 -- import This. Sigh.
1144 -- There's really no good way to detect this, so the error message
1145 -- in RnEnv.warnUnusedModules is weakened instead
1147 -- We've carefully preserved the provenance so that we can
1148 -- construct minimal imports that import the name by (one of)
1149 -- the same route(s) as the programmer originally did.
1150 add_name gre@(GRE {gre_prov = Imported (imp_spec:_)}) acc
1151 = addToFM_C plusAvailEnv acc
1152 (importSpecModule imp_spec) (unitAvailEnv (greAvail gre))
1153 add_name gre acc = acc -- Local
1155 -- Modules mentioned as 'module M' in the export list
1156 expall_mods = case export_decls of
1158 Just es -> [m | L _ (IEModuleContents m) <- es]
1160 -- This is really bogus. The idea is that if we see 'module M' in
1161 -- the export list we must retain the import decls that drive it
1162 -- If we aren't careful we might see
1163 -- module A( module M ) where
1166 -- and suppose that N exports everything that M does. Then we
1167 -- must not drop the import of M even though N brings it all into
1170 -- BUG WARNING: 'module M' exports aside, what if M.x is mentioned?!
1172 -- The reason that add_expall is bogus is that it doesn't take
1173 -- qualified imports into account. But it's an improvement.
1174 add_expall mod acc = addToFM_C plusAvailEnv acc mod emptyAvailEnv
1176 add_inst_mod (mod, _) acc
1177 | mod_name `elemFM` acc = acc -- We import something already
1178 | otherwise = addToFM acc mod_name emptyAvailEnv
1180 mod_name = moduleName mod
1181 -- Add an empty collection of imports for a module
1182 -- from which we have sucked only instance decls
1184 imports = tcg_imports gbl_env
1186 direct_import_mods :: [(Module, [(ModuleName, Bool, SrcSpan)])]
1187 -- See the type of the imp_mods for this triple
1188 direct_import_mods = moduleEnvElts (imp_mods imports)
1190 -- unused_imp_mods are the directly-imported modules
1191 -- that are not mentioned in minimal_imports1
1192 -- [Note: not 'minimal_imports', because that includes directly-imported
1193 -- modules even if we use nothing from them; see notes above]
1195 -- BUG WARNING: this code is generally buggy
1196 unused_imp_mods :: [(ModuleName, SrcSpan)]
1197 unused_imp_mods = [(mod_name,loc)
1198 | (mod, xs) <- direct_import_mods,
1199 (_, no_imp, loc) <- xs,
1200 let mod_name = moduleName mod,
1201 not (mod_name `elemFM` minimal_imports1),
1204 -- The not no_imp part is not to complain about
1205 -- import M (), which is an idiom for importing
1206 -- instance declarations
1208 module_unused :: ModuleName -> Bool
1209 module_unused mod = any (((==) mod) . fst) unused_imp_mods
1211 report_if_unused :: ImportSpec -> Bool
1212 -- Do we want to report this as an unused import?
1213 report_if_unused (ImpSpec {is_decl = d, is_item = i})
1214 = not (module_unused (is_mod d)) -- Not if we've already said entire import is unused
1215 && isExplicitItem i -- Only if the import was explicit
1217 ---------------------
1218 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
1219 -- Given the GREs for names that are used, figure out which imports
1220 -- could be omitted without changing the top-level environment.
1222 -- NB: Given import Foo( T )
1223 -- import qualified Foo
1224 -- we do not report a duplicate import, even though Foo.T is brought
1225 -- into scope by both, because there's nothing you can *omit* without
1226 -- changing the top-level environment. So we complain only if it's
1227 -- explicitly named in both imports or neither.
1229 -- Furthermore, we complain about Foo.T only if
1230 -- there is no complaint about (unqualified) T
1232 warnDuplicateImports gres
1233 = ifOptM Opt_WarnUnusedImports $
1234 sequenceM_ [ warn name pr
1235 | GRE { gre_name = name, gre_prov = Imported imps } <- gres
1236 , pr <- redundants imps ]
1238 warn name (red_imp, cov_imp)
1239 = addWarnAt (importSpecLoc red_imp)
1240 (vcat [ptext SLIT("Redundant import of:") <+> quotes pp_name,
1241 ptext SLIT("It is also") <+> ppr cov_imp])
1243 pp_name | is_qual red_decl = ppr (is_as red_decl) <> dot <> ppr occ
1244 | otherwise = ppr occ
1245 occ = nameOccName name
1246 red_decl = is_decl red_imp
1248 redundants :: [ImportSpec] -> [(ImportSpec,ImportSpec)]
1249 -- The returned pair is (redundant-import, covering-import)
1251 = [ (red_imp, cov_imp)
1253 , isExplicitItem (is_item red_imp)
1254 -- Complain only about redundant imports
1255 -- mentioned explicitly by the user
1256 , cov_imp <- take 1 (filter (covers red_imp) imps) ]
1257 -- The 'take 1' picks the first offending group
1258 -- for this particular name
1260 -- "red_imp" is a putative redundant import
1261 -- "cov_imp" potentially covers it
1262 -- This test decides whether red_imp could be dropped
1264 -- NOTE: currently the test does not warn about
1267 -- even if the same underlying 'x' is involved, because dropping
1268 -- either import would change the qualified names in scope (M.x, N.x)
1269 -- But if the qualified names aren't used, the import is indeed redundant
1270 -- Sadly we don't know that. Oh well.
1271 covers red_imp@(ImpSpec { is_decl = red_decl, is_item = red_item })
1272 cov_imp@(ImpSpec { is_decl = cov_decl, is_item = cov_item })
1273 | red_loc == cov_loc
1274 = False -- Ignore diagonal elements
1275 | not (is_as red_decl == is_as cov_decl)
1276 = False -- They bring into scope different qualified names
1277 | not (is_qual red_decl) && is_qual cov_decl
1278 = False -- Covering one doesn't bring unqualified name into scope
1280 = not (isExplicitItem cov_item) -- Redundant one is selective and covering one isn't
1281 || red_later -- or both are explicit; tie-break using red_later
1284 = not cov_selective -- Redundant one is selective and covering one isn't
1285 || red_later -- Both are explicit; tie-break using red_later
1287 = not cov_selective -- Neither import is selective
1288 && (is_mod red_decl == is_mod cov_decl) -- They import the same module
1289 && red_later -- Tie-break
1292 red_loc = importSpecLoc red_imp
1293 cov_loc = importSpecLoc cov_imp
1294 red_later = red_loc > cov_loc
1296 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
1297 printMinimalImports :: FiniteMap ModuleName AvailEnv -- Minimal imports
1299 printMinimalImports imps
1300 = ifOptM Opt_D_dump_minimal_imports $ do {
1302 mod_ies <- initIfaceTcRn $ mappM to_ies (fmToList imps) ;
1303 this_mod <- getModule ;
1304 rdr_env <- getGlobalRdrEnv ;
1305 dflags <- getDOpts ;
1306 ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
1307 printForUser h (mkPrintUnqualified dflags rdr_env)
1308 (vcat (map ppr_mod_ie mod_ies)) })
1311 mkFilename this_mod = moduleNameString (moduleName this_mod) ++ ".imports"
1312 ppr_mod_ie (mod_name, ies)
1313 | mod_name == moduleName pRELUDE
1315 | null ies -- Nothing except instances comes from here
1316 = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("() -- Instances only")
1318 = ptext SLIT("import") <+> ppr mod_name <>
1319 parens (fsep (punctuate comma (map ppr ies)))
1321 to_ies (mod, avail_env) = do ies <- mapM to_ie (availEnvElts avail_env)
1324 to_ie :: AvailInfo -> IfG (IE Name)
1325 -- The main trick here is that if we're importing all the constructors
1326 -- we want to say "T(..)", but if we're importing only a subset we want
1327 -- to say "T(A,B,C)". So we have to find out what the module exports.
1328 to_ie (Avail n) = returnM (IEVar n)
1329 to_ie (AvailTC n [m]) = ASSERT( n==m )
1330 returnM (IEThingAbs n)
1331 to_ie (AvailTC n ns)
1332 = loadSysInterface doc n_mod `thenM` \ iface ->
1333 case [xs | (m,as) <- mi_exports iface,
1336 x == nameOccName n] of
1337 [xs] | all_used xs -> returnM (IEThingAll n)
1338 | otherwise -> returnM (IEThingWith n (filter (/= n) ns))
1339 other -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
1342 all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
1343 doc = text "Compute minimal imports from" <+> ppr n
1344 n_mod = nameModule n
1348 %************************************************************************
1352 %************************************************************************
1355 badImportItemErr iface decl_spec ie
1356 = sep [ptext SLIT("Module"), quotes (ppr (is_mod decl_spec)), source_import,
1357 ptext SLIT("does not export"), quotes (ppr ie)]
1359 source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
1362 illegalImportItemErr = ptext SLIT("Illegal import item")
1364 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
1365 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
1368 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
1369 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructors or class methods,"),
1370 ptext SLIT("but it has none") ]
1372 exportItemErr export_item
1373 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
1374 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
1376 typeItemErr name wherestr
1377 = sep [ ptext SLIT("Using 'type' tag on") <+> quotes (ppr name) <+> wherestr,
1378 ptext SLIT("Use -XTypeFamilies to enable this extension") ]
1380 exportClashErr :: GlobalRdrEnv -> Name -> Name -> IE RdrName -> IE RdrName
1382 exportClashErr global_env name1 name2 ie1 ie2
1383 = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
1384 , ppr_export ie1' name1'
1385 , ppr_export ie2' name2' ]
1387 occ = nameOccName name1
1388 ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+>
1389 quotes (ppr name) <+> pprNameProvenance (get_gre name))
1391 -- get_gre finds a GRE for the Name, so that we can show its provenance
1393 = case lookupGRE_Name global_env name of
1395 [] -> pprPanic "exportClashErr" (ppr name)
1396 get_loc name = nameSrcLoc $ gre_name $ get_gre name
1397 (name1', ie1', name2', ie2') = if get_loc name1 < get_loc name2
1398 then (name1, ie1, name2, ie2)
1399 else (name2, ie2, name1, ie1)
1401 addDupDeclErr :: Name -> Name -> TcRn ()
1402 addDupDeclErr name_a name_b
1403 = addErrAt (srcLocSpan loc2) $
1404 vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
1405 ptext SLIT("Declared at:") <+> vcat [ppr (nameSrcLoc name1), ppr loc2]]
1407 loc2 = nameSrcLoc name2
1408 (name1,name2) | nameSrcLoc name_a > nameSrcLoc name_b = (name_b,name_a)
1409 | otherwise = (name_a,name_b)
1410 -- Report the error at the later location
1412 dupExportWarn occ_name ie1 ie2
1413 = hsep [quotes (ppr occ_name),
1414 ptext SLIT("is exported by"), quotes (ppr ie1),
1415 ptext SLIT("and"), quotes (ppr ie2)]
1418 = hsep [ptext SLIT("Duplicate"),
1419 quotes (ptext SLIT("Module") <+> ppr mod),
1420 ptext SLIT("in export list")]
1422 moduleNotImported :: ModuleName -> SDoc
1423 moduleNotImported mod
1424 = ptext SLIT("The export item `module") <+> ppr mod <>
1425 ptext SLIT("' is not imported")
1427 nullModuleExport mod
1428 = ptext SLIT("The export item `module") <+> ppr mod <> ptext SLIT("' exports nothing")
1430 moduleDeprec mod txt
1431 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),
1435 = ptext SLIT("Module `Prelude' implicitly imported")