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 )
54 import Data.List ( partition, concatMap, (\\), delete )
55 import IO ( openFile, IOMode(..) )
56 import Monad ( when, mplus )
61 %************************************************************************
65 %************************************************************************
68 rnImports :: [LImportDecl RdrName]
69 -> RnM ([LImportDecl Name], GlobalRdrEnv, ImportAvails,AnyHpcUsage)
72 -- PROCESS IMPORT DECLS
73 -- Do the non {- SOURCE -} ones first, so that we get a helpful
74 -- warning for {- SOURCE -} ones that are unnecessary
75 = do this_mod <- getModule
76 implicit_prelude <- doptM Opt_ImplicitPrelude
77 let prel_imports = mkPrelImports this_mod implicit_prelude imports
78 (source, ordinary) = partition is_source_import imports
79 is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot
81 ifOptM Opt_WarnImplicitPrelude (
82 when (notNull prel_imports) $ addWarn (implicitPreludeWarn)
85 stuff1 <- mapM (rnImportDecl this_mod) (prel_imports ++ ordinary)
86 stuff2 <- mapM (rnImportDecl this_mod) source
87 let (decls, rdr_env, imp_avails,hpc_usage) = combine (stuff1 ++ stuff2)
88 return (decls, rdr_env, imp_avails,hpc_usage)
91 combine :: [(LImportDecl Name, GlobalRdrEnv, ImportAvails,AnyHpcUsage)]
92 -> ([LImportDecl Name], GlobalRdrEnv, ImportAvails,AnyHpcUsage)
93 combine = foldr plus ([], emptyGlobalRdrEnv, emptyImportAvails,False)
94 where plus (decl, gbl_env1, imp_avails1,hpc_usage1)
95 (decls, gbl_env2, imp_avails2,hpc_usage2)
97 gbl_env1 `plusGlobalRdrEnv` gbl_env2,
98 imp_avails1 `plusImportAvails` imp_avails2,
99 hpc_usage1 || hpc_usage2)
101 mkPrelImports :: Module -> Bool -> [LImportDecl RdrName] -> [LImportDecl RdrName]
102 -- Consruct the implicit declaration "import Prelude" (or not)
104 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
105 -- because the former doesn't even look at Prelude.hi for instance
106 -- declarations, whereas the latter does.
107 mkPrelImports this_mod implicit_prelude import_decls
108 | this_mod == pRELUDE
109 || explicit_prelude_import
110 || not implicit_prelude
112 | otherwise = [preludeImportDecl]
114 explicit_prelude_import
115 = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- import_decls,
116 unLoc mod == pRELUDE_NAME ]
118 preludeImportDecl :: LImportDecl RdrName
121 ImportDecl (L loc pRELUDE_NAME)
122 False {- Not a boot interface -}
123 False {- Not qualified -}
124 Nothing {- No "as" -}
125 Nothing {- No import list -}
127 loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")
130 rnImportDecl :: Module
131 -> LImportDecl RdrName
132 -> RnM (LImportDecl Name, GlobalRdrEnv, ImportAvails,AnyHpcUsage)
134 rnImportDecl this_mod (L loc (ImportDecl loc_imp_mod_name want_boot
135 qual_only as_mod imp_details))
139 -- If there's an error in loadInterface, (e.g. interface
140 -- file not found) we get lots of spurious errors from 'filterImports'
142 imp_mod_name = unLoc loc_imp_mod_name
143 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
145 iface <- loadSrcInterface doc imp_mod_name want_boot
147 -- Compiler sanity check: if the import didn't say
148 -- {-# SOURCE #-} we should not get a hi-boot file
149 WARN( not want_boot && mi_boot iface, ppr imp_mod_name ) (do
151 -- Issue a user warning for a redundant {- SOURCE -} import
152 -- NB that we arrange to read all the ordinary imports before
153 -- any of the {- SOURCE -} imports
154 warnIf (want_boot && not (mi_boot iface))
155 (warnRedundantSourceImport imp_mod_name)
158 imp_mod = mi_module iface
159 deprecs = mi_deprecs iface
160 orph_iface = mi_orphan iface
161 has_finsts = mi_finsts iface
164 filtered_exports = filter not_this_mod (mi_exports iface)
165 not_this_mod (mod,_) = mod /= this_mod
166 -- If the module exports anything defined in this module, just
167 -- ignore it. Reason: otherwise it looks as if there are two
168 -- local definition sites for the thing, and an error gets
169 -- reported. Easiest thing is just to filter them out up
170 -- front. This situation only arises if a module imports
171 -- itself, or another module that imported it. (Necessarily,
172 -- this invoves a loop.)
174 -- Tiresome consequence: if you say
179 -- module B( AType ) where
180 -- import {-# SOURCE #-} A( AType )
182 -- then you'll get a 'B does not export AType' message. Oh well.
184 qual_mod_name = case as_mod of
185 Nothing -> imp_mod_name
186 Just another_name -> another_name
187 imp_spec = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,
188 is_dloc = loc, is_as = qual_mod_name }
191 -- Get the total exports from this module
192 total_avails <- ifaceExportNames filtered_exports
194 -- filter the imports according to the import declaration
195 (new_imp_details, gbl_env) <-
196 filterImports iface imp_spec imp_details total_avails
201 -- Compute new transitive dependencies
203 orphans | orph_iface = ASSERT( not (imp_mod `elem` dep_orphs deps) )
204 imp_mod : dep_orphs deps
205 | otherwise = dep_orphs deps
207 finsts | has_finsts = ASSERT( not (imp_mod `elem` dep_finsts deps) )
208 imp_mod : dep_finsts deps
209 | otherwise = dep_finsts deps
211 pkg = modulePackageId (mi_module iface)
213 (dependent_mods, dependent_pkgs)
214 | pkg == thisPackage dflags =
215 -- Imported module is from the home package
216 -- Take its dependent modules and add imp_mod itself
217 -- Take its dependent packages unchanged
219 -- NB: (dep_mods deps) might include a hi-boot file
220 -- for the module being compiled, CM. Do *not* filter
221 -- this out (as we used to), because when we've
222 -- finished dealing with the direct imports we want to
223 -- know if any of them depended on CM.hi-boot, in
224 -- which case we should do the hi-boot consistency
225 -- check. See LoadIface.loadHiBootInterface
226 ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)
229 -- Imported module is from another package
230 -- Dump the dependent modules
231 -- Add the package imp_mod comes from to the dependent packages
232 ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
233 ([], pkg : dep_pkgs deps)
235 -- True <=> import M ()
236 import_all = case imp_details of
237 Just (is_hiding, ls) -> not is_hiding && null ls
240 imports = ImportAvails {
241 imp_mods = unitModuleEnv imp_mod (imp_mod, [(qual_mod_name, import_all, loc)]),
244 imp_dep_mods = mkModDeps dependent_mods,
245 imp_dep_pkgs = dependent_pkgs
248 -- Complain if we import a deprecated module
249 ifOptM Opt_WarnDeprecations (
251 DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
255 let new_imp_decl = L loc (ImportDecl loc_imp_mod_name want_boot
256 qual_only as_mod new_imp_details)
258 return (new_imp_decl, gbl_env, imports, mi_hpc iface)
261 warnRedundantSourceImport mod_name
262 = ptext SLIT("Unnecessary {-# SOURCE #-} in the import of module")
263 <+> quotes (ppr mod_name)
267 %************************************************************************
269 importsFromLocalDecls
271 %************************************************************************
273 From the top-level declarations of this module produce
274 * the lexical environment
276 created by its bindings.
279 -- Bool determines shadowing:
280 -- true: names in the group should shadow other UnQuals
281 -- with the same OccName (used in Template Haskell)
282 -- false: duplicates should be reported as an error
284 -- The UniqFM (OccName -> FixItem) associates a Name's OccName's
285 -- FastString with a fixity declaration (that needs the actual OccName
286 -- to be plugged in). This fixity must be brought into scope when such
288 importsFromLocalDecls :: Bool -> HsGroup RdrName -> UniqFM (Located Fixity) -> RnM TcGblEnv
289 importsFromLocalDecls shadowP group fixities
290 = do { gbl_env <- getGblEnv
292 ; avails <- getLocalDeclBinders gbl_env group
294 ; (rdr_env', fix_env') <- extendRdrEnvRn shadowP (tcg_rdr_env gbl_env,
298 ; traceRn (text "local avails: " <> ppr avails)
300 ; return (gbl_env { tcg_rdr_env = rdr_env',
301 tcg_fix_env = fix_env'})
304 -- Bool determines shadowing as in importsFromLocalDecls.
305 -- UniqFM FixItem is the same as in importsFromLocalDecls.
307 -- Add the new locally-bound names one by one, checking for duplicates as
308 -- we do so. Remember that in Template Haskell the duplicates
309 -- might *already be* in the GlobalRdrEnv from higher up the module.
311 -- Also update the FixityEnv with the fixities for the names brought into scope.
313 -- Note that the return values are the extensions of the two inputs,
314 -- not the extras relative to them.
315 extendRdrEnvRn :: Bool -> (GlobalRdrEnv, NameEnv FixItem)
316 -> [AvailInfo] -> UniqFM (Located Fixity) -> RnM (GlobalRdrEnv, NameEnv FixItem)
317 extendRdrEnvRn shadowP (rdr_env, fix_env) avails fixities =
318 let -- if there is a fixity decl for the gre,
319 -- add it to the fixity env
320 extendFixEnv env gre =
321 let name = gre_name gre
322 occ = nameOccName name
323 curKey = occNameFS occ in
324 case lookupUFM fixities curKey of
326 Just (L _ fi) -> extendNameEnv env name (FixItem occ fi)
328 (rdr_env_to_extend, extender) =
330 then -- when shadowing is on,
331 -- (1) we need to remove the existing Unquals for the
332 -- names we're extending the env with
333 -- (2) but extending the env is simple
334 let names = concatMap availNames avails
335 new_occs = map nameOccName names
336 trimmed_rdr_env = hideSomeUnquals rdr_env new_occs
339 \(cur_rdr_env, cur_fix_env) -> \gre ->
340 return (extendGlobalRdrEnv cur_rdr_env gre,
341 extendFixEnv cur_fix_env gre))
342 else -- when shadowing is off,
343 -- (1) we don't munge the incoming env
344 -- (2) but we need to check for dups when extending
346 \(cur_rdr_env, cur_fix_env) -> \gre ->
347 let gres = lookupGlobalRdrEnv cur_rdr_env (nameOccName (gre_name gre))
348 in case filter isLocalGRE gres of -- Check for existing *local* defns
349 dup_gre:_ -> do { addDupDeclErr (gre_name dup_gre) (gre_name gre)
350 ; return (cur_rdr_env, cur_fix_env) }
351 [] -> return (extendGlobalRdrEnv cur_rdr_env gre,
352 extendFixEnv cur_fix_env gre))
353 in foldlM extender (rdr_env_to_extend, fix_env) (gresFromAvails LocalDef avails)
356 @getLocalDeclBinders@ returns the names for an @HsDecl@. It's
357 used for source code.
359 *** See "THE NAMING STORY" in HsDecls ****
361 Instances of type families
362 ~~~~~~~~~~~~~~~~~~~~~~~~~~
363 Indexed data/newtype instances contain data constructors that we need to
364 collect, too. Moreover, we need to descend into the data/newtypes instances
365 of associated families.
367 We need to be careful with the handling of the type constructor of each type
368 instance as the family constructor is already defined, and we want to avoid
369 raising a duplicate declaration error. So, we make a new name for it, but
370 don't return it in the 'AvailInfo'.
373 -- Note: this function does NOT get the binders of the ValBinds that
374 -- will be bound during renaming
375 getLocalDeclBinders :: TcGblEnv -> HsGroup RdrName -> RnM [AvailInfo]
376 getLocalDeclBinders gbl_env (HsGroup {hs_valds = ValBindsIn val_decls val_sigs,
377 hs_tyclds = tycl_decls,
378 hs_instds = inst_decls,
379 hs_fords = foreign_decls })
380 = do { tc_names_s <- mapM new_tc tycl_decls
381 ; at_names_s <- mapM inst_ats inst_decls
382 ; val_names <- mapM new_simple val_bndrs
383 ; return (val_names ++ tc_names_s ++ concat at_names_s) }
385 mod = tcg_mod gbl_env
386 is_hs_boot = isHsBoot (tcg_src gbl_env) ;
388 for_hs_bndrs = [nm | L _ (ForeignImport nm _ _) <- foreign_decls]
390 -- In a hs-boot file, the value binders come from the
391 -- *signatures*, and there should be no foreign binders
392 val_bndrs | is_hs_boot = [nm | L _ (TypeSig nm _) <- val_sigs]
393 | otherwise = for_hs_bndrs
395 new_simple rdr_name = do
396 nm <- newTopSrcBinder mod rdr_name
400 | isFamInstDecl (unLoc tc_decl)
401 = do { main_name <- lookupFamInstDeclBndr mod main_rdr
402 ; sub_names <- mapM (newTopSrcBinder mod) sub_rdrs
403 ; return (AvailTC main_name sub_names) }
404 -- main_name is not bound here!
406 = do { main_name <- newTopSrcBinder mod main_rdr
407 ; sub_names <- mapM (newTopSrcBinder mod) sub_rdrs
408 ; return (AvailTC main_name (main_name : sub_names)) }
410 (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
413 = mapM new_tc (instDeclATs (unLoc inst_decl))
415 getLocalDeclBinders _ _ = panic "getLocalDeclBinders" -- ValBindsOut can't happen
419 %************************************************************************
421 \subsection{Filtering imports}
423 %************************************************************************
425 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
426 available, and filters it through the import spec (if any).
429 filterImports :: ModIface
430 -> ImpDeclSpec -- The span for the entire import decl
431 -> Maybe (Bool, [LIE RdrName]) -- Import spec; True => hiding
432 -> [AvailInfo] -- What's available
433 -> RnM (Maybe (Bool, [LIE Name]), -- Import spec w/ Names
434 GlobalRdrEnv) -- Same again, but in GRE form
436 filterImports iface decl_spec Nothing all_avails
437 = return (Nothing, mkGlobalRdrEnv (gresFromAvails prov all_avails))
439 prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
442 filterImports iface decl_spec (Just (want_hiding, import_items)) all_avails
443 = do -- check for errors, convert RdrNames to Names
444 opt_typeFamilies <- doptM Opt_TypeFamilies
445 items1 <- mapM (lookup_lie opt_typeFamilies) import_items
447 let items2 :: [(LIE Name, AvailInfo)]
448 items2 = concat items1
449 -- NB the AvailInfo may have duplicates, and several items
450 -- for the same parent; e.g N(x) and N(y)
452 names = availsToNameSet (map snd items2)
453 keep n = not (n `elemNameSet` names)
454 pruned_avails = filterAvails keep all_avails
455 hiding_prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
457 gres | want_hiding = gresFromAvails hiding_prov pruned_avails
458 | otherwise = concatMap (gresFromIE decl_spec) items2
460 return (Just (want_hiding, map fst items2), mkGlobalRdrEnv gres)
462 -- This environment is how we map names mentioned in the import
463 -- list to the actual Name they correspond to, and the name family
464 -- that the Name belongs to (the AvailInfo). The situation is
465 -- complicated by associated families, which introduce a three-level
466 -- hierachy, where class = grand parent, assoc family = parent, and
467 -- data constructors = children. The occ_env entries for associated
468 -- families needs to capture all this information; hence, we have the
469 -- third component of the environment that gives the class name (=
470 -- grand parent) in case of associated families.
472 -- This env will have entries for data constructors too,
473 -- they won't make any difference because naked entities like T
474 -- in an import list map to TcOccs, not VarOccs.
475 occ_env :: OccEnv (Name, -- the name
476 AvailInfo, -- the export item providing the name
477 Maybe Name) -- the parent of associated types
478 occ_env = mkOccEnv_C combine [ (nameOccName n, (n, a, Nothing))
479 | a <- all_avails, n <- availNames a]
481 -- we know that (1) there are at most entries for one name, (2) their
482 -- first component is identical, (3) they are for tys/cls, and (4) one
483 -- entry has the name in its parent position (the other doesn't)
484 combine (name, AvailTC p1 subs1, Nothing)
485 (_ , AvailTC p2 subs2, Nothing)
487 (parent, subs) = if p1 == name then (p2, subs1) else (p1, subs2)
489 (name, AvailTC name subs, Just parent)
491 lookup_lie :: Bool -> LIE RdrName -> TcRn [(LIE Name, AvailInfo)]
492 lookup_lie opt_typeFamilies (L loc ieRdr)
494 stuff <- setSrcSpan loc $
495 case lookup_ie opt_typeFamilies ieRdr of
496 Failed err -> addErr err >> return []
497 Succeeded a -> return a
498 checkDodgyImport stuff
499 return [ (L loc ie, avail) | (ie,avail) <- stuff ]
501 -- Warn when importing T(..) if T was exported abstractly
502 checkDodgyImport stuff
503 | IEThingAll n <- ieRdr, (_, AvailTC _ [one]):_ <- stuff
504 = ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn n))
505 -- NB. use the RdrName for reporting the warning
509 -- For each import item, we convert its RdrNames to Names,
510 -- and at the same time construct an AvailInfo corresponding
511 -- to what is actually imported by this item.
512 -- Returns Nothing on error.
513 -- We return a list here, because in the case of an import
514 -- item like C, if we are hiding, then C refers to *both* a
515 -- type/class and a data constructor. Moreover, when we import
516 -- data constructors of an associated family, we need separate
517 -- AvailInfos for the data constructors and the family (as they have
518 -- different parents). See the discussion at occ_env.
519 lookup_ie :: Bool -> IE RdrName -> MaybeErr Message [(IE Name,AvailInfo)]
520 lookup_ie opt_typeFamilies ie
521 = let bad_ie = Failed (badImportItemErr iface decl_spec ie)
523 lookup_name rdrName =
524 case lookupOccEnv occ_env (rdrNameOcc rdrName) of
530 (name, avail, _) <- lookup_name n
531 return [(IEVar name, trimAvail avail name)]
534 (name, avail@(AvailTC name2 subs), mb_parent) <- lookup_name tc
536 -- non-associated ty/cls
537 Nothing -> return [(IEThingAll name, avail)]
539 Just parent -> return [(IEThingAll name,
540 AvailTC name2 (subs \\ [name])),
541 (IEThingAll name, AvailTC parent [name])]
544 | want_hiding -- hiding ( C )
545 -- Here the 'C' can be a data constructor
546 -- *or* a type/class, or even both
547 -> let tc_name = lookup_name tc
548 dc_name = lookup_name (setRdrNameSpace tc srcDataName)
550 case catMaybeErr [ tc_name, dc_name ] of
552 names -> return [mkIEThingAbs name | name <- names]
554 -> do nameAvail <- lookup_name tc
555 return [mkIEThingAbs nameAvail]
557 IEThingWith tc ns -> do
558 (name, AvailTC name2 subnames, mb_parent) <- lookup_name tc
560 env = mkOccEnv [(nameOccName s, s) | s <- subnames]
561 mb_children = map (lookupOccEnv env . rdrNameOcc) ns
562 children <- if any isNothing mb_children
564 else return (catMaybes mb_children)
565 -- check for proper import of type families
566 when (not opt_typeFamilies && any isTyConName children) $
567 Failed (typeItemErr (head . filter isTyConName $ children)
568 (text "in import list"))
570 -- non-associated ty/cls
571 Nothing -> return [(IEThingWith name children,
572 AvailTC name (name:children))]
574 Just parent -> return [(IEThingWith name children,
575 AvailTC name children),
576 (IEThingWith name children,
577 AvailTC parent [name])]
579 _other -> Failed illegalImportItemErr
580 -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed
584 mkIEThingAbs (n, av, Nothing ) = (IEThingAbs n, trimAvail av n)
585 mkIEThingAbs (n, av, Just parent) = (IEThingAbs n, AvailTC parent [n])
588 catMaybeErr :: [MaybeErr err a] -> [a]
589 catMaybeErr ms = [ a | Succeeded a <- ms ]
592 %************************************************************************
596 %************************************************************************
599 -- | make a 'GlobalRdrEnv' where all the elements point to the same
600 -- import declaration (useful for "hiding" imports, or imports with
602 gresFromAvails :: Provenance -> [AvailInfo] -> [GlobalRdrElt]
603 gresFromAvails prov avails
604 = concatMap (gresFromAvail (const prov)) avails
606 gresFromAvail :: (Name -> Provenance) -> AvailInfo -> [GlobalRdrElt]
607 gresFromAvail prov_fn avail
608 = [ GRE {gre_name = n,
609 gre_par = availParent n avail,
610 gre_prov = prov_fn n}
611 | n <- availNames avail ]
613 greAvail :: GlobalRdrElt -> AvailInfo
614 greAvail gre = mkUnitAvail (gre_name gre) (gre_par gre)
616 mkUnitAvail :: Name -> Parent -> AvailInfo
617 mkUnitAvail me (ParentIs p) = AvailTC p [me]
618 mkUnitAvail me NoParent | isTyConName me = AvailTC me [me]
619 | otherwise = Avail me
621 plusAvail (Avail n1) (Avail n2) = Avail n1
622 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
623 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
625 availParent :: Name -> AvailInfo -> Parent
626 availParent n (Avail _) = NoParent
627 availParent n (AvailTC m ms) | n==m = NoParent
628 | otherwise = ParentIs m
630 trimAvail :: AvailInfo -> Name -> AvailInfo
631 trimAvail (Avail n) m = Avail n
632 trimAvail (AvailTC n ns) m = ASSERT( m `elem` ns) AvailTC n [m]
634 -- | filters 'AvailInfo's by the given predicate
635 filterAvails :: (Name -> Bool) -> [AvailInfo] -> [AvailInfo]
636 filterAvails keep avails = foldr (filterAvail keep) [] avails
638 -- | filters an 'AvailInfo' by the given predicate
639 filterAvail :: (Name -> Bool) -> AvailInfo -> [AvailInfo] -> [AvailInfo]
640 filterAvail keep ie rest =
642 Avail n | keep n -> ie : rest
645 let left = filter keep ns in
646 if null left then rest else AvailTC tc left : rest
648 -- | Given an import/export spec, construct the appropriate 'GlobalRdrElt's.
649 gresFromIE :: ImpDeclSpec -> (LIE Name, AvailInfo) -> [GlobalRdrElt]
650 gresFromIE decl_spec (L loc ie, avail)
651 = gresFromAvail prov_fn avail
653 is_explicit = case ie of
654 IEThingAll name -> \n -> n==name
656 prov_fn name = Imported [imp_spec]
658 imp_spec = ImpSpec { is_decl = decl_spec, is_item = item_spec }
659 item_spec = ImpSome { is_explicit = is_explicit name, is_iloc = loc }
661 mkChildEnv :: [GlobalRdrElt] -> NameEnv [Name]
662 mkChildEnv gres = foldr add emptyNameEnv gres
664 add (GRE { gre_name = n, gre_par = ParentIs p }) env = extendNameEnv_C (++) env p [n]
665 add other_gre env = env
667 findChildren :: NameEnv [Name] -> Name -> [Name]
668 findChildren env n = lookupNameEnv env n `orElse` []
671 ---------------------------------------
674 All this AvailEnv stuff is hardly used; only in a very small
675 part of RnNames. Todo: remove?
676 ---------------------------------------
679 type AvailEnv = NameEnv AvailInfo -- Maps a Name to the AvailInfo that contains it
681 emptyAvailEnv :: AvailEnv
682 emptyAvailEnv = emptyNameEnv
684 unitAvailEnv :: AvailInfo -> AvailEnv
685 unitAvailEnv a = unitNameEnv (availName a) a
687 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
688 plusAvailEnv = plusNameEnv_C plusAvail
690 availEnvElts :: AvailEnv -> [AvailInfo]
691 availEnvElts = nameEnvElts
693 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
694 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
696 mkAvailEnv :: [AvailInfo] -> AvailEnv
697 -- 'avails' may have several items with the same availName
698 -- E.g import Ix( Ix(..), index )
699 -- will give Ix(Ix,index,range) and Ix(index)
700 -- We want to combine these; addAvail does that
701 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
703 -- After combining the avails, we need to ensure that the parent name is the
704 -- first entry in the list of subnames, if it is included at all. (Subsequent
705 -- functions rely on that.)
706 normaliseAvail :: AvailInfo -> AvailInfo
707 normaliseAvail avail@(Avail _) = avail
708 normaliseAvail (AvailTC name subs) = AvailTC name subs'
710 subs' = if name `elem` subs then name : (delete name subs) else subs
712 -- | combines 'AvailInfo's from the same family
713 nubAvails :: [AvailInfo] -> [AvailInfo]
714 nubAvails avails = map normaliseAvail . nameEnvElts . mkAvailEnv $ avails
718 %************************************************************************
720 \subsection{Export list processing}
722 %************************************************************************
724 Processing the export list.
726 You might think that we should record things that appear in the export
727 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
728 wrong. We do check (here) that they are in scope, but there is no
729 need to slurp in their actual declaration (which is what
730 @addOccurrenceName@ forces).
732 Indeed, doing so would big trouble when compiling @PrelBase@, because
733 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
734 @ConcBase.StateAndSynchVar#@, and so on...
737 type ExportAccum -- The type of the accumulating parameter of
738 -- the main worker function in rnExports
739 = ([LIE Name], -- Export items with Names
740 ExportOccMap, -- Tracks exported occurrence names
741 [AvailInfo]) -- The accumulated exported stuff
744 emptyExportAccum = ([], emptyOccEnv, [])
746 type ExportOccMap = OccEnv (Name, IE RdrName)
747 -- Tracks what a particular exported OccName
748 -- in an export list refers to, and which item
749 -- it came from. It's illegal to export two distinct things
750 -- that have the same occurrence name
752 rnExports :: Bool -- False => no 'module M(..) where' header at all
753 -> Maybe [LIE RdrName] -- Nothing => no explicit export list
757 -- Complains if two distinct exports have same OccName
758 -- Warns about identical exports.
759 -- Complains about exports items not in scope
761 rnExports explicit_mod exports
762 tcg_env@(TcGblEnv { tcg_mod = this_mod,
763 tcg_rdr_env = rdr_env,
764 tcg_imports = imports })
766 -- If the module header is omitted altogether, then behave
767 -- as if the user had written "module Main(main) where..."
768 -- EXCEPT in interactive mode, when we behave as if he had
769 -- written "module Main where ..."
770 -- Reason: don't want to complain about 'main' not in scope
771 -- in interactive mode
774 | explicit_mod = exports
775 | ghcLink dflags == LinkInMemory = Nothing
776 | otherwise = Just ([noLoc (IEVar main_RDR_Unqual)])
777 -- ToDo: the 'noLoc' here is unhelpful if 'main'
778 -- turns out to be out of scope
780 ; (rn_exports, avails) <- exports_from_avail real_exports rdr_env imports this_mod
781 ; let final_avails = nubAvails avails -- Combine families
783 ; return (tcg_env { tcg_exports = final_avails,
784 tcg_rn_exports = case tcg_rn_exports tcg_env of
786 Just _ -> rn_exports,
787 tcg_dus = tcg_dus tcg_env `plusDU`
788 usesOnly (availsToNameSet final_avails) }) }
791 exports_from_avail :: Maybe [LIE RdrName]
792 -- Nothing => no explicit export list
796 -> RnM (Maybe [LIE Name], [AvailInfo])
798 exports_from_avail Nothing rdr_env imports this_mod
799 = -- The same as (module M) where M is the current module name,
800 -- so that's how we handle it.
802 avails = [ greAvail gre | gre <- globalRdrEnvElts rdr_env,
805 return (Nothing, avails)
807 exports_from_avail (Just rdr_items) rdr_env imports this_mod
808 = do (ie_names, _, exports) <- foldlM do_litem emptyExportAccum rdr_items
810 return (Just ie_names, exports)
812 do_litem :: ExportAccum -> LIE RdrName -> RnM ExportAccum
813 do_litem acc lie = setSrcSpan (getLoc lie) (exports_from_item acc lie)
815 kids_env :: NameEnv [Name] -- Maps a parent to its in-scope children
816 kids_env = mkChildEnv (globalRdrEnvElts rdr_env)
818 imported_modules = [ qual_name
819 | (_, xs) <- moduleEnvElts $ imp_mods imports,
820 (qual_name, _, _) <- xs ]
822 exports_from_item :: ExportAccum -> LIE RdrName -> RnM ExportAccum
823 exports_from_item acc@(ie_names, occs, exports)
824 (L loc ie@(IEModuleContents mod))
825 | let earlier_mods = [ mod | (L _ (IEModuleContents mod)) <- ie_names ]
826 , mod `elem` earlier_mods -- Duplicate export of M
827 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
828 warnIf warn_dup_exports (dupModuleExport mod) ;
832 = do { implicit_prelude <- doptM Opt_ImplicitPrelude
833 ; let { exportValid = (mod `elem` imported_modules)
834 || (moduleName this_mod == mod)
835 ; gres = filter (isModuleExported implicit_prelude mod)
836 (globalRdrEnvElts rdr_env)
839 ; checkErr exportValid (moduleNotImported mod)
840 ; warnIf (exportValid && null gres) (nullModuleExport mod)
842 ; occs' <- check_occs ie occs (map gre_name gres)
843 -- This check_occs not only finds conflicts
844 -- between this item and others, but also
845 -- internally within this item. That is, if
846 -- 'M.x' is in scope in several ways, we'll have
847 -- several members of mod_avails with the same
849 ; return (L loc (IEModuleContents mod) : ie_names,
850 occs', map greAvail gres ++ exports) }
852 exports_from_item acc@(lie_names, occs, exports) (L loc ie)
854 = do new_ie <- lookup_doc_ie ie
855 return (L loc new_ie : lie_names, occs, exports)
858 = do (new_ie, avail) <- lookup_ie ie
859 if isUnboundName (ieName new_ie)
860 then return acc -- Avoid error cascade
863 occs' <- check_occs ie occs (availNames avail)
865 return (L loc new_ie : lie_names, occs', avail : exports)
868 lookup_ie :: IE RdrName -> RnM (IE Name, AvailInfo)
869 lookup_ie (IEVar rdr)
870 = do gre <- lookupGreRn rdr
871 return (IEVar (gre_name gre), greAvail gre)
873 lookup_ie (IEThingAbs rdr)
874 = do gre <- lookupGreRn rdr
875 let name = gre_name gre
877 NoParent -> return (IEThingAbs name,
879 ParentIs p -> return (IEThingAbs name,
882 lookup_ie ie@(IEThingAll rdr)
883 = do name <- lookupGlobalOccRn rdr
884 let kids = findChildren kids_env name
886 (if (isTyConName name) then addWarn (dodgyExportWarn name)
887 -- This occurs when you export T(..), but
888 -- only import T abstractly, or T is a synonym.
889 else addErr (exportItemErr ie))
891 return (IEThingAll name, AvailTC name (name:kids))
893 lookup_ie ie@(IEThingWith rdr sub_rdrs)
894 = do name <- lookupGlobalOccRn rdr
895 if isUnboundName name
896 then return (IEThingWith name [], AvailTC name [name])
898 let env = mkOccEnv [ (nameOccName s, s)
899 | s <- findChildren kids_env name ]
900 mb_names = map (lookupOccEnv env . rdrNameOcc) sub_rdrs
901 if any isNothing mb_names
902 then do addErr (exportItemErr ie)
903 return (IEThingWith name [], AvailTC name [name])
904 else do let names = catMaybes mb_names
905 optTyFam <- doptM Opt_TypeFamilies
906 when (not optTyFam && any isTyConName names) $
907 addErr (typeItemErr ( head
910 (text "in export list"))
911 return (IEThingWith name names, AvailTC name (name:names))
913 lookup_ie ie = panic "lookup_ie" -- Other cases covered earlier
916 lookup_doc_ie :: IE RdrName -> RnM (IE Name)
917 lookup_doc_ie (IEGroup lev doc) = do rn_doc <- rnHsDoc doc
918 return (IEGroup lev rn_doc)
919 lookup_doc_ie (IEDoc doc) = do rn_doc <- rnHsDoc doc
920 return (IEDoc rn_doc)
921 lookup_doc_ie (IEDocNamed str) = return (IEDocNamed str)
922 lookup_doc_ie ie = panic "lookup_doc_ie" -- Other cases covered earlier
925 isDoc (IEDoc _) = True
926 isDoc (IEDocNamed _) = True
927 isDoc (IEGroup _ _) = True
930 -------------------------------
931 isModuleExported :: Bool -> ModuleName -> GlobalRdrElt -> Bool
932 -- True if the thing is in scope *both* unqualified, *and* with qualifier M
933 isModuleExported implicit_prelude mod (GRE { gre_name = name, gre_prov = prov })
934 | implicit_prelude && isBuiltInSyntax name = False
935 -- Optimisation: filter out names for built-in syntax
936 -- They just clutter up the environment (esp tuples), and the parser
937 -- will generate Exact RdrNames for them, so the cluttered
938 -- envt is no use. To avoid doing this filter all the time,
939 -- we use -fno-implicit-prelude as a clue that the filter is
940 -- worth while. Really, it's only useful for GHC.Base and GHC.Tuple.
942 -- It's worth doing because it makes the environment smaller for
943 -- every module that imports the Prelude
946 LocalDef -> moduleName (nameModule name) == mod
947 Imported is -> any unQualSpecOK is && any (qualSpecOK mod) is
949 -------------------------------
950 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
951 check_occs ie occs names
952 = foldlM check occs names
955 = case lookupOccEnv occs name_occ of
956 Nothing -> return (extendOccEnv occs name_occ (name, ie))
959 | name == name' -- Duplicate export
960 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
961 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
964 | otherwise -- Same occ name but different names: an error
965 -> do { global_env <- getGlobalRdrEnv ;
966 addErr (exportClashErr global_env name' name ie' ie) ;
969 name_occ = nameOccName name
972 %*********************************************************
976 %*********************************************************
979 finishDeprecations :: DynFlags -> Maybe DeprecTxt
980 -> TcGblEnv -> RnM TcGblEnv
981 -- (a) Report usasge of deprecated imports
982 -- (b) If the whole module is deprecated, update tcg_deprecs
983 -- All this happens only once per module
984 finishDeprecations dflags mod_deprec tcg_env
985 = do { (eps,hpt) <- getEpsAndHpt
986 ; ifOptM Opt_WarnDeprecations $
987 mapM_ (check hpt (eps_PIT eps)) all_gres
988 -- By this time, typechecking is complete,
989 -- so the PIT is fully populated
991 -- Deal with a module deprecation; it overrides all existing deprecs
992 ; let new_deprecs = case mod_deprec of
993 Just txt -> DeprecAll txt
994 Nothing -> tcg_deprecs tcg_env
995 ; return (tcg_env { tcg_deprecs = new_deprecs }) }
997 used_names = allUses (tcg_dus tcg_env)
998 -- Report on all deprecated uses; hence allUses
999 all_gres = globalRdrEnvElts (tcg_rdr_env tcg_env)
1001 check hpt pit gre@(GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
1002 | name `elemNameSet` used_names
1003 , Just deprec_txt <- lookupImpDeprec dflags hpt pit gre
1004 = addWarnAt (importSpecLoc imp_spec)
1005 (sep [ptext SLIT("Deprecated use of") <+>
1006 pprNonVarNameSpace (occNameSpace (nameOccName name)) <+>
1008 (parens imp_msg) <> colon,
1011 name_mod = nameModule name
1012 imp_mod = importSpecModule imp_spec
1013 imp_msg = ptext SLIT("imported from") <+> ppr imp_mod <> extra
1014 extra | imp_mod == moduleName name_mod = empty
1015 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
1017 check hpt pit ok_gre = return () -- Local, or not used, or not deprectated
1018 -- The Imported pattern-match: don't deprecate locally defined names
1019 -- For a start, we may be exporting a deprecated thing
1020 -- Also we may use a deprecated thing in the defn of another
1021 -- deprecated things. We may even use a deprecated thing in
1022 -- the defn of a non-deprecated thing, when changing a module's
1025 lookupImpDeprec :: DynFlags -> HomePackageTable -> PackageIfaceTable
1026 -> GlobalRdrElt -> Maybe DeprecTxt
1027 -- The name is definitely imported, so look in HPT, PIT
1028 lookupImpDeprec dflags hpt pit gre
1029 = case lookupIfaceByModule dflags hpt pit (nameModule name) of
1030 Just iface -> mi_dep_fn iface name `mplus` -- Bleat if the thing, *or
1032 ParentIs p -> mi_dep_fn iface p -- its parent*, is deprec'd
1035 Nothing -> Nothing -- See Note [Used names with interface not loaded]
1040 Note [Used names with interface not loaded]
1041 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1042 By now all the interfaces should have been loaded,
1043 because reportDeprecations happens after typechecking.
1044 However, it's still (just) possible to to find a used
1045 Name whose interface hasn't been loaded:
1047 a) It might be a WiredInName; in that case we may not load
1048 its interface (although we could).
1050 b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
1051 These are seen as "used" by the renamer (if -fno-implicit-prelude)
1052 is on), but the typechecker may discard their uses
1053 if in fact the in-scope fromRational is GHC.Read.fromRational,
1054 (see tcPat.tcOverloadedLit), and the typechecker sees that the type
1055 is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
1056 In that obscure case it won't force the interface in.
1058 In both cases we simply don't permit deprecations;
1059 this is, after all, wired-in stuff.
1062 %*********************************************************
1066 %*********************************************************
1069 reportUnusedNames :: Maybe [LIE RdrName] -- Export list
1070 -> TcGblEnv -> RnM ()
1071 reportUnusedNames export_decls gbl_env
1072 = do { traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env)))
1073 ; warnUnusedTopBinds unused_locals
1074 ; warnUnusedModules unused_imp_mods
1075 ; warnUnusedImports unused_imports
1076 ; warnDuplicateImports defined_and_used
1077 ; printMinimalImports minimal_imports }
1079 used_names :: NameSet
1080 used_names = findUses (tcg_dus gbl_env) emptyNameSet
1081 -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
1084 -- Collect the defined names from the in-scope environment
1085 defined_names :: [GlobalRdrElt]
1086 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
1088 -- Note that defined_and_used, defined_but_not_used
1089 -- are both [GRE]; that's why we need defined_and_used
1090 -- rather than just used_names
1091 defined_and_used, defined_but_not_used :: [GlobalRdrElt]
1092 (defined_and_used, defined_but_not_used)
1093 = partition (gre_is_used used_names) defined_names
1095 kids_env = mkChildEnv defined_names
1096 -- This is done in mkExports too; duplicated work
1098 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
1099 gre_is_used used_names (GRE {gre_name = name})
1100 = name `elemNameSet` used_names
1101 || any (`elemNameSet` used_names) (findChildren kids_env name)
1102 -- A use of C implies a use of T,
1103 -- if C was brought into scope by T(..) or T(C)
1105 -- Filter out the ones that are
1106 -- (a) defined in this module, and
1107 -- (b) not defined by a 'deriving' clause
1108 -- The latter have an Internal Name, so we can filter them out easily
1109 unused_locals :: [GlobalRdrElt]
1110 unused_locals = filter is_unused_local defined_but_not_used
1111 is_unused_local :: GlobalRdrElt -> Bool
1112 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
1114 unused_imports :: [GlobalRdrElt]
1115 unused_imports = mapCatMaybes unused_imp defined_but_not_used
1116 unused_imp :: GlobalRdrElt -> Maybe GlobalRdrElt -- Result has trimmed Imported provenances
1117 unused_imp gre@(GRE {gre_prov = LocalDef}) = Nothing
1118 unused_imp gre@(GRE {gre_prov = Imported imp_specs})
1119 | null trimmed_specs = Nothing
1120 | otherwise = Just (gre {gre_prov = Imported trimmed_specs})
1122 trimmed_specs = filter report_if_unused imp_specs
1124 -- To figure out the minimal set of imports, start with the things
1125 -- that are in scope (i.e. in gbl_env). Then just combine them
1126 -- into a bunch of avails, so they are properly grouped
1128 -- BUG WARNING: this does not deal properly with qualified imports!
1129 minimal_imports :: FiniteMap ModuleName AvailEnv
1130 minimal_imports0 = foldr add_expall emptyFM expall_mods
1131 minimal_imports1 = foldr add_name minimal_imports0 defined_and_used
1132 minimal_imports = foldr add_inst_mod minimal_imports1 direct_import_mods
1133 -- The last line makes sure that we retain all direct imports
1134 -- even if we import nothing explicitly.
1135 -- It's not necessarily redundant to import such modules. Consider
1139 -- The import M() is not *necessarily* redundant, even if
1140 -- we suck in no instance decls from M (e.g. it contains
1141 -- no instance decls, or This contains no code). It may be
1142 -- that we import M solely to ensure that M's orphan instance
1143 -- decls (or those in its imports) are visible to people who
1144 -- import This. Sigh.
1145 -- There's really no good way to detect this, so the error message
1146 -- in RnEnv.warnUnusedModules is weakened instead
1148 -- We've carefully preserved the provenance so that we can
1149 -- construct minimal imports that import the name by (one of)
1150 -- the same route(s) as the programmer originally did.
1151 add_name gre@(GRE {gre_prov = Imported (imp_spec:_)}) acc
1152 = addToFM_C plusAvailEnv acc
1153 (importSpecModule imp_spec) (unitAvailEnv (greAvail gre))
1154 add_name gre acc = acc -- Local
1156 -- Modules mentioned as 'module M' in the export list
1157 expall_mods = case export_decls of
1159 Just es -> [m | L _ (IEModuleContents m) <- es]
1161 -- This is really bogus. The idea is that if we see 'module M' in
1162 -- the export list we must retain the import decls that drive it
1163 -- If we aren't careful we might see
1164 -- module A( module M ) where
1167 -- and suppose that N exports everything that M does. Then we
1168 -- must not drop the import of M even though N brings it all into
1171 -- BUG WARNING: 'module M' exports aside, what if M.x is mentioned?!
1173 -- The reason that add_expall is bogus is that it doesn't take
1174 -- qualified imports into account. But it's an improvement.
1175 add_expall mod acc = addToFM_C plusAvailEnv acc mod emptyAvailEnv
1177 add_inst_mod (mod, _) acc
1178 | mod_name `elemFM` acc = acc -- We import something already
1179 | otherwise = addToFM acc mod_name emptyAvailEnv
1181 mod_name = moduleName mod
1182 -- Add an empty collection of imports for a module
1183 -- from which we have sucked only instance decls
1185 imports = tcg_imports gbl_env
1187 direct_import_mods :: [(Module, [(ModuleName, Bool, SrcSpan)])]
1188 -- See the type of the imp_mods for this triple
1189 direct_import_mods = moduleEnvElts (imp_mods imports)
1191 -- unused_imp_mods are the directly-imported modules
1192 -- that are not mentioned in minimal_imports1
1193 -- [Note: not 'minimal_imports', because that includes directly-imported
1194 -- modules even if we use nothing from them; see notes above]
1196 -- BUG WARNING: this code is generally buggy
1197 unused_imp_mods :: [(ModuleName, SrcSpan)]
1198 unused_imp_mods = [(mod_name,loc)
1199 | (mod, xs) <- direct_import_mods,
1200 (_, no_imp, loc) <- xs,
1201 let mod_name = moduleName mod,
1202 not (mod_name `elemFM` minimal_imports1),
1205 -- The not no_imp part is not to complain about
1206 -- import M (), which is an idiom for importing
1207 -- instance declarations
1209 module_unused :: ModuleName -> Bool
1210 module_unused mod = any (((==) mod) . fst) unused_imp_mods
1212 report_if_unused :: ImportSpec -> Bool
1213 -- Do we want to report this as an unused import?
1214 report_if_unused (ImpSpec {is_decl = d, is_item = i})
1215 = not (module_unused (is_mod d)) -- Not if we've already said entire import is unused
1216 && isExplicitItem i -- Only if the import was explicit
1218 ---------------------
1219 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
1220 -- Given the GREs for names that are used, figure out which imports
1221 -- could be omitted without changing the top-level environment.
1223 -- NB: Given import Foo( T )
1224 -- import qualified Foo
1225 -- we do not report a duplicate import, even though Foo.T is brought
1226 -- into scope by both, because there's nothing you can *omit* without
1227 -- changing the top-level environment. So we complain only if it's
1228 -- explicitly named in both imports or neither.
1230 -- Furthermore, we complain about Foo.T only if
1231 -- there is no complaint about (unqualified) T
1233 warnDuplicateImports gres
1234 = ifOptM Opt_WarnUnusedImports $
1235 sequence_ [ warn name pr
1236 | GRE { gre_name = name, gre_prov = Imported imps } <- gres
1237 , pr <- redundants imps ]
1239 warn name (red_imp, cov_imp)
1240 = addWarnAt (importSpecLoc red_imp)
1241 (vcat [ptext SLIT("Redundant import of:") <+> quotes pp_name,
1242 ptext SLIT("It is also") <+> ppr cov_imp])
1244 pp_name | is_qual red_decl = ppr (is_as red_decl) <> dot <> ppr occ
1245 | otherwise = ppr occ
1246 occ = nameOccName name
1247 red_decl = is_decl red_imp
1249 redundants :: [ImportSpec] -> [(ImportSpec,ImportSpec)]
1250 -- The returned pair is (redundant-import, covering-import)
1252 = [ (red_imp, cov_imp)
1254 , isExplicitItem (is_item red_imp)
1255 -- Complain only about redundant imports
1256 -- mentioned explicitly by the user
1257 , cov_imp <- take 1 (filter (covers red_imp) imps) ]
1258 -- The 'take 1' picks the first offending group
1259 -- for this particular name
1261 -- "red_imp" is a putative redundant import
1262 -- "cov_imp" potentially covers it
1263 -- This test decides whether red_imp could be dropped
1265 -- NOTE: currently the test does not warn about
1268 -- even if the same underlying 'x' is involved, because dropping
1269 -- either import would change the qualified names in scope (M.x, N.x)
1270 -- But if the qualified names aren't used, the import is indeed redundant
1271 -- Sadly we don't know that. Oh well.
1272 covers red_imp@(ImpSpec { is_decl = red_decl, is_item = red_item })
1273 cov_imp@(ImpSpec { is_decl = cov_decl, is_item = cov_item })
1274 | red_loc == cov_loc
1275 = False -- Ignore diagonal elements
1276 | not (is_as red_decl == is_as cov_decl)
1277 = False -- They bring into scope different qualified names
1278 | not (is_qual red_decl) && is_qual cov_decl
1279 = False -- Covering one doesn't bring unqualified name into scope
1281 = not (isExplicitItem cov_item) -- Redundant one is selective and covering one isn't
1282 || red_later -- or both are explicit; tie-break using red_later
1285 = not cov_selective -- Redundant one is selective and covering one isn't
1286 || red_later -- Both are explicit; tie-break using red_later
1288 = not cov_selective -- Neither import is selective
1289 && (is_mod red_decl == is_mod cov_decl) -- They import the same module
1290 && red_later -- Tie-break
1293 red_loc = importSpecLoc red_imp
1294 cov_loc = importSpecLoc cov_imp
1295 red_later = red_loc > cov_loc
1297 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
1298 printMinimalImports :: FiniteMap ModuleName AvailEnv -- Minimal imports
1300 printMinimalImports imps
1301 = ifOptM Opt_D_dump_minimal_imports $ do {
1303 mod_ies <- initIfaceTcRn $ mapM to_ies (fmToList imps) ;
1304 this_mod <- getModule ;
1305 rdr_env <- getGlobalRdrEnv ;
1306 dflags <- getDOpts ;
1307 liftIO $ do h <- openFile (mkFilename this_mod) WriteMode
1308 printForUser h (mkPrintUnqualified dflags rdr_env)
1309 (vcat (map ppr_mod_ie mod_ies))
1312 mkFilename this_mod = moduleNameString (moduleName this_mod) ++ ".imports"
1313 ppr_mod_ie (mod_name, ies)
1314 | mod_name == moduleName pRELUDE
1316 | null ies -- Nothing except instances comes from here
1317 = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("() -- Instances only")
1319 = ptext SLIT("import") <+> ppr mod_name <>
1320 parens (fsep (punctuate comma (map ppr ies)))
1322 to_ies (mod, avail_env) = do ies <- mapM to_ie (availEnvElts avail_env)
1325 to_ie :: AvailInfo -> IfG (IE Name)
1326 -- The main trick here is that if we're importing all the constructors
1327 -- we want to say "T(..)", but if we're importing only a subset we want
1328 -- to say "T(A,B,C)". So we have to find out what the module exports.
1329 to_ie (Avail n) = return (IEVar n)
1330 to_ie (AvailTC n [m]) = ASSERT( n==m )
1331 return (IEThingAbs n)
1332 to_ie (AvailTC n ns) = do
1333 iface <- loadSysInterface doc n_mod
1334 case [xs | (m,as) <- mi_exports iface,
1337 x == nameOccName n] of
1338 [xs] | all_used xs -> return (IEThingAll n)
1339 | otherwise -> return (IEThingWith n (filter (/= n) ns))
1340 other -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
1343 all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
1344 doc = text "Compute minimal imports from" <+> ppr n
1345 n_mod = nameModule n
1349 %************************************************************************
1353 %************************************************************************
1356 badImportItemErr iface decl_spec ie
1357 = sep [ptext SLIT("Module"), quotes (ppr (is_mod decl_spec)), source_import,
1358 ptext SLIT("does not export"), quotes (ppr ie)]
1360 source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
1363 illegalImportItemErr = ptext SLIT("Illegal import item")
1365 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
1366 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
1369 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
1370 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructors or class methods,"),
1371 ptext SLIT("but it has none") ]
1373 exportItemErr export_item
1374 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
1375 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
1377 typeItemErr name wherestr
1378 = sep [ ptext SLIT("Using 'type' tag on") <+> quotes (ppr name) <+> wherestr,
1379 ptext SLIT("Use -XTypeFamilies to enable this extension") ]
1381 exportClashErr :: GlobalRdrEnv -> Name -> Name -> IE RdrName -> IE RdrName
1383 exportClashErr global_env name1 name2 ie1 ie2
1384 = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
1385 , ppr_export ie1' name1'
1386 , ppr_export ie2' name2' ]
1388 occ = nameOccName name1
1389 ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+>
1390 quotes (ppr name) <+> pprNameProvenance (get_gre name))
1392 -- get_gre finds a GRE for the Name, so that we can show its provenance
1394 = case lookupGRE_Name global_env name of
1396 [] -> pprPanic "exportClashErr" (ppr name)
1397 get_loc name = nameSrcLoc $ gre_name $ get_gre name
1398 (name1', ie1', name2', ie2') = if get_loc name1 < get_loc name2
1399 then (name1, ie1, name2, ie2)
1400 else (name2, ie2, name1, ie1)
1402 addDupDeclErr :: Name -> Name -> TcRn ()
1403 addDupDeclErr name_a name_b
1404 = addErrAt (srcLocSpan loc2) $
1405 vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
1406 ptext SLIT("Declared at:") <+> vcat [ppr (nameSrcLoc name1), ppr loc2]]
1408 loc2 = nameSrcLoc name2
1409 (name1,name2) | nameSrcLoc name_a > nameSrcLoc name_b = (name_b,name_a)
1410 | otherwise = (name_a,name_b)
1411 -- Report the error at the later location
1413 dupExportWarn occ_name ie1 ie2
1414 = hsep [quotes (ppr occ_name),
1415 ptext SLIT("is exported by"), quotes (ppr ie1),
1416 ptext SLIT("and"), quotes (ppr ie2)]
1419 = hsep [ptext SLIT("Duplicate"),
1420 quotes (ptext SLIT("Module") <+> ppr mod),
1421 ptext SLIT("in export list")]
1423 moduleNotImported :: ModuleName -> SDoc
1424 moduleNotImported mod
1425 = ptext SLIT("The export item `module") <+> ppr mod <>
1426 ptext SLIT("' is not imported")
1428 nullModuleExport mod
1429 = ptext SLIT("The export item `module") <+> ppr mod <> ptext SLIT("' exports nothing")
1431 moduleDeprec mod txt
1432 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),
1436 = ptext SLIT("Module `Prelude' implicitly imported")