2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnNames]{Extracting imported and top-level names in scope}
8 rnImports, getLocalNonValBinders,
9 rnExports, extendGlobalRdrEnvRn,
11 reportUnusedNames, finishWarnings,
14 #include "HsVersions.h"
18 import TcEnv ( isBrackStage )
20 import RnHsDoc ( rnHsDoc )
21 import IfaceEnv ( ifaceExportNames )
22 import LoadIface ( loadSrcInterface, loadSysInterface )
25 import HeaderInfo ( mkPrelImports )
40 import Data.List ( partition, (\\), delete )
41 import qualified Data.Set as Set
45 import qualified Data.Map as Map
50 %************************************************************************
54 %************************************************************************
57 rnImports :: [LImportDecl RdrName]
58 -> RnM ([LImportDecl Name], GlobalRdrEnv, ImportAvails,AnyHpcUsage)
61 -- PROCESS IMPORT DECLS
62 -- Do the non {- SOURCE -} ones first, so that we get a helpful
63 -- warning for {- SOURCE -} ones that are unnecessary
64 = do this_mod <- getModule
65 implicit_prelude <- doptM Opt_ImplicitPrelude
66 let prel_imports = mkPrelImports (moduleName this_mod) implicit_prelude imports
67 (source, ordinary) = partition is_source_import imports
68 is_source_import (L _ (ImportDecl _ _ is_boot _ _ _)) = is_boot
70 ifOptM Opt_WarnImplicitPrelude (
71 when (notNull prel_imports) $ addWarn (implicitPreludeWarn)
74 stuff1 <- mapM (rnImportDecl this_mod True) prel_imports
75 stuff2 <- mapM (rnImportDecl this_mod False) ordinary
76 stuff3 <- mapM (rnImportDecl this_mod False) source
77 let (decls, rdr_env, imp_avails, hpc_usage) = combine (stuff1 ++ stuff2 ++ stuff3)
78 return (decls, rdr_env, imp_avails, hpc_usage)
81 combine :: [(LImportDecl Name, GlobalRdrEnv, ImportAvails,AnyHpcUsage)]
82 -> ([LImportDecl Name], GlobalRdrEnv, ImportAvails,AnyHpcUsage)
83 combine = foldr plus ([], emptyGlobalRdrEnv, emptyImportAvails,False)
84 where plus (decl, gbl_env1, imp_avails1,hpc_usage1)
85 (decls, gbl_env2, imp_avails2,hpc_usage2)
87 gbl_env1 `plusGlobalRdrEnv` gbl_env2,
88 imp_avails1 `plusImportAvails` imp_avails2,
89 hpc_usage1 || hpc_usage2)
91 rnImportDecl :: Module -> Bool
92 -> LImportDecl RdrName
93 -> RnM (LImportDecl Name, GlobalRdrEnv, ImportAvails,AnyHpcUsage)
95 rnImportDecl this_mod implicit_prelude (L loc (ImportDecl loc_imp_mod_name mb_pkg want_boot
96 qual_only as_mod imp_details))
99 when (isJust mb_pkg) $ do
100 pkg_imports <- doptM Opt_PackageImports
101 when (not pkg_imports) $ addErr packageImportErr
103 -- If there's an error in loadInterface, (e.g. interface
104 -- file not found) we get lots of spurious errors from 'filterImports'
106 imp_mod_name = unLoc loc_imp_mod_name
107 doc = ppr imp_mod_name <+> ptext (sLit "is directly imported")
109 let isExplicit lie = case unLoc lie of
110 IEThingAll _ -> False
114 | all isExplicit lies ->
117 unless implicit_prelude $
118 ifOptM Opt_WarnMissingImportList (addWarn (missingImportListWarn imp_mod_name))
120 iface <- loadSrcInterface doc imp_mod_name want_boot mb_pkg
122 -- Compiler sanity check: if the import didn't say
123 -- {-# SOURCE #-} we should not get a hi-boot file
124 WARN( not want_boot && mi_boot iface, ppr imp_mod_name ) (do
126 -- Issue a user warning for a redundant {- SOURCE -} import
127 -- NB that we arrange to read all the ordinary imports before
128 -- any of the {- SOURCE -} imports.
130 -- in --make and GHCi, the compilation manager checks for this,
131 -- and indeed we shouldn't do it here because the existence of
132 -- the non-boot module depends on the compilation order, which
133 -- is not deterministic. The hs-boot test can show this up.
135 warnIf (want_boot && not (mi_boot iface) && isOneShot (ghcMode dflags))
136 (warnRedundantSourceImport imp_mod_name)
139 imp_mod = mi_module iface
140 warns = mi_warns iface
141 orph_iface = mi_orphan iface
142 has_finsts = mi_finsts iface
145 filtered_exports = filter not_this_mod (mi_exports iface)
146 not_this_mod (mod,_) = mod /= this_mod
147 -- If the module exports anything defined in this module, just
148 -- ignore it. Reason: otherwise it looks as if there are two
149 -- local definition sites for the thing, and an error gets
150 -- reported. Easiest thing is just to filter them out up
151 -- front. This situation only arises if a module imports
152 -- itself, or another module that imported it. (Necessarily,
153 -- this invoves a loop.)
155 -- Tiresome consequence: if you say
160 -- module B( AType ) where
161 -- import {-# SOURCE #-} A( AType )
163 -- then you'll get a 'B does not export AType' message. Oh well.
165 qual_mod_name = case as_mod of
166 Nothing -> imp_mod_name
167 Just another_name -> another_name
168 imp_spec = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,
169 is_dloc = loc, is_as = qual_mod_name }
172 -- Get the total exports from this module
173 total_avails <- ifaceExportNames filtered_exports
175 -- filter the imports according to the import declaration
176 (new_imp_details, gbl_env) <-
177 filterImports iface imp_spec imp_details total_avails
182 -- Compute new transitive dependencies
184 orphans | orph_iface = ASSERT( not (imp_mod `elem` dep_orphs deps) )
185 imp_mod : dep_orphs deps
186 | otherwise = dep_orphs deps
188 finsts | has_finsts = ASSERT( not (imp_mod `elem` dep_finsts deps) )
189 imp_mod : dep_finsts deps
190 | otherwise = dep_finsts deps
192 pkg = modulePackageId (mi_module iface)
194 (dependent_mods, dependent_pkgs)
195 | pkg == thisPackage dflags =
196 -- Imported module is from the home package
197 -- Take its dependent modules and add imp_mod itself
198 -- Take its dependent packages unchanged
200 -- NB: (dep_mods deps) might include a hi-boot file
201 -- for the module being compiled, CM. Do *not* filter
202 -- this out (as we used to), because when we've
203 -- finished dealing with the direct imports we want to
204 -- know if any of them depended on CM.hi-boot, in
205 -- which case we should do the hi-boot consistency
206 -- check. See LoadIface.loadHiBootInterface
207 ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)
210 -- Imported module is from another package
211 -- Dump the dependent modules
212 -- Add the package imp_mod comes from to the dependent packages
213 ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
214 ([], pkg : dep_pkgs deps)
216 -- True <=> import M ()
217 import_all = case imp_details of
218 Just (is_hiding, ls) -> not is_hiding && null ls
221 imports = ImportAvails {
222 imp_mods = unitModuleEnv imp_mod [(qual_mod_name, import_all, loc)],
225 imp_dep_mods = mkModDeps dependent_mods,
226 imp_dep_pkgs = dependent_pkgs
229 -- Complain if we import a deprecated module
230 ifOptM Opt_WarnWarningsDeprecations (
232 WarnAll txt -> addWarn (moduleWarn imp_mod_name txt)
236 let new_imp_decl = L loc (ImportDecl loc_imp_mod_name mb_pkg want_boot
237 qual_only as_mod new_imp_details)
239 return (new_imp_decl, gbl_env, imports, mi_hpc iface)
242 warnRedundantSourceImport :: ModuleName -> SDoc
243 warnRedundantSourceImport mod_name
244 = ptext (sLit "Unnecessary {-# SOURCE #-} in the import of module")
245 <+> quotes (ppr mod_name)
249 %************************************************************************
251 importsFromLocalDecls
253 %************************************************************************
255 From the top-level declarations of this module produce
256 * the lexical environment
258 created by its bindings.
260 Note [Top-level Names in Template Haskell decl quotes]
261 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
262 Consider a Template Haskell declaration quotation like this:
265 When renaming the declarations inside [d| ...|], we treat the
266 top level binders specially in two ways
268 1. We give them an Internal name, not (as usual) an External one.
269 Otherwise the NameCache gets confused by a second allocation of
270 M.f. (We used to invent a fake module ThFake to avoid this, but
271 that had other problems, notably in getting the correct answer for
272 nameIsLocalOrFrom in lookupFixity. So we now leave tcg_module
275 2. We make them *shadow* the outer bindings. If we don't do that,
276 we'll get a complaint when extending the GlobalRdrEnv, saying that
277 there are two bindings for 'f'. There are several tricky points:
279 * This shadowing applies even if the binding for 'f' is in a
280 where-clause, and hence is in the *local* RdrEnv not the *global*
283 * The *qualified* name M.f from the enclosing module must certainly
284 still be available. So we don't nuke it entirely; we just make
285 it seem like qualified import.
287 * We only shadow *External* names (which come from the main module)
288 Do not shadow *Inernal* names because in the bracket
289 [d| class C a where f :: a
291 rnSrcDecls will first call extendGlobalRdrEnvRn with C[f] from the
292 class decl, and *separately* extend the envt with the value binding.
294 3. We find out whether we are inside a [d| ... |] by testing the TH
295 stage. This is a slight hack, because the stage field was really
296 meant for the type checker, and here we are not interested in the
297 fields of Brack, hence the error thunks in thRnBrack.
300 extendGlobalRdrEnvRn :: [AvailInfo]
302 -> RnM (TcGblEnv, TcLclEnv)
303 -- Updates both the GlobalRdrEnv and the FixityEnv
304 -- We return a new TcLclEnv only because we might have to
305 -- delete some bindings from it;
306 -- see Note [Top-level Names in Template Haskell decl quotes]
308 extendGlobalRdrEnvRn avails new_fixities
309 = do { (gbl_env, lcl_env) <- getEnvs
311 ; let rdr_env = tcg_rdr_env gbl_env
312 fix_env = tcg_fix_env gbl_env
314 -- Delete new_occs from global and local envs
315 -- If we are in a TemplateHaskell decl bracket,
316 -- we are going to shadow them
317 -- See Note [Top-level Names in Template Haskell decl quotes]
318 shadowP = isBrackStage stage
319 new_occs = map (nameOccName . gre_name) gres
320 rdr_env1 = transformGREs qual_gre new_occs rdr_env
321 lcl_env1 = lcl_env { tcl_rdr = delListFromOccEnv (tcl_rdr lcl_env) new_occs }
322 (rdr_env2, lcl_env2) | shadowP = (rdr_env1, lcl_env1)
323 | otherwise = (rdr_env, lcl_env)
325 rdr_env3 = foldl extendGlobalRdrEnv rdr_env2 gres
326 fix_env' = foldl extend_fix_env fix_env gres
327 (rdr_env', dups) = findLocalDupsRdrEnv rdr_env3 new_occs
329 gbl_env' = gbl_env { tcg_rdr_env = rdr_env', tcg_fix_env = fix_env' }
331 ; mapM_ addDupDeclErr dups
333 ; traceRn (text "extendGlobalRdrEnvRn" <+> (ppr new_fixities $$ ppr fix_env $$ ppr fix_env'))
334 ; return (gbl_env', lcl_env2) }
336 gres = gresFromAvails LocalDef avails
338 -- If there is a fixity decl for the gre, add it to the fixity env
339 extend_fix_env fix_env gre
340 | Just (L _ fi) <- lookupFsEnv new_fixities (occNameFS occ)
341 = extendNameEnv fix_env name (FixItem occ fi)
346 occ = nameOccName name
348 qual_gre :: GlobalRdrElt -> GlobalRdrElt
349 -- Transform top-level GREs from the module being compiled
350 -- so that they are out of the way of new definitions in a Template
352 -- See Note [Top-level Names in Template Haskell decl quotes]
353 -- Seems like 5 times as much work as it deserves!
355 -- For a LocalDef we make a (fake) qualified imported GRE for a
356 -- local GRE so that the original *qualified* name is still in scope
357 -- but the *unqualified* one no longer is. What a hack!
359 qual_gre gre@(GRE { gre_prov = LocalDef, gre_name = name })
360 | isExternalName name = gre { gre_prov = Imported [imp_spec] }
362 -- Do not shadow Internal (ie Template Haskell) Names
363 -- See Note [Top-level Names in Template Haskell decl quotes]
365 mod = ASSERT2( isExternalName name, ppr name) moduleName (nameModule name)
366 imp_spec = ImpSpec { is_item = ImpAll, is_decl = decl_spec }
367 decl_spec = ImpDeclSpec { is_mod = mod, is_as = mod,
368 is_qual = True, -- Qualified only!
369 is_dloc = srcLocSpan (nameSrcLoc name) }
371 qual_gre gre@(GRE { gre_prov = Imported specs })
372 = gre { gre_prov = Imported (map qual_spec specs) }
374 qual_spec spec@(ImpSpec { is_decl = decl_spec })
375 = spec { is_decl = decl_spec { is_qual = True } }
378 @getLocalDeclBinders@ returns the names for an @HsDecl@. It's
379 used for source code.
381 *** See "THE NAMING STORY" in HsDecls ****
383 Instances of type families
384 ~~~~~~~~~~~~~~~~~~~~~~~~~~
385 Family instances contain data constructors that we need to collect and we also
386 need to descend into the type instances of associated families in class
387 instances. The type constructor of a family instance is a usage occurence.
388 Hence, we don't return it as a subname in 'AvailInfo'; otherwise, we would get
389 a duplicate declaration error.
391 Note [Looking up family names in family instances]
392 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
397 type instance M.T Int = Bool
399 We might think that we can simply use 'lookupOccRn' when processing the type
400 instance to look up 'M.T'. Alas, we can't! The type family declaration is in
401 the *same* HsGroup as the type instance declaration. Hence, as we are
402 currently collecting the binders declared in that HsGroup, these binders will
403 not have been added to the global environment yet.
405 In the case of type classes, this problem does not arise, as a class instance
406 does not define any binders of it's own. So, we simply don't attempt to look
407 up the class names of class instances in 'get_local_binders' below.
409 If we don't look up class instances, can't we get away without looking up type
410 instances, too? No, we can't. Data type instances define data constructors
413 (1) collect those in 'get_local_binders' and
414 (2) we need to get their parent name in 'get_local_binders', too, to
415 produce an appropriate 'AvailTC'.
417 This parent name is exactly the family name of the type instance that is so
418 difficult to look up.
420 We solve this problem as follows:
422 (a) We process all type declarations other than type instances first.
423 (b) Then, we compute a 'GlobalRdrEnv' from the result of the first step.
424 (c) Finally, we process all type instances (both those on the toplevel and
425 those nested in class instances) and check for the family names in the
426 'GlobalRdrEnv' produced in the previous step before using 'lookupOccRn'.
429 getLocalNonValBinders :: HsGroup RdrName -> RnM [AvailInfo]
430 -- Get all the top-level binders bound the group *except*
431 -- for value bindings, which are treated separately
432 -- Specificaly we return AvailInfo for
433 -- type decls (incl constructors and record selectors)
434 -- class decls (including class ops)
437 -- (in hs-boot files) value signatures
439 getLocalNonValBinders group
440 = do { gbl_env <- getGblEnv
441 ; get_local_binders gbl_env group }
443 get_local_binders :: TcGblEnv -> HsGroup RdrName -> RnM [GenAvailInfo Name]
444 get_local_binders gbl_env (HsGroup {hs_valds = ValBindsIn _ val_sigs,
445 hs_tyclds = tycl_decls,
446 hs_instds = inst_decls,
447 hs_fords = foreign_decls })
448 = do { -- separate out the family instance declarations
449 let (tyinst_decls1, tycl_decls_noinsts)
450 = partition (isFamInstDecl . unLoc) tycl_decls
451 tyinst_decls = tyinst_decls1 ++ instDeclATs inst_decls
453 -- process all type/class decls except family instances
454 ; tc_names <- mapM new_tc tycl_decls_noinsts
456 -- create a temporary rdr env of the type binders
457 ; let tc_gres = gresFromAvails LocalDef tc_names
458 tc_name_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv tc_gres
460 -- process all family instances
461 ; ti_names <- mapM (new_ti tc_name_env) tyinst_decls
463 -- finish off with value binder in case of a hs-boot file
464 ; val_names <- mapM new_simple val_bndrs
465 ; return (val_names ++ tc_names ++ ti_names) }
467 is_hs_boot = isHsBoot (tcg_src gbl_env) ;
469 for_hs_bndrs :: [Located RdrName]
470 for_hs_bndrs = [nm | L _ (ForeignImport nm _ _) <- foreign_decls]
472 -- In a hs-boot file, the value binders come from the
473 -- *signatures*, and there should be no foreign binders
474 val_bndrs :: [Located RdrName]
475 val_bndrs | is_hs_boot = [nm | L _ (TypeSig nm _) <- val_sigs]
476 | otherwise = for_hs_bndrs
478 new_simple :: Located RdrName -> RnM (GenAvailInfo Name)
479 new_simple rdr_name = do
480 nm <- newTopSrcBinder rdr_name
483 new_tc tc_decl -- NOT for type/data instances
484 = do { main_name <- newTopSrcBinder main_rdr
485 ; sub_names <- mapM newTopSrcBinder sub_rdrs
486 ; return (AvailTC main_name (main_name : sub_names)) }
488 (main_rdr : sub_rdrs) = hsTyClDeclBinders tc_decl
490 new_ti tc_name_env ti_decl -- ONLY for type/data instances
491 = do { main_name <- lookupFamInstDeclBndr tc_name_env main_rdr
492 ; sub_names <- mapM newTopSrcBinder sub_rdrs
493 ; return (AvailTC main_name sub_names) }
494 -- main_name is not bound here!
496 (main_rdr : sub_rdrs) = hsTyClDeclBinders ti_decl
498 get_local_binders _ g = pprPanic "get_local_binders" (ppr g)
502 %************************************************************************
504 \subsection{Filtering imports}
506 %************************************************************************
508 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
509 available, and filters it through the import spec (if any).
512 filterImports :: ModIface
513 -> ImpDeclSpec -- The span for the entire import decl
514 -> Maybe (Bool, [LIE RdrName]) -- Import spec; True => hiding
515 -> [AvailInfo] -- What's available
516 -> RnM (Maybe (Bool, [LIE Name]), -- Import spec w/ Names
517 GlobalRdrEnv) -- Same again, but in GRE form
518 filterImports _ decl_spec Nothing all_avails
519 = return (Nothing, mkGlobalRdrEnv (gresFromAvails prov all_avails))
521 prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
524 filterImports iface decl_spec (Just (want_hiding, import_items)) all_avails
525 = do -- check for errors, convert RdrNames to Names
526 opt_typeFamilies <- doptM Opt_TypeFamilies
527 items1 <- mapM (lookup_lie opt_typeFamilies) import_items
529 let items2 :: [(LIE Name, AvailInfo)]
530 items2 = concat items1
531 -- NB the AvailInfo may have duplicates, and several items
532 -- for the same parent; e.g N(x) and N(y)
534 names = availsToNameSet (map snd items2)
535 keep n = not (n `elemNameSet` names)
536 pruned_avails = filterAvails keep all_avails
537 hiding_prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
539 gres | want_hiding = gresFromAvails hiding_prov pruned_avails
540 | otherwise = concatMap (gresFromIE decl_spec) items2
542 return (Just (want_hiding, map fst items2), mkGlobalRdrEnv gres)
544 -- This environment is how we map names mentioned in the import
545 -- list to the actual Name they correspond to, and the name family
546 -- that the Name belongs to (the AvailInfo). The situation is
547 -- complicated by associated families, which introduce a three-level
548 -- hierachy, where class = grand parent, assoc family = parent, and
549 -- data constructors = children. The occ_env entries for associated
550 -- families needs to capture all this information; hence, we have the
551 -- third component of the environment that gives the class name (=
552 -- grand parent) in case of associated families.
554 -- This env will have entries for data constructors too,
555 -- they won't make any difference because naked entities like T
556 -- in an import list map to TcOccs, not VarOccs.
557 occ_env :: OccEnv (Name, -- the name
558 AvailInfo, -- the export item providing the name
559 Maybe Name) -- the parent of associated types
560 occ_env = mkOccEnv_C combine [ (nameOccName n, (n, a, Nothing))
561 | a <- all_avails, n <- availNames a]
563 -- we know that (1) there are at most entries for one name, (2) their
564 -- first component is identical, (3) they are for tys/cls, and (4) one
565 -- entry has the name in its parent position (the other doesn't)
566 combine (name, AvailTC p1 subs1, Nothing)
567 (_ , AvailTC p2 subs2, Nothing)
569 (parent, subs) = if p1 == name then (p2, subs1) else (p1, subs2)
571 (name, AvailTC name subs, Just parent)
572 combine x y = pprPanic "filterImports/combine" (ppr x $$ ppr y)
574 lookup_lie :: Bool -> LIE RdrName -> TcRn [(LIE Name, AvailInfo)]
575 lookup_lie opt_typeFamilies (L loc ieRdr)
577 stuff <- setSrcSpan loc $
578 case lookup_ie opt_typeFamilies ieRdr of
579 Failed err -> addErr err >> return []
580 Succeeded a -> return a
581 checkDodgyImport stuff
582 return [ (L loc ie, avail) | (ie,avail) <- stuff ]
584 -- Warn when importing T(..) if T was exported abstractly
585 checkDodgyImport stuff
586 | IEThingAll n <- ieRdr, (_, AvailTC _ [_]):_ <- stuff
587 = ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn n))
588 -- NB. use the RdrName for reporting the warning
592 -- For each import item, we convert its RdrNames to Names,
593 -- and at the same time construct an AvailInfo corresponding
594 -- to what is actually imported by this item.
595 -- Returns Nothing on error.
596 -- We return a list here, because in the case of an import
597 -- item like C, if we are hiding, then C refers to *both* a
598 -- type/class and a data constructor. Moreover, when we import
599 -- data constructors of an associated family, we need separate
600 -- AvailInfos for the data constructors and the family (as they have
601 -- different parents). See the discussion at occ_env.
602 lookup_ie :: Bool -> IE RdrName -> MaybeErr Message [(IE Name,AvailInfo)]
603 lookup_ie opt_typeFamilies ie
604 = let bad_ie :: MaybeErr Message a
605 bad_ie = Failed (badImportItemErr iface decl_spec ie)
608 | isQual rdr = Failed (qualImportItemErr rdr)
609 | Just nm <- lookupOccEnv occ_env (rdrNameOcc rdr) = return nm
614 (name, avail, _) <- lookup_name n
615 return [(IEVar name, trimAvail avail name)]
618 (name, avail@(AvailTC name2 subs), mb_parent) <- lookup_name tc
620 -- non-associated ty/cls
621 Nothing -> return [(IEThingAll name, avail)]
623 Just parent -> return [(IEThingAll name,
624 AvailTC name2 (subs \\ [name])),
625 (IEThingAll name, AvailTC parent [name])]
628 | want_hiding -- hiding ( C )
629 -- Here the 'C' can be a data constructor
630 -- *or* a type/class, or even both
631 -> let tc_name = lookup_name tc
632 dc_name = lookup_name (setRdrNameSpace tc srcDataName)
634 case catMaybeErr [ tc_name, dc_name ] of
636 names -> return [mkIEThingAbs name | name <- names]
638 -> do nameAvail <- lookup_name tc
639 return [mkIEThingAbs nameAvail]
641 IEThingWith tc ns -> do
642 (name, AvailTC _ subnames, mb_parent) <- lookup_name tc
644 env = mkOccEnv [(nameOccName s, s) | s <- subnames]
645 mb_children = map (lookupOccEnv env . rdrNameOcc) ns
646 children <- if any isNothing mb_children
648 else return (catMaybes mb_children)
649 -- check for proper import of type families
650 when (not opt_typeFamilies && any isTyConName children) $
651 Failed (typeItemErr (head . filter isTyConName $ children)
652 (text "in import list"))
654 -- non-associated ty/cls
655 Nothing -> return [(IEThingWith name children,
656 AvailTC name (name:children))]
658 Just parent -> return [(IEThingWith name children,
659 AvailTC name children),
660 (IEThingWith name children,
661 AvailTC parent [name])]
663 _other -> Failed illegalImportItemErr
664 -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed
668 mkIEThingAbs (n, av, Nothing ) = (IEThingAbs n, trimAvail av n)
669 mkIEThingAbs (n, _, Just parent) = (IEThingAbs n, AvailTC parent [n])
672 catMaybeErr :: [MaybeErr err a] -> [a]
673 catMaybeErr ms = [ a | Succeeded a <- ms ]
676 %************************************************************************
680 %************************************************************************
683 -- | make a 'GlobalRdrEnv' where all the elements point to the same
684 -- import declaration (useful for "hiding" imports, or imports with
686 gresFromAvails :: Provenance -> [AvailInfo] -> [GlobalRdrElt]
687 gresFromAvails prov avails
688 = concatMap (gresFromAvail (const prov)) avails
690 gresFromAvail :: (Name -> Provenance) -> AvailInfo -> [GlobalRdrElt]
691 gresFromAvail prov_fn avail
692 = [ GRE {gre_name = n,
693 gre_par = availParent n avail,
694 gre_prov = prov_fn n}
695 | n <- availNames avail ]
697 greAvail :: GlobalRdrElt -> AvailInfo
698 greAvail gre = mkUnitAvail (gre_name gre) (gre_par gre)
700 mkUnitAvail :: Name -> Parent -> AvailInfo
701 mkUnitAvail me (ParentIs p) = AvailTC p [me]
702 mkUnitAvail me NoParent | isTyConName me = AvailTC me [me]
703 | otherwise = Avail me
705 plusAvail :: GenAvailInfo Name -> GenAvailInfo Name -> GenAvailInfo Name
706 plusAvail (Avail n1) (Avail _) = Avail n1
707 plusAvail (AvailTC _ ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
708 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
710 availParent :: Name -> AvailInfo -> Parent
711 availParent _ (Avail _) = NoParent
712 availParent n (AvailTC m _) | n == m = NoParent
713 | otherwise = ParentIs m
715 trimAvail :: AvailInfo -> Name -> AvailInfo
716 trimAvail (Avail n) _ = Avail n
717 trimAvail (AvailTC n ns) m = ASSERT( m `elem` ns) AvailTC n [m]
719 -- | filters 'AvailInfo's by the given predicate
720 filterAvails :: (Name -> Bool) -> [AvailInfo] -> [AvailInfo]
721 filterAvails keep avails = foldr (filterAvail keep) [] avails
723 -- | filters an 'AvailInfo' by the given predicate
724 filterAvail :: (Name -> Bool) -> AvailInfo -> [AvailInfo] -> [AvailInfo]
725 filterAvail keep ie rest =
727 Avail n | keep n -> ie : rest
730 let left = filter keep ns in
731 if null left then rest else AvailTC tc left : rest
733 -- | Given an import\/export spec, construct the appropriate 'GlobalRdrElt's.
734 gresFromIE :: ImpDeclSpec -> (LIE Name, AvailInfo) -> [GlobalRdrElt]
735 gresFromIE decl_spec (L loc ie, avail)
736 = gresFromAvail prov_fn avail
738 is_explicit = case ie of
739 IEThingAll name -> \n -> n == name
741 prov_fn name = Imported [imp_spec]
743 imp_spec = ImpSpec { is_decl = decl_spec, is_item = item_spec }
744 item_spec = ImpSome { is_explicit = is_explicit name, is_iloc = loc }
746 mkChildEnv :: [GlobalRdrElt] -> NameEnv [Name]
747 mkChildEnv gres = foldr add emptyNameEnv gres
749 add (GRE { gre_name = n, gre_par = ParentIs p }) env = extendNameEnv_Acc (:) singleton env p n
752 findChildren :: NameEnv [Name] -> Name -> [Name]
753 findChildren env n = lookupNameEnv env n `orElse` []
756 ---------------------------------------
759 All this AvailEnv stuff is hardly used; only in a very small
760 part of RnNames. Todo: remove?
761 ---------------------------------------
764 type AvailEnv = NameEnv AvailInfo -- Maps a Name to the AvailInfo that contains it
766 emptyAvailEnv :: AvailEnv
767 emptyAvailEnv = emptyNameEnv
770 unitAvailEnv :: AvailInfo -> AvailEnv
771 unitAvailEnv a = unitNameEnv (availName a) a
773 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
774 plusAvailEnv = plusNameEnv_C plusAvail
776 availEnvElts :: AvailEnv -> [AvailInfo]
777 availEnvElts = nameEnvElts
780 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
781 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
783 mkAvailEnv :: [AvailInfo] -> AvailEnv
784 -- 'avails' may have several items with the same availName
785 -- E.g import Ix( Ix(..), index )
786 -- will give Ix(Ix,index,range) and Ix(index)
787 -- We want to combine these; addAvail does that
788 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
790 -- After combining the avails, we need to ensure that the parent name is the
791 -- first entry in the list of subnames, if it is included at all. (Subsequent
792 -- functions rely on that.)
793 normaliseAvail :: AvailInfo -> AvailInfo
794 normaliseAvail avail@(Avail _) = avail
795 normaliseAvail (AvailTC name subs) = AvailTC name subs'
797 subs' = if name `elem` subs then name : (delete name subs) else subs
799 -- | combines 'AvailInfo's from the same family
800 nubAvails :: [AvailInfo] -> [AvailInfo]
801 nubAvails avails = map normaliseAvail . nameEnvElts . mkAvailEnv $ avails
805 %************************************************************************
807 \subsection{Export list processing}
809 %************************************************************************
811 Processing the export list.
813 You might think that we should record things that appear in the export
814 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
815 wrong. We do check (here) that they are in scope, but there is no
816 need to slurp in their actual declaration (which is what
817 @addOccurrenceName@ forces).
819 Indeed, doing so would big trouble when compiling @PrelBase@, because
820 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
821 @ConcBase.StateAndSynchVar#@, and so on...
824 type ExportAccum -- The type of the accumulating parameter of
825 -- the main worker function in rnExports
826 = ([LIE Name], -- Export items with Names
827 ExportOccMap, -- Tracks exported occurrence names
828 [AvailInfo]) -- The accumulated exported stuff
831 emptyExportAccum :: ExportAccum
832 emptyExportAccum = ([], emptyOccEnv, [])
834 type ExportOccMap = OccEnv (Name, IE RdrName)
835 -- Tracks what a particular exported OccName
836 -- in an export list refers to, and which item
837 -- it came from. It's illegal to export two distinct things
838 -- that have the same occurrence name
840 rnExports :: Bool -- False => no 'module M(..) where' header at all
841 -> Maybe [LIE RdrName] -- Nothing => no explicit export list
845 -- Complains if two distinct exports have same OccName
846 -- Warns about identical exports.
847 -- Complains about exports items not in scope
849 rnExports explicit_mod exports
850 tcg_env@(TcGblEnv { tcg_mod = this_mod,
851 tcg_rdr_env = rdr_env,
852 tcg_imports = imports })
854 -- If the module header is omitted altogether, then behave
855 -- as if the user had written "module Main(main) where..."
856 -- EXCEPT in interactive mode, when we behave as if he had
857 -- written "module Main where ..."
858 -- Reason: don't want to complain about 'main' not in scope
859 -- in interactive mode
862 | explicit_mod = exports
863 | ghcLink dflags == LinkInMemory = Nothing
864 | otherwise = Just ([noLoc (IEVar main_RDR_Unqual)])
865 -- ToDo: the 'noLoc' here is unhelpful if 'main'
866 -- turns out to be out of scope
868 ; (rn_exports, avails) <- exports_from_avail real_exports rdr_env imports this_mod
869 ; let final_avails = nubAvails avails -- Combine families
871 ; return (tcg_env { tcg_exports = final_avails,
872 tcg_rn_exports = case tcg_rn_exports tcg_env of
874 Just _ -> rn_exports,
875 tcg_dus = tcg_dus tcg_env `plusDU`
876 usesOnly (availsToNameSet final_avails) }) }
878 exports_from_avail :: Maybe [LIE RdrName]
879 -- Nothing => no explicit export list
883 -> RnM (Maybe [LIE Name], [AvailInfo])
885 exports_from_avail Nothing rdr_env _imports _this_mod
886 = -- The same as (module M) where M is the current module name,
887 -- so that's how we handle it.
889 avails = [ greAvail gre | gre <- globalRdrEnvElts rdr_env,
892 return (Nothing, avails)
894 exports_from_avail (Just rdr_items) rdr_env imports this_mod
895 = do (ie_names, _, exports) <- foldlM do_litem emptyExportAccum rdr_items
897 return (Just ie_names, exports)
899 do_litem :: ExportAccum -> LIE RdrName -> RnM ExportAccum
900 do_litem acc lie = setSrcSpan (getLoc lie) (exports_from_item acc lie)
902 kids_env :: NameEnv [Name] -- Maps a parent to its in-scope children
903 kids_env = mkChildEnv (globalRdrEnvElts rdr_env)
905 imported_modules = [ qual_name
906 | xs <- moduleEnvElts $ imp_mods imports,
907 (qual_name, _, _) <- xs ]
909 exports_from_item :: ExportAccum -> LIE RdrName -> RnM ExportAccum
910 exports_from_item acc@(ie_names, occs, exports)
911 (L loc ie@(IEModuleContents mod))
912 | let earlier_mods = [ mod | (L _ (IEModuleContents mod)) <- ie_names ]
913 , mod `elem` earlier_mods -- Duplicate export of M
914 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
915 warnIf warn_dup_exports (dupModuleExport mod) ;
919 = do { implicit_prelude <- doptM Opt_ImplicitPrelude
920 ; warnDodgyExports <- doptM Opt_WarnDodgyExports
921 ; let { exportValid = (mod `elem` imported_modules)
922 || (moduleName this_mod == mod)
923 ; gres = filter (isModuleExported implicit_prelude mod)
924 (globalRdrEnvElts rdr_env)
925 ; names = map gre_name gres
928 ; checkErr exportValid (moduleNotImported mod)
929 ; warnIf (warnDodgyExports && exportValid && null gres) (nullModuleExport mod)
931 ; addUsedRdrNames (concat [ [mkRdrQual mod occ, mkRdrUnqual occ]
932 | occ <- map nameOccName names ])
933 -- The qualified and unqualified version of all of
934 -- these names are, in effect, used by this export
936 ; occs' <- check_occs ie occs names
937 -- This check_occs not only finds conflicts
938 -- between this item and others, but also
939 -- internally within this item. That is, if
940 -- 'M.x' is in scope in several ways, we'll have
941 -- several members of mod_avails with the same
943 ; return (L loc (IEModuleContents mod) : ie_names,
944 occs', map greAvail gres ++ exports) }
946 exports_from_item acc@(lie_names, occs, exports) (L loc ie)
948 = do new_ie <- lookup_doc_ie ie
949 return (L loc new_ie : lie_names, occs, exports)
952 = do (new_ie, avail) <- lookup_ie ie
953 if isUnboundName (ieName new_ie)
954 then return acc -- Avoid error cascade
957 occs' <- check_occs ie occs (availNames avail)
959 return (L loc new_ie : lie_names, occs', avail : exports)
962 lookup_ie :: IE RdrName -> RnM (IE Name, AvailInfo)
963 lookup_ie (IEVar rdr)
964 = do gre <- lookupGreRn rdr
965 return (IEVar (gre_name gre), greAvail gre)
967 lookup_ie (IEThingAbs rdr)
968 = do gre <- lookupGreRn rdr
969 let name = gre_name gre
971 NoParent -> return (IEThingAbs name,
973 ParentIs p -> return (IEThingAbs name,
976 lookup_ie ie@(IEThingAll rdr)
977 = do name <- lookupGlobalOccRn rdr
978 let kids = findChildren kids_env name
979 mkKidRdrName = case isQual_maybe rdr of
980 Nothing -> mkRdrUnqual
981 Just (modName, _) -> mkRdrQual modName
982 addUsedRdrNames $ map (mkKidRdrName . nameOccName) kids
983 warnDodgyExports <- doptM Opt_WarnDodgyExports
986 then when warnDodgyExports $ addWarn (dodgyExportWarn name)
987 else -- This occurs when you export T(..), but
988 -- only import T abstractly, or T is a synonym.
989 addErr (exportItemErr ie)
991 return (IEThingAll name, AvailTC name (name:kids))
993 lookup_ie ie@(IEThingWith rdr sub_rdrs)
994 = do name <- lookupGlobalOccRn rdr
995 if isUnboundName name
996 then return (IEThingWith name [], AvailTC name [name])
998 let env = mkOccEnv [ (nameOccName s, s)
999 | s <- findChildren kids_env name ]
1000 mb_names = map (lookupOccEnv env . rdrNameOcc) sub_rdrs
1001 if any isNothing mb_names
1002 then do addErr (exportItemErr ie)
1003 return (IEThingWith name [], AvailTC name [name])
1004 else do let names = catMaybes mb_names
1005 optTyFam <- doptM Opt_TypeFamilies
1006 when (not optTyFam && any isTyConName names) $
1007 addErr (typeItemErr ( head
1008 . filter isTyConName
1010 (text "in export list"))
1011 return (IEThingWith name names, AvailTC name (name:names))
1013 lookup_ie _ = panic "lookup_ie" -- Other cases covered earlier
1016 lookup_doc_ie :: IE RdrName -> RnM (IE Name)
1017 lookup_doc_ie (IEGroup lev doc) = do rn_doc <- rnHsDoc doc
1018 return (IEGroup lev rn_doc)
1019 lookup_doc_ie (IEDoc doc) = do rn_doc <- rnHsDoc doc
1020 return (IEDoc rn_doc)
1021 lookup_doc_ie (IEDocNamed str) = return (IEDocNamed str)
1022 lookup_doc_ie _ = panic "lookup_doc_ie" -- Other cases covered earlier
1025 isDoc :: IE RdrName -> Bool
1026 isDoc (IEDoc _) = True
1027 isDoc (IEDocNamed _) = True
1028 isDoc (IEGroup _ _) = True
1031 -------------------------------
1032 isModuleExported :: Bool -> ModuleName -> GlobalRdrElt -> Bool
1033 -- True if the thing is in scope *both* unqualified, *and* with qualifier M
1034 isModuleExported implicit_prelude mod (GRE { gre_name = name, gre_prov = prov })
1035 | implicit_prelude && isBuiltInSyntax name = False
1036 -- Optimisation: filter out names for built-in syntax
1037 -- They just clutter up the environment (esp tuples), and the parser
1038 -- will generate Exact RdrNames for them, so the cluttered
1039 -- envt is no use. To avoid doing this filter all the time,
1040 -- we use -XNoImplicitPrelude as a clue that the filter is
1041 -- worth while. Really, it's only useful for GHC.Base and GHC.Tuple.
1043 -- It's worth doing because it makes the environment smaller for
1044 -- every module that imports the Prelude
1047 LocalDef | Just name_mod <- nameModule_maybe name
1048 -> moduleName name_mod == mod
1049 | otherwise -> False
1050 Imported is -> any unQualSpecOK is && any (qualSpecOK mod) is
1052 -------------------------------
1053 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
1054 check_occs ie occs names
1055 = foldlM check occs names
1058 = case lookupOccEnv occs name_occ of
1059 Nothing -> return (extendOccEnv occs name_occ (name, ie))
1062 | name == name' -- Duplicate export
1063 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
1064 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
1067 | otherwise -- Same occ name but different names: an error
1068 -> do { global_env <- getGlobalRdrEnv ;
1069 addErr (exportClashErr global_env name' name ie' ie) ;
1072 name_occ = nameOccName name
1075 %*********************************************************
1079 %*********************************************************
1082 finishWarnings :: DynFlags -> Maybe WarningTxt
1083 -> TcGblEnv -> RnM TcGblEnv
1084 -- (a) Report usage of imports that are deprecated or have other warnings
1085 -- (b) If the whole module is warned about or deprecated, update tcg_warns
1086 -- All this happens only once per module
1087 finishWarnings dflags mod_warn tcg_env
1088 = do { (eps,hpt) <- getEpsAndHpt
1089 ; ifOptM Opt_WarnWarningsDeprecations $
1090 mapM_ (check hpt (eps_PIT eps)) all_gres
1091 -- By this time, typechecking is complete,
1092 -- so the PIT is fully populated
1094 -- Deal with a module deprecation; it overrides all existing warns
1095 ; let new_warns = case mod_warn of
1096 Just txt -> WarnAll txt
1097 Nothing -> tcg_warns tcg_env
1098 ; return (tcg_env { tcg_warns = new_warns }) }
1100 used_names = allUses (tcg_dus tcg_env)
1101 -- Report on all deprecated uses; hence allUses
1102 all_gres = globalRdrEnvElts (tcg_rdr_env tcg_env)
1104 check hpt pit gre@(GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
1105 | name `elemNameSet` used_names
1106 , Just deprec_txt <- lookupImpDeprec dflags hpt pit gre
1107 = addWarnAt (importSpecLoc imp_spec)
1108 (sep [ptext (sLit "In the use of") <+>
1109 pprNonVarNameSpace (occNameSpace (nameOccName name)) <+>
1111 (parens imp_msg) <> colon,
1114 name_mod = ASSERT2( isExternalName name, ppr name ) nameModule name
1115 imp_mod = importSpecModule imp_spec
1116 imp_msg = ptext (sLit "imported from") <+> ppr imp_mod <> extra
1117 extra | imp_mod == moduleName name_mod = empty
1118 | otherwise = ptext (sLit ", but defined in") <+> ppr name_mod
1120 check _ _ _ = return () -- Local, or not used, or not deprectated
1121 -- The Imported pattern-match: don't deprecate locally defined names
1122 -- For a start, we may be exporting a deprecated thing
1123 -- Also we may use a deprecated thing in the defn of another
1124 -- deprecated things. We may even use a deprecated thing in
1125 -- the defn of a non-deprecated thing, when changing a module's
1128 lookupImpDeprec :: DynFlags -> HomePackageTable -> PackageIfaceTable
1129 -> GlobalRdrElt -> Maybe WarningTxt
1130 -- The name is definitely imported, so look in HPT, PIT
1131 lookupImpDeprec dflags hpt pit gre
1132 = case lookupIfaceByModule dflags hpt pit mod of
1133 Just iface -> mi_warn_fn iface name `mplus` -- Bleat if the thing, *or
1135 ParentIs p -> mi_warn_fn iface p -- its parent*, is warn'd
1138 Nothing -> Nothing -- See Note [Used names with interface not loaded]
1141 mod = ASSERT2( isExternalName name, ppr name ) nameModule name
1144 Note [Used names with interface not loaded]
1145 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1146 By now all the interfaces should have been loaded,
1147 because reportDeprecations happens after typechecking.
1148 However, it's still (just) possible to to find a used
1149 Name whose interface hasn't been loaded:
1151 a) It might be a WiredInName; in that case we may not load
1152 its interface (although we could).
1154 b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
1155 These are seen as "used" by the renamer (if -XNoImplicitPrelude)
1156 is on), but the typechecker may discard their uses
1157 if in fact the in-scope fromRational is GHC.Read.fromRational,
1158 (see tcPat.tcOverloadedLit), and the typechecker sees that the type
1159 is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
1160 In that obscure case it won't force the interface in.
1162 In both cases we simply don't permit deprecations;
1163 this is, after all, wired-in stuff.
1166 %*********************************************************
1170 %*********************************************************
1173 reportUnusedNames :: Maybe [LIE RdrName] -- Export list
1174 -> TcGblEnv -> RnM ()
1175 reportUnusedNames _export_decls gbl_env
1176 = do { traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env)))
1177 ; warnUnusedImportDecls gbl_env
1178 ; warnUnusedTopBinds unused_locals }
1180 used_names :: NameSet
1181 used_names = findUses (tcg_dus gbl_env) emptyNameSet
1182 -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
1185 -- Collect the defined names from the in-scope environment
1186 defined_names :: [GlobalRdrElt]
1187 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
1189 -- Note that defined_and_used, defined_but_not_used
1190 -- are both [GRE]; that's why we need defined_and_used
1191 -- rather than just used_names
1192 _defined_and_used, defined_but_not_used :: [GlobalRdrElt]
1193 (_defined_and_used, defined_but_not_used)
1194 = partition (gre_is_used used_names) defined_names
1196 kids_env = mkChildEnv defined_names
1197 -- This is done in mkExports too; duplicated work
1199 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
1200 gre_is_used used_names (GRE {gre_name = name})
1201 = name `elemNameSet` used_names
1202 || any (`elemNameSet` used_names) (findChildren kids_env name)
1203 -- A use of C implies a use of T,
1204 -- if C was brought into scope by T(..) or T(C)
1206 -- Filter out the ones that are
1207 -- (a) defined in this module, and
1208 -- (b) not defined by a 'deriving' clause
1209 -- The latter have an Internal Name, so we can filter them out easily
1210 unused_locals :: [GlobalRdrElt]
1211 unused_locals = filter is_unused_local defined_but_not_used
1212 is_unused_local :: GlobalRdrElt -> Bool
1213 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
1216 %*********************************************************
1220 %*********************************************************
1222 This code finds which import declarations are unused. The
1223 specification and implementation notes are here:
1224 http://hackage.haskell.org/trac/ghc/wiki/Commentary/Compiler/UnusedImports
1227 type ImportDeclUsage
1228 = ( LImportDecl Name -- The import declaration
1229 , [AvailInfo] -- What *is* used (normalised)
1230 , [Name] ) -- What is imported but *not* used
1234 warnUnusedImportDecls :: TcGblEnv -> RnM ()
1235 warnUnusedImportDecls gbl_env
1236 = do { uses <- readMutVar (tcg_used_rdrnames gbl_env)
1237 ; let imports = filter explicit_import (tcg_rn_imports gbl_env)
1238 rdr_env = tcg_rdr_env gbl_env
1240 ; let usage :: [ImportDeclUsage]
1241 usage = findImportUsage imports rdr_env (Set.elems uses)
1243 ; ifOptM Opt_WarnUnusedImports $
1244 mapM_ warnUnusedImport usage
1246 ; ifOptM Opt_D_dump_minimal_imports $
1247 printMinimalImports usage }
1249 explicit_import (L loc _) = isGoodSrcSpan loc
1250 -- Filter out the implicit Prelude import
1251 -- which we do not want to bleat about
1255 findImportUsage :: [LImportDecl Name]
1258 -> [ImportDeclUsage]
1260 type ImportMap = Map SrcLoc [AvailInfo]
1261 -- The intermediate data struture records, for each import
1262 -- declaration, what stuff brought into scope by that
1263 -- declaration is actually used in the module.
1265 -- The SrcLoc is the location of the start
1266 -- of a particular 'import' declaration
1268 -- The AvailInfos are the things imported from that decl
1269 -- (just a list, not normalised)
1271 findImportUsage imports rdr_env rdrs
1272 = map unused_decl imports
1274 import_usage :: ImportMap
1275 import_usage = foldr add_rdr Map.empty rdrs
1277 unused_decl decl@(L loc (ImportDecl { ideclHiding = imps }))
1278 = (decl, nubAvails used_avails, unused_imps)
1280 used_avails = Map.lookup (srcSpanStart loc) import_usage `orElse` []
1281 used_names = availsToNameSet used_avails
1283 unused_imps = case imps of
1284 Just (False, imp_ies) -> nameSetToList unused_imps
1286 imp_names = mkNameSet (concatMap (ieNames . unLoc) imp_ies)
1287 unused_imps = imp_names `minusNameSet` used_names
1289 _other -> [] -- No explicit import list => no unused-name list
1291 add_rdr :: RdrName -> ImportMap -> ImportMap
1293 = case lookupGRE_RdrName rdr rdr_env of
1294 [gre] | Imported imps <- gre_prov gre
1295 -> add_imp gre (bestImport imps) iu
1298 add_imp :: GlobalRdrElt -> ImportSpec -> ImportMap -> ImportMap
1299 add_imp gre (ImpSpec { is_decl = imp_decl_spec }) iu
1300 = Map.insertWith add decl_loc [avail] iu
1302 add _ avails = avail : avails -- add is really just a specialised (++)
1303 decl_loc = srcSpanStart (is_dloc imp_decl_spec)
1305 avail = case gre_par gre of
1306 ParentIs p -> AvailTC p [p,name]
1307 NoParent | isTyConName name -> AvailTC name [name]
1308 | otherwise -> Avail name
1309 -- If you use (+) from Num, then for this purpose we want
1310 -- to say that Num is used as well. That is why in the
1311 -- ParentIs case we have [p,name] in the ParentIs case
1313 bestImport :: [ImportSpec] -> ImportSpec
1315 = case partition isImpAll iss of
1316 ([], imp_somes) -> textuallyFirst imp_somes
1317 (imp_alls, _) -> textuallyFirst imp_alls
1319 textuallyFirst :: [ImportSpec] -> ImportSpec
1320 textuallyFirst iss = case sortWith (is_dloc . is_decl) iss of
1321 [] -> pprPanic "textuallyFirst" (ppr iss)
1324 isImpAll :: ImportSpec -> Bool
1325 isImpAll (ImpSpec { is_item = ImpAll }) = True
1326 isImpAll _other = False
1330 warnUnusedImport :: ImportDeclUsage -> RnM ()
1331 warnUnusedImport (L loc decl, used, unused)
1332 | Just (False,[]) <- ideclHiding decl
1333 = return () -- Do not warn for 'import M()'
1334 | null used = addWarnAt loc msg1 -- Nothing used; drop entire decl
1335 | null unused = return () -- Everything imported is used; nop
1336 | otherwise = addWarnAt loc msg2 -- Some imports are unused
1338 msg1 = vcat [pp_herald <+> quotes pp_mod <+> pp_not_used,
1339 nest 2 (ptext (sLit "except perhaps to import instances from")
1341 ptext (sLit "To import instances alone, use:")
1342 <+> ptext (sLit "import") <+> pp_mod <> parens empty ]
1343 msg2 = sep [pp_herald <+> quotes (pprWithCommas ppr unused),
1344 text "from module" <+> quotes pp_mod <+> pp_not_used]
1345 pp_herald = text "The import of"
1346 pp_mod = ppr (unLoc (ideclName decl))
1347 pp_not_used = text "is redundant"
1350 To print the minimal imports we walk over the user-supplied import
1351 decls, and simply trim their import lists. NB that
1353 * We do *not* change the 'qualified' or 'as' parts!
1355 * We do not disard a decl altogether; we might need instances
1356 from it. Instead we just trim to an empty import list
1359 printMinimalImports :: [ImportDeclUsage] -> RnM ()
1360 printMinimalImports imports_w_usage
1361 = do { imports' <- mapM mk_minimal imports_w_usage
1362 ; this_mod <- getModule
1364 do { h <- openFile (mkFilename this_mod) WriteMode
1365 ; printForUser h neverQualify (vcat (map ppr imports')) }
1366 -- The neverQualify is important. We are printing Names
1367 -- but they are in the context of an 'import' decl, and
1368 -- we never qualify things inside there
1369 -- E.g. import Blag( f, b )
1370 -- not import Blag( Blag.f, Blag.g )!
1373 mkFilename this_mod = moduleNameString (moduleName this_mod) ++ ".imports"
1375 mk_minimal (L l decl, used, unused)
1377 , Just (False, _) <- ideclHiding decl
1380 = do { ies <- initIfaceTcRn $ mapM to_ie used
1381 ; return (L l (decl { ideclHiding = Just (False, map (L l) ies) })) }
1383 to_ie :: AvailInfo -> IfG (IE Name)
1384 -- The main trick here is that if we're importing all the constructors
1385 -- we want to say "T(..)", but if we're importing only a subset we want
1386 -- to say "T(A,B,C)". So we have to find out what the module exports.
1387 to_ie (Avail n) = return (IEVar n)
1388 to_ie (AvailTC n [m]) = ASSERT( n==m )
1389 return (IEThingAbs n)
1390 to_ie (AvailTC n ns) = do
1391 iface <- loadSysInterface doc n_mod
1392 case [xs | (m,as) <- mi_exports iface,
1395 x == nameOccName n] of
1396 [xs] | all_used xs -> return (IEThingAll n)
1397 | otherwise -> return (IEThingWith n (filter (/= n) ns))
1398 other -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
1401 all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
1402 doc = text "Compute minimal imports from" <+> ppr n
1403 n_mod = ASSERT( isExternalName n ) nameModule n
1406 %************************************************************************
1410 %************************************************************************
1413 qualImportItemErr :: RdrName -> SDoc
1414 qualImportItemErr rdr
1415 = hang (ptext (sLit "Illegal qualified name in import item:"))
1418 badImportItemErr :: ModIface -> ImpDeclSpec -> IE RdrName -> SDoc
1419 badImportItemErr iface decl_spec ie
1420 = sep [ptext (sLit "Module"), quotes (ppr (is_mod decl_spec)), source_import,
1421 ptext (sLit "does not export"), quotes (ppr ie)]
1423 source_import | mi_boot iface = ptext (sLit "(hi-boot interface)")
1426 illegalImportItemErr :: SDoc
1427 illegalImportItemErr = ptext (sLit "Illegal import item")
1429 dodgyImportWarn :: RdrName -> SDoc
1430 dodgyImportWarn item = dodgyMsg (ptext (sLit "import")) item
1431 dodgyExportWarn :: Name -> SDoc
1432 dodgyExportWarn item = dodgyMsg (ptext (sLit "export")) item
1434 dodgyMsg :: OutputableBndr n => SDoc -> n -> SDoc
1436 = sep [ ptext (sLit "The") <+> kind <+> ptext (sLit "item") <+> quotes (ppr (IEThingAll tc))
1437 <+> ptext (sLit "suggests that"),
1438 quotes (ppr tc) <+> ptext (sLit "has (in-scope) constructors or class methods,"),
1439 ptext (sLit "but it has none") ]
1441 exportItemErr :: IE RdrName -> SDoc
1442 exportItemErr export_item
1443 = sep [ ptext (sLit "The export item") <+> quotes (ppr export_item),
1444 ptext (sLit "attempts to export constructors or class methods that are not visible here") ]
1446 typeItemErr :: Name -> SDoc -> SDoc
1447 typeItemErr name wherestr
1448 = sep [ ptext (sLit "Using 'type' tag on") <+> quotes (ppr name) <+> wherestr,
1449 ptext (sLit "Use -XTypeFamilies to enable this extension") ]
1451 exportClashErr :: GlobalRdrEnv -> Name -> Name -> IE RdrName -> IE RdrName
1453 exportClashErr global_env name1 name2 ie1 ie2
1454 = vcat [ ptext (sLit "Conflicting exports for") <+> quotes (ppr occ) <> colon
1455 , ppr_export ie1' name1'
1456 , ppr_export ie2' name2' ]
1458 occ = nameOccName name1
1459 ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext (sLit "exports") <+>
1460 quotes (ppr name) <+> pprNameProvenance (get_gre name))
1462 -- get_gre finds a GRE for the Name, so that we can show its provenance
1464 = case lookupGRE_Name global_env name of
1466 [] -> pprPanic "exportClashErr" (ppr name)
1467 get_loc name = nameSrcLoc $ gre_name $ get_gre name
1468 (name1', ie1', name2', ie2') = if get_loc name1 < get_loc name2
1469 then (name1, ie1, name2, ie2)
1470 else (name2, ie2, name1, ie1)
1472 addDupDeclErr :: [Name] -> TcRn ()
1474 = panic "addDupDeclErr: empty list"
1475 addDupDeclErr names@(name : _)
1476 = addErrAt (getSrcSpan (last sorted_names)) $
1477 -- Report the error at the later location
1478 vcat [ptext (sLit "Multiple declarations of") <+> quotes (ppr name),
1479 ptext (sLit "Declared at:") <+> vcat (map (ppr . nameSrcLoc) sorted_names)]
1481 sorted_names = sortWith nameSrcLoc names
1483 dupExportWarn :: OccName -> IE RdrName -> IE RdrName -> SDoc
1484 dupExportWarn occ_name ie1 ie2
1485 = hsep [quotes (ppr occ_name),
1486 ptext (sLit "is exported by"), quotes (ppr ie1),
1487 ptext (sLit "and"), quotes (ppr ie2)]
1489 dupModuleExport :: ModuleName -> SDoc
1491 = hsep [ptext (sLit "Duplicate"),
1492 quotes (ptext (sLit "Module") <+> ppr mod),
1493 ptext (sLit "in export list")]
1495 moduleNotImported :: ModuleName -> SDoc
1496 moduleNotImported mod
1497 = ptext (sLit "The export item `module") <+> ppr mod <>
1498 ptext (sLit "' is not imported")
1500 nullModuleExport :: ModuleName -> SDoc
1501 nullModuleExport mod
1502 = ptext (sLit "The export item `module") <+> ppr mod <> ptext (sLit "' exports nothing")
1504 missingImportListWarn :: ModuleName -> SDoc
1505 missingImportListWarn mod
1506 = ptext (sLit "The module") <+> quotes (ppr mod) <+> ptext (sLit "does not have an explicit import list")
1508 moduleWarn :: ModuleName -> WarningTxt -> SDoc
1509 moduleWarn mod (WarningTxt txt)
1510 = sep [ ptext (sLit "Module") <+> quotes (ppr mod) <> ptext (sLit ":"),
1511 nest 2 (vcat (map ppr txt)) ]
1512 moduleWarn mod (DeprecatedTxt txt)
1513 = sep [ ptext (sLit "Module") <+> quotes (ppr mod)
1514 <+> ptext (sLit "is deprecated:"),
1515 nest 2 (vcat (map ppr txt)) ]
1517 implicitPreludeWarn :: SDoc
1519 = ptext (sLit "Module `Prelude' implicitly imported")
1521 packageImportErr :: SDoc
1523 = ptext (sLit "Package-qualified imports are not enabled; use -XPackageImports")