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 )
41 import Data.List ( partition, (\\), delete )
42 import qualified Data.Set as Set
49 %************************************************************************
53 %************************************************************************
56 rnImports :: [LImportDecl RdrName]
57 -> RnM ([LImportDecl Name], GlobalRdrEnv, ImportAvails,AnyHpcUsage)
60 -- PROCESS IMPORT DECLS
61 -- Do the non {- SOURCE -} ones first, so that we get a helpful
62 -- warning for {- SOURCE -} ones that are unnecessary
63 = do this_mod <- getModule
64 implicit_prelude <- doptM Opt_ImplicitPrelude
65 let prel_imports = mkPrelImports (moduleName this_mod) implicit_prelude imports
66 (source, ordinary) = partition is_source_import imports
67 is_source_import (L _ (ImportDecl _ _ is_boot _ _ _)) = is_boot
69 ifOptM Opt_WarnImplicitPrelude (
70 when (notNull prel_imports) $ addWarn (implicitPreludeWarn)
73 stuff1 <- mapM (rnImportDecl this_mod True) prel_imports
74 stuff2 <- mapM (rnImportDecl this_mod False) ordinary
75 stuff3 <- mapM (rnImportDecl this_mod False) source
76 let (decls, rdr_env, imp_avails, hpc_usage) = combine (stuff1 ++ stuff2 ++ stuff3)
77 return (decls, rdr_env, imp_avails, hpc_usage)
80 combine :: [(LImportDecl Name, GlobalRdrEnv, ImportAvails,AnyHpcUsage)]
81 -> ([LImportDecl Name], GlobalRdrEnv, ImportAvails,AnyHpcUsage)
82 combine = foldr plus ([], emptyGlobalRdrEnv, emptyImportAvails,False)
83 where plus (decl, gbl_env1, imp_avails1,hpc_usage1)
84 (decls, gbl_env2, imp_avails2,hpc_usage2)
86 gbl_env1 `plusGlobalRdrEnv` gbl_env2,
87 imp_avails1 `plusImportAvails` imp_avails2,
88 hpc_usage1 || hpc_usage2)
90 rnImportDecl :: Module -> Bool
91 -> LImportDecl RdrName
92 -> RnM (LImportDecl Name, GlobalRdrEnv, ImportAvails,AnyHpcUsage)
94 rnImportDecl this_mod implicit_prelude (L loc (ImportDecl loc_imp_mod_name mb_pkg want_boot
95 qual_only as_mod imp_details))
98 when (isJust mb_pkg) $ do
99 pkg_imports <- doptM Opt_PackageImports
100 when (not pkg_imports) $ addErr packageImportErr
102 -- If there's an error in loadInterface, (e.g. interface
103 -- file not found) we get lots of spurious errors from 'filterImports'
105 imp_mod_name = unLoc loc_imp_mod_name
106 doc = ppr imp_mod_name <+> ptext (sLit "is directly imported")
108 let isExplicit lie = case unLoc lie of
109 IEThingAll _ -> False
113 | all isExplicit lies ->
116 unless implicit_prelude $
117 ifOptM Opt_WarnMissingImportList (addWarn (missingImportListWarn imp_mod_name))
119 iface <- loadSrcInterface doc imp_mod_name want_boot mb_pkg
121 -- Compiler sanity check: if the import didn't say
122 -- {-# SOURCE #-} we should not get a hi-boot file
123 WARN( not want_boot && mi_boot iface, ppr imp_mod_name ) (do
125 -- Issue a user warning for a redundant {- SOURCE -} import
126 -- NB that we arrange to read all the ordinary imports before
127 -- any of the {- SOURCE -} imports.
129 -- in --make and GHCi, the compilation manager checks for this,
130 -- and indeed we shouldn't do it here because the existence of
131 -- the non-boot module depends on the compilation order, which
132 -- is not deterministic. The hs-boot test can show this up.
134 warnIf (want_boot && not (mi_boot iface) && isOneShot (ghcMode dflags))
135 (warnRedundantSourceImport imp_mod_name)
138 imp_mod = mi_module iface
139 warns = mi_warns iface
140 orph_iface = mi_orphan iface
141 has_finsts = mi_finsts iface
144 filtered_exports = filter not_this_mod (mi_exports iface)
145 not_this_mod (mod,_) = mod /= this_mod
146 -- If the module exports anything defined in this module, just
147 -- ignore it. Reason: otherwise it looks as if there are two
148 -- local definition sites for the thing, and an error gets
149 -- reported. Easiest thing is just to filter them out up
150 -- front. This situation only arises if a module imports
151 -- itself, or another module that imported it. (Necessarily,
152 -- this invoves a loop.)
154 -- Tiresome consequence: if you say
159 -- module B( AType ) where
160 -- import {-# SOURCE #-} A( AType )
162 -- then you'll get a 'B does not export AType' message. Oh well.
164 qual_mod_name = case as_mod of
165 Nothing -> imp_mod_name
166 Just another_name -> another_name
167 imp_spec = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,
168 is_dloc = loc, is_as = qual_mod_name }
171 -- Get the total exports from this module
172 total_avails <- ifaceExportNames filtered_exports
174 -- filter the imports according to the import declaration
175 (new_imp_details, gbl_env) <-
176 filterImports iface imp_spec imp_details total_avails
181 -- Compute new transitive dependencies
183 orphans | orph_iface = ASSERT( not (imp_mod `elem` dep_orphs deps) )
184 imp_mod : dep_orphs deps
185 | otherwise = dep_orphs deps
187 finsts | has_finsts = ASSERT( not (imp_mod `elem` dep_finsts deps) )
188 imp_mod : dep_finsts deps
189 | otherwise = dep_finsts deps
191 pkg = modulePackageId (mi_module iface)
193 (dependent_mods, dependent_pkgs)
194 | pkg == thisPackage dflags =
195 -- Imported module is from the home package
196 -- Take its dependent modules and add imp_mod itself
197 -- Take its dependent packages unchanged
199 -- NB: (dep_mods deps) might include a hi-boot file
200 -- for the module being compiled, CM. Do *not* filter
201 -- this out (as we used to), because when we've
202 -- finished dealing with the direct imports we want to
203 -- know if any of them depended on CM.hi-boot, in
204 -- which case we should do the hi-boot consistency
205 -- check. See LoadIface.loadHiBootInterface
206 ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)
209 -- Imported module is from another package
210 -- Dump the dependent modules
211 -- Add the package imp_mod comes from to the dependent packages
212 ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
213 ([], pkg : dep_pkgs deps)
215 -- True <=> import M ()
216 import_all = case imp_details of
217 Just (is_hiding, ls) -> not is_hiding && null ls
220 imports = ImportAvails {
221 imp_mods = unitModuleEnv imp_mod [(qual_mod_name, import_all, loc)],
224 imp_dep_mods = mkModDeps dependent_mods,
225 imp_dep_pkgs = dependent_pkgs
228 -- Complain if we import a deprecated module
229 ifOptM Opt_WarnWarningsDeprecations (
231 WarnAll txt -> addWarn (moduleWarn imp_mod_name txt)
235 let new_imp_decl = L loc (ImportDecl loc_imp_mod_name mb_pkg want_boot
236 qual_only as_mod new_imp_details)
238 return (new_imp_decl, gbl_env, imports, mi_hpc iface)
241 warnRedundantSourceImport :: ModuleName -> SDoc
242 warnRedundantSourceImport mod_name
243 = ptext (sLit "Unnecessary {-# SOURCE #-} in the import of module")
244 <+> quotes (ppr mod_name)
248 %************************************************************************
250 importsFromLocalDecls
252 %************************************************************************
254 From the top-level declarations of this module produce
255 * the lexical environment
257 created by its bindings.
259 Note [Top-level Names in Template Haskell decl quotes]
260 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
261 Consider a Template Haskell declaration quotation like this:
264 When renaming the declarations inside [d| ...|], we treat the
265 top level binders specially in two ways
267 1. We give them an Internal name, not (as usual) an External one.
268 Otherwise the NameCache gets confused by a second allocation of
269 M.f. (We used to invent a fake module ThFake to avoid this, but
270 that had other problems, notably in getting the correct answer for
271 nameIsLocalOrFrom in lookupFixity. So we now leave tcg_module
274 2. We make them *shadow* the outer bindings. If we don't do that,
275 we'll get a complaint when extending the GlobalRdrEnv, saying that
276 there are two bindings for 'f'. There are several tricky points:
278 * This shadowing applies even if the binding for 'f' is in a
279 where-clause, and hence is in the *local* RdrEnv not the *global*
282 * The *qualified* name M.f from the enclosing module must certainly
283 still be available. So we don't nuke it entirely; we just make
284 it seem like qualified import.
286 * We only shadow *External* names (which come from the main module)
287 Do not shadow *Inernal* names because in the bracket
288 [d| class C a where f :: a
290 rnSrcDecls will first call extendGlobalRdrEnvRn with C[f] from the
291 class decl, and *separately* extend the envt with the value binding.
293 3. We find out whether we are inside a [d| ... |] by testing the TH
294 stage. This is a slight hack, because the stage field was really
295 meant for the type checker, and here we are not interested in the
296 fields of Brack, hence the error thunks in thRnBrack.
299 extendGlobalRdrEnvRn :: [AvailInfo]
301 -> RnM (TcGblEnv, TcLclEnv)
302 -- Updates both the GlobalRdrEnv and the FixityEnv
303 -- We return a new TcLclEnv only because we might have to
304 -- delete some bindings from it;
305 -- see Note [Top-level Names in Template Haskell decl quotes]
307 extendGlobalRdrEnvRn avails new_fixities
308 = do { (gbl_env, lcl_env) <- getEnvs
310 ; let rdr_env = tcg_rdr_env gbl_env
311 fix_env = tcg_fix_env gbl_env
313 -- Delete new_occs from global and local envs
314 -- If we are in a TemplateHaskell decl bracket,
315 -- we are going to shadow them
316 -- See Note [Top-level Names in Template Haskell decl quotes]
317 shadowP = isBrackStage stage
318 new_occs = map (nameOccName . gre_name) gres
319 rdr_env1 = transformGREs qual_gre new_occs rdr_env
320 lcl_env1 = lcl_env { tcl_rdr = delListFromOccEnv (tcl_rdr lcl_env) new_occs }
321 (rdr_env2, lcl_env2) | shadowP = (rdr_env1, lcl_env1)
322 | otherwise = (rdr_env, lcl_env)
324 rdr_env3 = foldl extendGlobalRdrEnv rdr_env2 gres
325 fix_env' = foldl extend_fix_env fix_env gres
326 (rdr_env', dups) = findLocalDupsRdrEnv rdr_env3 new_occs
328 gbl_env' = gbl_env { tcg_rdr_env = rdr_env', tcg_fix_env = fix_env' }
330 ; mapM_ addDupDeclErr dups
332 ; traceRn (text "extendGlobalRdrEnvRn" <+> (ppr new_fixities $$ ppr fix_env $$ ppr fix_env'))
333 ; return (gbl_env', lcl_env2) }
335 gres = gresFromAvails LocalDef avails
337 -- If there is a fixity decl for the gre, add it to the fixity env
338 extend_fix_env fix_env gre
339 | Just (L _ fi) <- lookupFsEnv new_fixities (occNameFS occ)
340 = extendNameEnv fix_env name (FixItem occ fi)
345 occ = nameOccName name
347 qual_gre :: GlobalRdrElt -> GlobalRdrElt
348 -- Transform top-level GREs from the module being compiled
349 -- so that they are out of the way of new definitions in a Template
351 -- See Note [Top-level Names in Template Haskell decl quotes]
352 -- Seems like 5 times as much work as it deserves!
354 -- For a LocalDef we make a (fake) qualified imported GRE for a
355 -- local GRE so that the original *qualified* name is still in scope
356 -- but the *unqualified* one no longer is. What a hack!
358 qual_gre gre@(GRE { gre_prov = LocalDef, gre_name = name })
359 | isExternalName name = gre { gre_prov = Imported [imp_spec] }
361 -- Do not shadow Internal (ie Template Haskell) Names
362 -- See Note [Top-level Names in Template Haskell decl quotes]
364 mod = ASSERT2( isExternalName name, ppr name) moduleName (nameModule name)
365 imp_spec = ImpSpec { is_item = ImpAll, is_decl = decl_spec }
366 decl_spec = ImpDeclSpec { is_mod = mod, is_as = mod,
367 is_qual = True, -- Qualified only!
368 is_dloc = srcLocSpan (nameSrcLoc name) }
370 qual_gre gre@(GRE { gre_prov = Imported specs })
371 = gre { gre_prov = Imported (map qual_spec specs) }
373 qual_spec spec@(ImpSpec { is_decl = decl_spec })
374 = spec { is_decl = decl_spec { is_qual = True } }
377 @getLocalDeclBinders@ returns the names for an @HsDecl@. It's
378 used for source code.
380 *** See "THE NAMING STORY" in HsDecls ****
382 Instances of type families
383 ~~~~~~~~~~~~~~~~~~~~~~~~~~
384 Family instances contain data constructors that we need to collect and we also
385 need to descend into the type instances of associated families in class
386 instances. The type constructor of a family instance is a usage occurence.
387 Hence, we don't return it as a subname in 'AvailInfo'; otherwise, we would get
388 a duplicate declaration error.
390 Note [Looking up family names in family instances]
391 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
396 type instance M.T Int = Bool
398 We might think that we can simply use 'lookupOccRn' when processing the type
399 instance to look up 'M.T'. Alas, we can't! The type family declaration is in
400 the *same* HsGroup as the type instance declaration. Hence, as we are
401 currently collecting the binders declared in that HsGroup, these binders will
402 not have been added to the global environment yet.
404 In the case of type classes, this problem does not arise, as a class instance
405 does not define any binders of it's own. So, we simply don't attempt to look
406 up the class names of class instances in 'get_local_binders' below.
408 If we don't look up class instances, can't we get away without looking up type
409 instances, too? No, we can't. Data type instances define data constructors
412 (1) collect those in 'get_local_binders' and
413 (2) we need to get their parent name in 'get_local_binders', too, to
414 produce an appropriate 'AvailTC'.
416 This parent name is exactly the family name of the type instance that is so
417 difficult to look up.
419 We solve this problem as follows:
421 (a) We process all type declarations other than type instances first.
422 (b) Then, we compute a 'GlobalRdrEnv' from the result of the first step.
423 (c) Finally, we process all type instances (both those on the toplevel and
424 those nested in class instances) and check for the family names in the
425 'GlobalRdrEnv' produced in the previous step before using 'lookupOccRn'.
428 getLocalNonValBinders :: HsGroup RdrName -> RnM [AvailInfo]
429 -- Get all the top-level binders bound the group *except*
430 -- for value bindings, which are treated separately
431 -- Specificaly we return AvailInfo for
432 -- type decls (incl constructors and record selectors)
433 -- class decls (including class ops)
436 -- (in hs-boot files) value signatures
438 getLocalNonValBinders group
439 = do { gbl_env <- getGblEnv
440 ; get_local_binders gbl_env group }
442 get_local_binders :: TcGblEnv -> HsGroup RdrName -> RnM [GenAvailInfo Name]
443 get_local_binders gbl_env (HsGroup {hs_valds = ValBindsIn _ val_sigs,
444 hs_tyclds = tycl_decls,
445 hs_instds = inst_decls,
446 hs_fords = foreign_decls })
447 = do { -- separate out the family instance declarations
448 let (tyinst_decls1, tycl_decls_noinsts)
449 = partition (isFamInstDecl . unLoc) tycl_decls
450 tyinst_decls = tyinst_decls1 ++ instDeclATs inst_decls
452 -- process all type/class decls except family instances
453 ; tc_names <- mapM new_tc tycl_decls_noinsts
455 -- create a temporary rdr env of the type binders
456 ; let tc_gres = gresFromAvails LocalDef tc_names
457 tc_name_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv tc_gres
459 -- process all family instances
460 ; ti_names <- mapM (new_ti tc_name_env) tyinst_decls
462 -- finish off with value binder in case of a hs-boot file
463 ; val_names <- mapM new_simple val_bndrs
464 ; return (val_names ++ tc_names ++ ti_names) }
466 is_hs_boot = isHsBoot (tcg_src gbl_env) ;
468 for_hs_bndrs :: [Located RdrName]
469 for_hs_bndrs = [nm | L _ (ForeignImport nm _ _) <- foreign_decls]
471 -- In a hs-boot file, the value binders come from the
472 -- *signatures*, and there should be no foreign binders
473 val_bndrs :: [Located RdrName]
474 val_bndrs | is_hs_boot = [nm | L _ (TypeSig nm _) <- val_sigs]
475 | otherwise = for_hs_bndrs
477 new_simple :: Located RdrName -> RnM (GenAvailInfo Name)
478 new_simple rdr_name = do
479 nm <- newTopSrcBinder rdr_name
482 new_tc tc_decl -- NOT for type/data instances
483 = do { main_name <- newTopSrcBinder main_rdr
484 ; sub_names <- mapM newTopSrcBinder sub_rdrs
485 ; return (AvailTC main_name (main_name : sub_names)) }
487 (main_rdr : sub_rdrs) = hsTyClDeclBinders tc_decl
489 new_ti tc_name_env ti_decl -- ONLY for type/data instances
490 = do { main_name <- lookupFamInstDeclBndr tc_name_env main_rdr
491 ; sub_names <- mapM newTopSrcBinder sub_rdrs
492 ; return (AvailTC main_name sub_names) }
493 -- main_name is not bound here!
495 (main_rdr : sub_rdrs) = hsTyClDeclBinders ti_decl
497 get_local_binders _ g = pprPanic "get_local_binders" (ppr g)
501 %************************************************************************
503 \subsection{Filtering imports}
505 %************************************************************************
507 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
508 available, and filters it through the import spec (if any).
511 filterImports :: ModIface
512 -> ImpDeclSpec -- The span for the entire import decl
513 -> Maybe (Bool, [LIE RdrName]) -- Import spec; True => hiding
514 -> [AvailInfo] -- What's available
515 -> RnM (Maybe (Bool, [LIE Name]), -- Import spec w/ Names
516 GlobalRdrEnv) -- Same again, but in GRE form
517 filterImports _ decl_spec Nothing all_avails
518 = return (Nothing, mkGlobalRdrEnv (gresFromAvails prov all_avails))
520 prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
523 filterImports iface decl_spec (Just (want_hiding, import_items)) all_avails
524 = do -- check for errors, convert RdrNames to Names
525 opt_typeFamilies <- doptM Opt_TypeFamilies
526 items1 <- mapM (lookup_lie opt_typeFamilies) import_items
528 let items2 :: [(LIE Name, AvailInfo)]
529 items2 = concat items1
530 -- NB the AvailInfo may have duplicates, and several items
531 -- for the same parent; e.g N(x) and N(y)
533 names = availsToNameSet (map snd items2)
534 keep n = not (n `elemNameSet` names)
535 pruned_avails = filterAvails keep all_avails
536 hiding_prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
538 gres | want_hiding = gresFromAvails hiding_prov pruned_avails
539 | otherwise = concatMap (gresFromIE decl_spec) items2
541 return (Just (want_hiding, map fst items2), mkGlobalRdrEnv gres)
543 -- This environment is how we map names mentioned in the import
544 -- list to the actual Name they correspond to, and the name family
545 -- that the Name belongs to (the AvailInfo). The situation is
546 -- complicated by associated families, which introduce a three-level
547 -- hierachy, where class = grand parent, assoc family = parent, and
548 -- data constructors = children. The occ_env entries for associated
549 -- families needs to capture all this information; hence, we have the
550 -- third component of the environment that gives the class name (=
551 -- grand parent) in case of associated families.
553 -- This env will have entries for data constructors too,
554 -- they won't make any difference because naked entities like T
555 -- in an import list map to TcOccs, not VarOccs.
556 occ_env :: OccEnv (Name, -- the name
557 AvailInfo, -- the export item providing the name
558 Maybe Name) -- the parent of associated types
559 occ_env = mkOccEnv_C combine [ (nameOccName n, (n, a, Nothing))
560 | a <- all_avails, n <- availNames a]
562 -- we know that (1) there are at most entries for one name, (2) their
563 -- first component is identical, (3) they are for tys/cls, and (4) one
564 -- entry has the name in its parent position (the other doesn't)
565 combine (name, AvailTC p1 subs1, Nothing)
566 (_ , AvailTC p2 subs2, Nothing)
568 (parent, subs) = if p1 == name then (p2, subs1) else (p1, subs2)
570 (name, AvailTC name subs, Just parent)
571 combine x y = pprPanic "filterImports/combine" (ppr x $$ ppr y)
573 lookup_lie :: Bool -> LIE RdrName -> TcRn [(LIE Name, AvailInfo)]
574 lookup_lie opt_typeFamilies (L loc ieRdr)
576 stuff <- setSrcSpan loc $
577 case lookup_ie opt_typeFamilies ieRdr of
578 Failed err -> addErr err >> return []
579 Succeeded a -> return a
580 checkDodgyImport stuff
581 return [ (L loc ie, avail) | (ie,avail) <- stuff ]
583 -- Warn when importing T(..) if T was exported abstractly
584 checkDodgyImport stuff
585 | IEThingAll n <- ieRdr, (_, AvailTC _ [_]):_ <- stuff
586 = ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn n))
587 -- NB. use the RdrName for reporting the warning
591 -- For each import item, we convert its RdrNames to Names,
592 -- and at the same time construct an AvailInfo corresponding
593 -- to what is actually imported by this item.
594 -- Returns Nothing on error.
595 -- We return a list here, because in the case of an import
596 -- item like C, if we are hiding, then C refers to *both* a
597 -- type/class and a data constructor. Moreover, when we import
598 -- data constructors of an associated family, we need separate
599 -- AvailInfos for the data constructors and the family (as they have
600 -- different parents). See the discussion at occ_env.
601 lookup_ie :: Bool -> IE RdrName -> MaybeErr Message [(IE Name,AvailInfo)]
602 lookup_ie opt_typeFamilies ie
603 = let bad_ie :: MaybeErr Message a
604 bad_ie = Failed (badImportItemErr iface decl_spec ie)
607 | isQual rdr = Failed (qualImportItemErr rdr)
608 | Just nm <- lookupOccEnv occ_env (rdrNameOcc rdr) = return nm
613 (name, avail, _) <- lookup_name n
614 return [(IEVar name, trimAvail avail name)]
617 (name, avail@(AvailTC name2 subs), mb_parent) <- lookup_name tc
619 -- non-associated ty/cls
620 Nothing -> return [(IEThingAll name, avail)]
622 Just parent -> return [(IEThingAll name,
623 AvailTC name2 (subs \\ [name])),
624 (IEThingAll name, AvailTC parent [name])]
627 | want_hiding -- hiding ( C )
628 -- Here the 'C' can be a data constructor
629 -- *or* a type/class, or even both
630 -> let tc_name = lookup_name tc
631 dc_name = lookup_name (setRdrNameSpace tc srcDataName)
633 case catMaybeErr [ tc_name, dc_name ] of
635 names -> return [mkIEThingAbs name | name <- names]
637 -> do nameAvail <- lookup_name tc
638 return [mkIEThingAbs nameAvail]
640 IEThingWith tc ns -> do
641 (name, AvailTC _ subnames, mb_parent) <- lookup_name tc
643 env = mkOccEnv [(nameOccName s, s) | s <- subnames]
644 mb_children = map (lookupOccEnv env . rdrNameOcc) ns
645 children <- if any isNothing mb_children
647 else return (catMaybes mb_children)
648 -- check for proper import of type families
649 when (not opt_typeFamilies && any isTyConName children) $
650 Failed (typeItemErr (head . filter isTyConName $ children)
651 (text "in import list"))
653 -- non-associated ty/cls
654 Nothing -> return [(IEThingWith name children,
655 AvailTC name (name:children))]
657 Just parent -> return [(IEThingWith name children,
658 AvailTC name children),
659 (IEThingWith name children,
660 AvailTC parent [name])]
662 _other -> Failed illegalImportItemErr
663 -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed
667 mkIEThingAbs (n, av, Nothing ) = (IEThingAbs n, trimAvail av n)
668 mkIEThingAbs (n, _, Just parent) = (IEThingAbs n, AvailTC parent [n])
671 catMaybeErr :: [MaybeErr err a] -> [a]
672 catMaybeErr ms = [ a | Succeeded a <- ms ]
675 %************************************************************************
679 %************************************************************************
682 -- | make a 'GlobalRdrEnv' where all the elements point to the same
683 -- import declaration (useful for "hiding" imports, or imports with
685 gresFromAvails :: Provenance -> [AvailInfo] -> [GlobalRdrElt]
686 gresFromAvails prov avails
687 = concatMap (gresFromAvail (const prov)) avails
689 gresFromAvail :: (Name -> Provenance) -> AvailInfo -> [GlobalRdrElt]
690 gresFromAvail prov_fn avail
691 = [ GRE {gre_name = n,
692 gre_par = availParent n avail,
693 gre_prov = prov_fn n}
694 | n <- availNames avail ]
696 greAvail :: GlobalRdrElt -> AvailInfo
697 greAvail gre = mkUnitAvail (gre_name gre) (gre_par gre)
699 mkUnitAvail :: Name -> Parent -> AvailInfo
700 mkUnitAvail me (ParentIs p) = AvailTC p [me]
701 mkUnitAvail me NoParent | isTyConName me = AvailTC me [me]
702 | otherwise = Avail me
704 plusAvail :: GenAvailInfo Name -> GenAvailInfo Name -> GenAvailInfo Name
705 plusAvail (Avail n1) (Avail _) = Avail n1
706 plusAvail (AvailTC _ ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
707 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
709 availParent :: Name -> AvailInfo -> Parent
710 availParent _ (Avail _) = NoParent
711 availParent n (AvailTC m _) | n == m = NoParent
712 | otherwise = ParentIs m
714 trimAvail :: AvailInfo -> Name -> AvailInfo
715 trimAvail (Avail n) _ = Avail n
716 trimAvail (AvailTC n ns) m = ASSERT( m `elem` ns) AvailTC n [m]
718 -- | filters 'AvailInfo's by the given predicate
719 filterAvails :: (Name -> Bool) -> [AvailInfo] -> [AvailInfo]
720 filterAvails keep avails = foldr (filterAvail keep) [] avails
722 -- | filters an 'AvailInfo' by the given predicate
723 filterAvail :: (Name -> Bool) -> AvailInfo -> [AvailInfo] -> [AvailInfo]
724 filterAvail keep ie rest =
726 Avail n | keep n -> ie : rest
729 let left = filter keep ns in
730 if null left then rest else AvailTC tc left : rest
732 -- | Given an import\/export spec, construct the appropriate 'GlobalRdrElt's.
733 gresFromIE :: ImpDeclSpec -> (LIE Name, AvailInfo) -> [GlobalRdrElt]
734 gresFromIE decl_spec (L loc ie, avail)
735 = gresFromAvail prov_fn avail
737 is_explicit = case ie of
738 IEThingAll name -> \n -> n == name
740 prov_fn name = Imported [imp_spec]
742 imp_spec = ImpSpec { is_decl = decl_spec, is_item = item_spec }
743 item_spec = ImpSome { is_explicit = is_explicit name, is_iloc = loc }
745 mkChildEnv :: [GlobalRdrElt] -> NameEnv [Name]
746 mkChildEnv gres = foldr add emptyNameEnv gres
748 add (GRE { gre_name = n, gre_par = ParentIs p }) env = extendNameEnv_Acc (:) singleton env p n
751 findChildren :: NameEnv [Name] -> Name -> [Name]
752 findChildren env n = lookupNameEnv env n `orElse` []
755 ---------------------------------------
758 All this AvailEnv stuff is hardly used; only in a very small
759 part of RnNames. Todo: remove?
760 ---------------------------------------
763 type AvailEnv = NameEnv AvailInfo -- Maps a Name to the AvailInfo that contains it
765 emptyAvailEnv :: AvailEnv
766 emptyAvailEnv = emptyNameEnv
769 unitAvailEnv :: AvailInfo -> AvailEnv
770 unitAvailEnv a = unitNameEnv (availName a) a
772 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
773 plusAvailEnv = plusNameEnv_C plusAvail
775 availEnvElts :: AvailEnv -> [AvailInfo]
776 availEnvElts = nameEnvElts
779 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
780 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
782 mkAvailEnv :: [AvailInfo] -> AvailEnv
783 -- 'avails' may have several items with the same availName
784 -- E.g import Ix( Ix(..), index )
785 -- will give Ix(Ix,index,range) and Ix(index)
786 -- We want to combine these; addAvail does that
787 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
789 -- After combining the avails, we need to ensure that the parent name is the
790 -- first entry in the list of subnames, if it is included at all. (Subsequent
791 -- functions rely on that.)
792 normaliseAvail :: AvailInfo -> AvailInfo
793 normaliseAvail avail@(Avail _) = avail
794 normaliseAvail (AvailTC name subs) = AvailTC name subs'
796 subs' = if name `elem` subs then name : (delete name subs) else subs
798 -- | combines 'AvailInfo's from the same family
799 nubAvails :: [AvailInfo] -> [AvailInfo]
800 nubAvails avails = map normaliseAvail . nameEnvElts . mkAvailEnv $ avails
804 %************************************************************************
806 \subsection{Export list processing}
808 %************************************************************************
810 Processing the export list.
812 You might think that we should record things that appear in the export
813 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
814 wrong. We do check (here) that they are in scope, but there is no
815 need to slurp in their actual declaration (which is what
816 @addOccurrenceName@ forces).
818 Indeed, doing so would big trouble when compiling @PrelBase@, because
819 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
820 @ConcBase.StateAndSynchVar#@, and so on...
823 type ExportAccum -- The type of the accumulating parameter of
824 -- the main worker function in rnExports
825 = ([LIE Name], -- Export items with Names
826 ExportOccMap, -- Tracks exported occurrence names
827 [AvailInfo]) -- The accumulated exported stuff
830 emptyExportAccum :: ExportAccum
831 emptyExportAccum = ([], emptyOccEnv, [])
833 type ExportOccMap = OccEnv (Name, IE RdrName)
834 -- Tracks what a particular exported OccName
835 -- in an export list refers to, and which item
836 -- it came from. It's illegal to export two distinct things
837 -- that have the same occurrence name
839 rnExports :: Bool -- False => no 'module M(..) where' header at all
840 -> Maybe [LIE RdrName] -- Nothing => no explicit export list
844 -- Complains if two distinct exports have same OccName
845 -- Warns about identical exports.
846 -- Complains about exports items not in scope
848 rnExports explicit_mod exports
849 tcg_env@(TcGblEnv { tcg_mod = this_mod,
850 tcg_rdr_env = rdr_env,
851 tcg_imports = imports })
853 -- If the module header is omitted altogether, then behave
854 -- as if the user had written "module Main(main) where..."
855 -- EXCEPT in interactive mode, when we behave as if he had
856 -- written "module Main where ..."
857 -- Reason: don't want to complain about 'main' not in scope
858 -- in interactive mode
861 | explicit_mod = exports
862 | ghcLink dflags == LinkInMemory = Nothing
863 | otherwise = Just ([noLoc (IEVar main_RDR_Unqual)])
864 -- ToDo: the 'noLoc' here is unhelpful if 'main'
865 -- turns out to be out of scope
867 ; (rn_exports, avails) <- exports_from_avail real_exports rdr_env imports this_mod
868 ; let final_avails = nubAvails avails -- Combine families
870 ; return (tcg_env { tcg_exports = final_avails,
871 tcg_rn_exports = case tcg_rn_exports tcg_env of
873 Just _ -> rn_exports,
874 tcg_dus = tcg_dus tcg_env `plusDU`
875 usesOnly (availsToNameSet final_avails) }) }
877 exports_from_avail :: Maybe [LIE RdrName]
878 -- Nothing => no explicit export list
882 -> RnM (Maybe [LIE Name], [AvailInfo])
884 exports_from_avail Nothing rdr_env _imports _this_mod
885 = -- The same as (module M) where M is the current module name,
886 -- so that's how we handle it.
888 avails = [ greAvail gre | gre <- globalRdrEnvElts rdr_env,
891 return (Nothing, avails)
893 exports_from_avail (Just rdr_items) rdr_env imports this_mod
894 = do (ie_names, _, exports) <- foldlM do_litem emptyExportAccum rdr_items
896 return (Just ie_names, exports)
898 do_litem :: ExportAccum -> LIE RdrName -> RnM ExportAccum
899 do_litem acc lie = setSrcSpan (getLoc lie) (exports_from_item acc lie)
901 kids_env :: NameEnv [Name] -- Maps a parent to its in-scope children
902 kids_env = mkChildEnv (globalRdrEnvElts rdr_env)
904 imported_modules = [ qual_name
905 | xs <- moduleEnvElts $ imp_mods imports,
906 (qual_name, _, _) <- xs ]
908 exports_from_item :: ExportAccum -> LIE RdrName -> RnM ExportAccum
909 exports_from_item acc@(ie_names, occs, exports)
910 (L loc ie@(IEModuleContents mod))
911 | let earlier_mods = [ mod | (L _ (IEModuleContents mod)) <- ie_names ]
912 , mod `elem` earlier_mods -- Duplicate export of M
913 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
914 warnIf warn_dup_exports (dupModuleExport mod) ;
918 = do { implicit_prelude <- doptM Opt_ImplicitPrelude
919 ; warnDodgyExports <- doptM Opt_WarnDodgyExports
920 ; let { exportValid = (mod `elem` imported_modules)
921 || (moduleName this_mod == mod)
922 ; gres = filter (isModuleExported implicit_prelude mod)
923 (globalRdrEnvElts rdr_env)
924 ; names = map gre_name gres
927 ; checkErr exportValid (moduleNotImported mod)
928 ; warnIf (warnDodgyExports && exportValid && null gres) (nullModuleExport mod)
930 ; addUsedRdrNames (concat [ [mkRdrQual mod occ, mkRdrUnqual occ]
931 | occ <- map nameOccName names ])
932 -- The qualified and unqualified version of all of
933 -- these names are, in effect, used by this export
935 ; occs' <- check_occs ie occs names
936 -- This check_occs not only finds conflicts
937 -- between this item and others, but also
938 -- internally within this item. That is, if
939 -- 'M.x' is in scope in several ways, we'll have
940 -- several members of mod_avails with the same
942 ; return (L loc (IEModuleContents mod) : ie_names,
943 occs', map greAvail gres ++ exports) }
945 exports_from_item acc@(lie_names, occs, exports) (L loc ie)
947 = do new_ie <- lookup_doc_ie ie
948 return (L loc new_ie : lie_names, occs, exports)
951 = do (new_ie, avail) <- lookup_ie ie
952 if isUnboundName (ieName new_ie)
953 then return acc -- Avoid error cascade
956 occs' <- check_occs ie occs (availNames avail)
958 return (L loc new_ie : lie_names, occs', avail : exports)
961 lookup_ie :: IE RdrName -> RnM (IE Name, AvailInfo)
962 lookup_ie (IEVar rdr)
963 = do gre <- lookupGreRn rdr
964 return (IEVar (gre_name gre), greAvail gre)
966 lookup_ie (IEThingAbs rdr)
967 = do gre <- lookupGreRn rdr
968 let name = gre_name gre
970 NoParent -> return (IEThingAbs name,
972 ParentIs p -> return (IEThingAbs name,
975 lookup_ie ie@(IEThingAll rdr)
976 = do name <- lookupGlobalOccRn rdr
977 let kids = findChildren kids_env name
978 mkKidRdrName = case isQual_maybe rdr of
979 Nothing -> mkRdrUnqual
980 Just (modName, _) -> mkRdrQual modName
981 addUsedRdrNames $ map (mkKidRdrName . nameOccName) kids
982 warnDodgyExports <- doptM Opt_WarnDodgyExports
985 then when warnDodgyExports $ addWarn (dodgyExportWarn name)
986 else -- This occurs when you export T(..), but
987 -- only import T abstractly, or T is a synonym.
988 addErr (exportItemErr ie)
990 return (IEThingAll name, AvailTC name (name:kids))
992 lookup_ie ie@(IEThingWith rdr sub_rdrs)
993 = do name <- lookupGlobalOccRn rdr
994 if isUnboundName name
995 then return (IEThingWith name [], AvailTC name [name])
997 let env = mkOccEnv [ (nameOccName s, s)
998 | s <- findChildren kids_env name ]
999 mb_names = map (lookupOccEnv env . rdrNameOcc) sub_rdrs
1000 if any isNothing mb_names
1001 then do addErr (exportItemErr ie)
1002 return (IEThingWith name [], AvailTC name [name])
1003 else do let names = catMaybes mb_names
1004 optTyFam <- doptM Opt_TypeFamilies
1005 when (not optTyFam && any isTyConName names) $
1006 addErr (typeItemErr ( head
1007 . filter isTyConName
1009 (text "in export list"))
1010 return (IEThingWith name names, AvailTC name (name:names))
1012 lookup_ie _ = panic "lookup_ie" -- Other cases covered earlier
1015 lookup_doc_ie :: IE RdrName -> RnM (IE Name)
1016 lookup_doc_ie (IEGroup lev doc) = do rn_doc <- rnHsDoc doc
1017 return (IEGroup lev rn_doc)
1018 lookup_doc_ie (IEDoc doc) = do rn_doc <- rnHsDoc doc
1019 return (IEDoc rn_doc)
1020 lookup_doc_ie (IEDocNamed str) = return (IEDocNamed str)
1021 lookup_doc_ie _ = panic "lookup_doc_ie" -- Other cases covered earlier
1024 isDoc :: IE RdrName -> Bool
1025 isDoc (IEDoc _) = True
1026 isDoc (IEDocNamed _) = True
1027 isDoc (IEGroup _ _) = True
1030 -------------------------------
1031 isModuleExported :: Bool -> ModuleName -> GlobalRdrElt -> Bool
1032 -- True if the thing is in scope *both* unqualified, *and* with qualifier M
1033 isModuleExported implicit_prelude mod (GRE { gre_name = name, gre_prov = prov })
1034 | implicit_prelude && isBuiltInSyntax name = False
1035 -- Optimisation: filter out names for built-in syntax
1036 -- They just clutter up the environment (esp tuples), and the parser
1037 -- will generate Exact RdrNames for them, so the cluttered
1038 -- envt is no use. To avoid doing this filter all the time,
1039 -- we use -XNoImplicitPrelude as a clue that the filter is
1040 -- worth while. Really, it's only useful for GHC.Base and GHC.Tuple.
1042 -- It's worth doing because it makes the environment smaller for
1043 -- every module that imports the Prelude
1046 LocalDef | Just name_mod <- nameModule_maybe name
1047 -> moduleName name_mod == mod
1048 | otherwise -> False
1049 Imported is -> any unQualSpecOK is && any (qualSpecOK mod) is
1051 -------------------------------
1052 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
1053 check_occs ie occs names
1054 = foldlM check occs names
1057 = case lookupOccEnv occs name_occ of
1058 Nothing -> return (extendOccEnv occs name_occ (name, ie))
1061 | name == name' -- Duplicate export
1062 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
1063 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
1066 | otherwise -- Same occ name but different names: an error
1067 -> do { global_env <- getGlobalRdrEnv ;
1068 addErr (exportClashErr global_env name' name ie' ie) ;
1071 name_occ = nameOccName name
1074 %*********************************************************
1078 %*********************************************************
1081 finishWarnings :: DynFlags -> Maybe WarningTxt
1082 -> TcGblEnv -> RnM TcGblEnv
1083 -- (a) Report usage of imports that are deprecated or have other warnings
1084 -- (b) If the whole module is warned about or deprecated, update tcg_warns
1085 -- All this happens only once per module
1086 finishWarnings dflags mod_warn tcg_env
1087 = do { (eps,hpt) <- getEpsAndHpt
1088 ; ifOptM Opt_WarnWarningsDeprecations $
1089 mapM_ (check hpt (eps_PIT eps)) all_gres
1090 -- By this time, typechecking is complete,
1091 -- so the PIT is fully populated
1093 -- Deal with a module deprecation; it overrides all existing warns
1094 ; let new_warns = case mod_warn of
1095 Just txt -> WarnAll txt
1096 Nothing -> tcg_warns tcg_env
1097 ; return (tcg_env { tcg_warns = new_warns }) }
1099 used_names = allUses (tcg_dus tcg_env)
1100 -- Report on all deprecated uses; hence allUses
1101 all_gres = globalRdrEnvElts (tcg_rdr_env tcg_env)
1103 check hpt pit gre@(GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
1104 | name `elemNameSet` used_names
1105 , Just deprec_txt <- lookupImpDeprec dflags hpt pit gre
1106 = addWarnAt (importSpecLoc imp_spec)
1107 (sep [ptext (sLit "In the use of") <+>
1108 pprNonVarNameSpace (occNameSpace (nameOccName name)) <+>
1110 (parens imp_msg) <> colon,
1113 name_mod = ASSERT2( isExternalName name, ppr name ) nameModule name
1114 imp_mod = importSpecModule imp_spec
1115 imp_msg = ptext (sLit "imported from") <+> ppr imp_mod <> extra
1116 extra | imp_mod == moduleName name_mod = empty
1117 | otherwise = ptext (sLit ", but defined in") <+> ppr name_mod
1119 check _ _ _ = return () -- Local, or not used, or not deprectated
1120 -- The Imported pattern-match: don't deprecate locally defined names
1121 -- For a start, we may be exporting a deprecated thing
1122 -- Also we may use a deprecated thing in the defn of another
1123 -- deprecated things. We may even use a deprecated thing in
1124 -- the defn of a non-deprecated thing, when changing a module's
1127 lookupImpDeprec :: DynFlags -> HomePackageTable -> PackageIfaceTable
1128 -> GlobalRdrElt -> Maybe WarningTxt
1129 -- The name is definitely imported, so look in HPT, PIT
1130 lookupImpDeprec dflags hpt pit gre
1131 = case lookupIfaceByModule dflags hpt pit mod of
1132 Just iface -> mi_warn_fn iface name `mplus` -- Bleat if the thing, *or
1134 ParentIs p -> mi_warn_fn iface p -- its parent*, is warn'd
1137 Nothing -> Nothing -- See Note [Used names with interface not loaded]
1140 mod = ASSERT2( isExternalName name, ppr name ) nameModule name
1143 Note [Used names with interface not loaded]
1144 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1145 By now all the interfaces should have been loaded,
1146 because reportDeprecations happens after typechecking.
1147 However, it's still (just) possible to to find a used
1148 Name whose interface hasn't been loaded:
1150 a) It might be a WiredInName; in that case we may not load
1151 its interface (although we could).
1153 b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
1154 These are seen as "used" by the renamer (if -XNoImplicitPrelude)
1155 is on), but the typechecker may discard their uses
1156 if in fact the in-scope fromRational is GHC.Read.fromRational,
1157 (see tcPat.tcOverloadedLit), and the typechecker sees that the type
1158 is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
1159 In that obscure case it won't force the interface in.
1161 In both cases we simply don't permit deprecations;
1162 this is, after all, wired-in stuff.
1165 %*********************************************************
1169 %*********************************************************
1172 reportUnusedNames :: Maybe [LIE RdrName] -- Export list
1173 -> TcGblEnv -> RnM ()
1174 reportUnusedNames _export_decls gbl_env
1175 = do { traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env)))
1176 ; warnUnusedImportDecls gbl_env
1177 ; warnUnusedTopBinds unused_locals }
1179 used_names :: NameSet
1180 used_names = findUses (tcg_dus gbl_env) emptyNameSet
1181 -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
1184 -- Collect the defined names from the in-scope environment
1185 defined_names :: [GlobalRdrElt]
1186 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
1188 -- Note that defined_and_used, defined_but_not_used
1189 -- are both [GRE]; that's why we need defined_and_used
1190 -- rather than just used_names
1191 _defined_and_used, defined_but_not_used :: [GlobalRdrElt]
1192 (_defined_and_used, defined_but_not_used)
1193 = partition (gre_is_used used_names) defined_names
1195 kids_env = mkChildEnv defined_names
1196 -- This is done in mkExports too; duplicated work
1198 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
1199 gre_is_used used_names (GRE {gre_name = name})
1200 = name `elemNameSet` used_names
1201 || any (`elemNameSet` used_names) (findChildren kids_env name)
1202 -- A use of C implies a use of T,
1203 -- if C was brought into scope by T(..) or T(C)
1205 -- Filter out the ones that are
1206 -- (a) defined in this module, and
1207 -- (b) not defined by a 'deriving' clause
1208 -- The latter have an Internal Name, so we can filter them out easily
1209 unused_locals :: [GlobalRdrElt]
1210 unused_locals = filter is_unused_local defined_but_not_used
1211 is_unused_local :: GlobalRdrElt -> Bool
1212 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
1215 %*********************************************************
1219 %*********************************************************
1221 This code finds which import declarations are unused. The
1222 specification and implementation notes are here:
1223 http://hackage.haskell.org/trac/ghc/wiki/Commentary/Compiler/UnusedImports
1226 type ImportDeclUsage
1227 = ( LImportDecl Name -- The import declaration
1228 , [AvailInfo] -- What *is* used (normalised)
1229 , [Name] ) -- What is imported but *not* used
1233 warnUnusedImportDecls :: TcGblEnv -> RnM ()
1234 warnUnusedImportDecls gbl_env
1235 = do { uses <- readMutVar (tcg_used_rdrnames gbl_env)
1236 ; let imports = filter explicit_import (tcg_rn_imports gbl_env)
1237 rdr_env = tcg_rdr_env gbl_env
1239 ; let usage :: [ImportDeclUsage]
1240 usage = findImportUsage imports rdr_env (Set.elems uses)
1242 ; ifOptM Opt_WarnUnusedImports $
1243 mapM_ warnUnusedImport usage
1245 ; ifOptM Opt_D_dump_minimal_imports $
1246 printMinimalImports usage }
1248 explicit_import (L loc _) = isGoodSrcSpan loc
1249 -- Filter out the implicit Prelude import
1250 -- which we do not want to bleat about
1254 findImportUsage :: [LImportDecl Name]
1257 -> [ImportDeclUsage]
1259 type ImportMap = FiniteMap SrcLoc [AvailInfo]
1260 -- The intermediate data struture records, for each import
1261 -- declaration, what stuff brought into scope by that
1262 -- declaration is actually used in the module.
1264 -- The SrcLoc is the location of the start
1265 -- of a particular 'import' declaration
1267 -- The AvailInfos are the things imported from that decl
1268 -- (just a list, not normalised)
1270 findImportUsage imports rdr_env rdrs
1271 = map unused_decl imports
1273 import_usage :: ImportMap
1274 import_usage = foldr add_rdr emptyFM rdrs
1276 unused_decl decl@(L loc (ImportDecl { ideclHiding = imps }))
1277 = (decl, nubAvails used_avails, unused_imps)
1279 used_avails = lookupFM import_usage (srcSpanStart loc) `orElse` []
1280 used_names = availsToNameSet used_avails
1282 unused_imps = case imps of
1283 Just (False, imp_ies) -> nameSetToList unused_imps
1285 imp_names = mkNameSet (concatMap (ieNames . unLoc) imp_ies)
1286 unused_imps = imp_names `minusNameSet` used_names
1288 _other -> [] -- No explicit import list => no unused-name list
1290 add_rdr :: RdrName -> ImportMap -> ImportMap
1292 = case lookupGRE_RdrName rdr rdr_env of
1293 [gre] | Imported imps <- gre_prov gre
1294 -> add_imp gre (bestImport imps) iu
1297 add_imp :: GlobalRdrElt -> ImportSpec -> ImportMap -> ImportMap
1298 add_imp gre (ImpSpec { is_decl = imp_decl_spec }) iu
1299 = addToFM_C add iu decl_loc [avail]
1301 add avails _ = avail : avails
1302 decl_loc = srcSpanStart (is_dloc imp_decl_spec)
1304 avail = case gre_par gre of
1305 ParentIs p -> AvailTC p [p,name]
1306 NoParent | isTyConName name -> AvailTC name [name]
1307 | otherwise -> Avail name
1308 -- If you use (+) from Num, then for this purpose we want
1309 -- to say that Num is used as well. That is why in the
1310 -- ParentIs case we have [p,name] in the ParentIs case
1312 bestImport :: [ImportSpec] -> ImportSpec
1314 = case partition isImpAll iss of
1315 ([], imp_somes) -> textuallyFirst imp_somes
1316 (imp_alls, _) -> textuallyFirst imp_alls
1318 textuallyFirst :: [ImportSpec] -> ImportSpec
1319 textuallyFirst iss = case sortWith (is_dloc . is_decl) iss of
1320 [] -> pprPanic "textuallyFirst" (ppr iss)
1323 isImpAll :: ImportSpec -> Bool
1324 isImpAll (ImpSpec { is_item = ImpAll }) = True
1325 isImpAll _other = False
1329 warnUnusedImport :: ImportDeclUsage -> RnM ()
1330 warnUnusedImport (L loc decl, used, unused)
1331 | Just (False,[]) <- ideclHiding decl
1332 = return () -- Do not warn for 'import M()'
1333 | null used = addWarnAt loc msg1 -- Nothing used; drop entire decl
1334 | null unused = return () -- Everything imported is used; nop
1335 | otherwise = addWarnAt loc msg2 -- Some imports are unused
1337 msg1 = vcat [pp_herald <+> quotes pp_mod <+> pp_not_used,
1338 nest 2 (ptext (sLit "except perhaps to import instances from")
1340 ptext (sLit "To import instances alone, use:")
1341 <+> ptext (sLit "import") <+> pp_mod <> parens empty ]
1342 msg2 = sep [pp_herald <+> quotes (pprWithCommas ppr unused),
1343 text "from module" <+> quotes pp_mod <+> pp_not_used]
1344 pp_herald = text "The import of"
1345 pp_mod = ppr (unLoc (ideclName decl))
1346 pp_not_used = text "is redundant"
1349 To print the minimal imports we walk over the user-supplied import
1350 decls, and simply trim their import lists. NB that
1352 * We do *not* change the 'qualified' or 'as' parts!
1354 * We do not disard a decl altogether; we might need instances
1355 from it. Instead we just trim to an empty import list
1358 printMinimalImports :: [ImportDeclUsage] -> RnM ()
1359 printMinimalImports imports_w_usage
1360 = do { imports' <- mapM mk_minimal imports_w_usage
1361 ; this_mod <- getModule
1363 do { h <- openFile (mkFilename this_mod) WriteMode
1364 ; printForUser h neverQualify (vcat (map ppr imports')) }
1365 -- The neverQualify is important. We are printing Names
1366 -- but they are in the context of an 'import' decl, and
1367 -- we never qualify things inside there
1368 -- E.g. import Blag( f, b )
1369 -- not import Blag( Blag.f, Blag.g )!
1372 mkFilename this_mod = moduleNameString (moduleName this_mod) ++ ".imports"
1374 mk_minimal (L l decl, used, unused)
1376 , Just (False, _) <- ideclHiding decl
1379 = do { ies <- initIfaceTcRn $ mapM to_ie used
1380 ; return (L l (decl { ideclHiding = Just (False, map (L l) ies) })) }
1382 to_ie :: AvailInfo -> IfG (IE Name)
1383 -- The main trick here is that if we're importing all the constructors
1384 -- we want to say "T(..)", but if we're importing only a subset we want
1385 -- to say "T(A,B,C)". So we have to find out what the module exports.
1386 to_ie (Avail n) = return (IEVar n)
1387 to_ie (AvailTC n [m]) = ASSERT( n==m )
1388 return (IEThingAbs n)
1389 to_ie (AvailTC n ns) = do
1390 iface <- loadSysInterface doc n_mod
1391 case [xs | (m,as) <- mi_exports iface,
1394 x == nameOccName n] of
1395 [xs] | all_used xs -> return (IEThingAll n)
1396 | otherwise -> return (IEThingWith n (filter (/= n) ns))
1397 other -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
1400 all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
1401 doc = text "Compute minimal imports from" <+> ppr n
1402 n_mod = ASSERT( isExternalName n ) nameModule n
1405 %************************************************************************
1409 %************************************************************************
1412 qualImportItemErr :: RdrName -> SDoc
1413 qualImportItemErr rdr
1414 = hang (ptext (sLit "Illegal qualified name in import item:"))
1417 badImportItemErr :: ModIface -> ImpDeclSpec -> IE RdrName -> SDoc
1418 badImportItemErr iface decl_spec ie
1419 = sep [ptext (sLit "Module"), quotes (ppr (is_mod decl_spec)), source_import,
1420 ptext (sLit "does not export"), quotes (ppr ie)]
1422 source_import | mi_boot iface = ptext (sLit "(hi-boot interface)")
1425 illegalImportItemErr :: SDoc
1426 illegalImportItemErr = ptext (sLit "Illegal import item")
1428 dodgyImportWarn :: RdrName -> SDoc
1429 dodgyImportWarn item = dodgyMsg (ptext (sLit "import")) item
1430 dodgyExportWarn :: Name -> SDoc
1431 dodgyExportWarn item = dodgyMsg (ptext (sLit "export")) item
1433 dodgyMsg :: OutputableBndr n => SDoc -> n -> SDoc
1435 = sep [ ptext (sLit "The") <+> kind <+> ptext (sLit "item") <+> quotes (ppr (IEThingAll tc))
1436 <+> ptext (sLit "suggests that"),
1437 quotes (ppr tc) <+> ptext (sLit "has (in-scope) constructors or class methods,"),
1438 ptext (sLit "but it has none") ]
1440 exportItemErr :: IE RdrName -> SDoc
1441 exportItemErr export_item
1442 = sep [ ptext (sLit "The export item") <+> quotes (ppr export_item),
1443 ptext (sLit "attempts to export constructors or class methods that are not visible here") ]
1445 typeItemErr :: Name -> SDoc -> SDoc
1446 typeItemErr name wherestr
1447 = sep [ ptext (sLit "Using 'type' tag on") <+> quotes (ppr name) <+> wherestr,
1448 ptext (sLit "Use -XTypeFamilies to enable this extension") ]
1450 exportClashErr :: GlobalRdrEnv -> Name -> Name -> IE RdrName -> IE RdrName
1452 exportClashErr global_env name1 name2 ie1 ie2
1453 = vcat [ ptext (sLit "Conflicting exports for") <+> quotes (ppr occ) <> colon
1454 , ppr_export ie1' name1'
1455 , ppr_export ie2' name2' ]
1457 occ = nameOccName name1
1458 ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext (sLit "exports") <+>
1459 quotes (ppr name) <+> pprNameProvenance (get_gre name))
1461 -- get_gre finds a GRE for the Name, so that we can show its provenance
1463 = case lookupGRE_Name global_env name of
1465 [] -> pprPanic "exportClashErr" (ppr name)
1466 get_loc name = nameSrcLoc $ gre_name $ get_gre name
1467 (name1', ie1', name2', ie2') = if get_loc name1 < get_loc name2
1468 then (name1, ie1, name2, ie2)
1469 else (name2, ie2, name1, ie1)
1471 addDupDeclErr :: [Name] -> TcRn ()
1473 = panic "addDupDeclErr: empty list"
1474 addDupDeclErr names@(name : _)
1475 = addErrAt (getSrcSpan (last sorted_names)) $
1476 -- Report the error at the later location
1477 vcat [ptext (sLit "Multiple declarations of") <+> quotes (ppr name),
1478 ptext (sLit "Declared at:") <+> vcat (map (ppr . nameSrcLoc) sorted_names)]
1480 sorted_names = sortWith nameSrcLoc names
1482 dupExportWarn :: OccName -> IE RdrName -> IE RdrName -> SDoc
1483 dupExportWarn occ_name ie1 ie2
1484 = hsep [quotes (ppr occ_name),
1485 ptext (sLit "is exported by"), quotes (ppr ie1),
1486 ptext (sLit "and"), quotes (ppr ie2)]
1488 dupModuleExport :: ModuleName -> SDoc
1490 = hsep [ptext (sLit "Duplicate"),
1491 quotes (ptext (sLit "Module") <+> ppr mod),
1492 ptext (sLit "in export list")]
1494 moduleNotImported :: ModuleName -> SDoc
1495 moduleNotImported mod
1496 = ptext (sLit "The export item `module") <+> ppr mod <>
1497 ptext (sLit "' is not imported")
1499 nullModuleExport :: ModuleName -> SDoc
1500 nullModuleExport mod
1501 = ptext (sLit "The export item `module") <+> ppr mod <> ptext (sLit "' exports nothing")
1503 missingImportListWarn :: ModuleName -> SDoc
1504 missingImportListWarn mod
1505 = ptext (sLit "The module") <+> quotes (ppr mod) <+> ptext (sLit "does not have an explicit import list")
1507 moduleWarn :: ModuleName -> WarningTxt -> SDoc
1508 moduleWarn mod (WarningTxt txt)
1509 = sep [ ptext (sLit "Module") <+> quotes (ppr mod) <> ptext (sLit ":"),
1510 nest 2 (vcat (map ppr txt)) ]
1511 moduleWarn mod (DeprecatedTxt txt)
1512 = sep [ ptext (sLit "Module") <+> quotes (ppr mod)
1513 <+> ptext (sLit "is deprecated:"),
1514 nest 2 (vcat (map ppr txt)) ]
1516 implicitPreludeWarn :: SDoc
1518 = ptext (sLit "Module `Prelude' implicitly imported")
1520 packageImportErr :: SDoc
1522 = ptext (sLit "Package-qualified imports are not enabled; use -XPackageImports")