2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnNames]{Extracting imported and top-level names in scope}
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
15 rnImports, importsFromLocalDecls,
17 getLocalDeclBinders, extendRdrEnvRn,
18 reportUnusedNames, finishDeprecations
21 #include "HsVersions.h"
24 import HsSyn ( IE(..), ieName, ImportDecl(..), LImportDecl,
25 ForeignDecl(..), HsGroup(..), HsValBinds(..),
26 Sig(..), collectHsBindLocatedBinders, tyClDeclNames,
27 instDeclATs, isFamInstDecl,
30 import RnHsDoc ( rnHsDoc )
31 import IfaceEnv ( ifaceExportNames )
32 import LoadIface ( loadSrcInterface, loadSysInterface )
33 import TcRnMonad hiding (LIE)
48 import BasicTypes ( DeprecTxt )
49 import DriverPhases ( isHsBoot )
52 import Data.List ( partition, concatMap, (\\), delete )
53 import IO ( openFile, IOMode(..) )
59 %************************************************************************
63 %************************************************************************
66 rnImports :: [LImportDecl RdrName]
67 -> RnM ([LImportDecl Name], GlobalRdrEnv, ImportAvails,AnyHpcUsage)
70 -- PROCESS IMPORT DECLS
71 -- Do the non {- SOURCE -} ones first, so that we get a helpful
72 -- warning for {- SOURCE -} ones that are unnecessary
73 = do this_mod <- getModule
74 implicit_prelude <- doptM Opt_ImplicitPrelude
75 let prel_imports = mkPrelImports this_mod implicit_prelude imports
76 (source, ordinary) = partition is_source_import imports
77 is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot
79 ifOptM Opt_WarnImplicitPrelude (
80 when (notNull prel_imports) $ addWarn (implicitPreludeWarn)
83 stuff1 <- mapM (rnImportDecl this_mod) (prel_imports ++ ordinary)
84 stuff2 <- mapM (rnImportDecl this_mod) source
85 let (decls, rdr_env, imp_avails,hpc_usage) = combine (stuff1 ++ stuff2)
86 return (decls, rdr_env, imp_avails,hpc_usage)
89 combine :: [(LImportDecl Name, GlobalRdrEnv, ImportAvails,AnyHpcUsage)]
90 -> ([LImportDecl Name], GlobalRdrEnv, ImportAvails,AnyHpcUsage)
91 combine = foldr plus ([], emptyGlobalRdrEnv, emptyImportAvails,False)
92 where plus (decl, gbl_env1, imp_avails1,hpc_usage1)
93 (decls, gbl_env2, imp_avails2,hpc_usage2)
95 gbl_env1 `plusGlobalRdrEnv` gbl_env2,
96 imp_avails1 `plusImportAvails` imp_avails2,
97 hpc_usage1 || hpc_usage2)
99 mkPrelImports :: Module -> Bool -> [LImportDecl RdrName] -> [LImportDecl RdrName]
100 -- Consruct the implicit declaration "import Prelude" (or not)
102 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
103 -- because the former doesn't even look at Prelude.hi for instance
104 -- declarations, whereas the latter does.
105 mkPrelImports this_mod implicit_prelude import_decls
106 | this_mod == pRELUDE
107 || explicit_prelude_import
108 || not implicit_prelude
110 | otherwise = [preludeImportDecl]
112 explicit_prelude_import
113 = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- import_decls,
114 unLoc mod == pRELUDE_NAME ]
116 preludeImportDecl :: LImportDecl RdrName
119 ImportDecl (L loc pRELUDE_NAME)
120 False {- Not a boot interface -}
121 False {- Not qualified -}
122 Nothing {- No "as" -}
123 Nothing {- No import list -}
125 loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")
128 rnImportDecl :: Module
129 -> LImportDecl RdrName
130 -> RnM (LImportDecl Name, GlobalRdrEnv, ImportAvails,AnyHpcUsage)
132 rnImportDecl this_mod (L loc (ImportDecl loc_imp_mod_name want_boot
133 qual_only as_mod imp_details))
137 -- If there's an error in loadInterface, (e.g. interface
138 -- file not found) we get lots of spurious errors from 'filterImports'
140 imp_mod_name = unLoc loc_imp_mod_name
141 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
143 iface <- loadSrcInterface doc imp_mod_name want_boot
145 -- Compiler sanity check: if the import didn't say
146 -- {-# SOURCE #-} we should not get a hi-boot file
147 WARN( not want_boot && mi_boot iface, ppr imp_mod_name ) (do
149 -- Issue a user warning for a redundant {- SOURCE -} import
150 -- NB that we arrange to read all the ordinary imports before
151 -- any of the {- SOURCE -} imports
152 warnIf (want_boot && not (mi_boot iface))
153 (warnRedundantSourceImport imp_mod_name)
156 imp_mod = mi_module iface
157 deprecs = mi_deprecs iface
158 orph_iface = mi_orphan iface
159 has_finsts = mi_finsts iface
162 filtered_exports = filter not_this_mod (mi_exports iface)
163 not_this_mod (mod,_) = mod /= this_mod
164 -- If the module exports anything defined in this module, just
165 -- ignore it. Reason: otherwise it looks as if there are two
166 -- local definition sites for the thing, and an error gets
167 -- reported. Easiest thing is just to filter them out up
168 -- front. This situation only arises if a module imports
169 -- itself, or another module that imported it. (Necessarily,
170 -- this invoves a loop.)
172 -- Tiresome consequence: if you say
177 -- module B( AType ) where
178 -- import {-# SOURCE #-} A( AType )
180 -- then you'll get a 'B does not export AType' message. Oh well.
182 qual_mod_name = case as_mod of
183 Nothing -> imp_mod_name
184 Just another_name -> another_name
185 imp_spec = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,
186 is_dloc = loc, is_as = qual_mod_name }
189 -- Get the total exports from this module
190 total_avails <- ifaceExportNames filtered_exports
192 -- filter the imports according to the import declaration
193 (new_imp_details, gbl_env) <-
194 filterImports iface imp_spec imp_details total_avails
199 -- Compute new transitive dependencies
201 orphans | orph_iface = ASSERT( not (imp_mod `elem` dep_orphs deps) )
202 imp_mod : dep_orphs deps
203 | otherwise = dep_orphs deps
205 finsts | has_finsts = ASSERT( not (imp_mod `elem` dep_finsts deps) )
206 imp_mod : dep_finsts deps
207 | otherwise = dep_finsts deps
209 pkg = modulePackageId (mi_module iface)
211 (dependent_mods, dependent_pkgs)
212 | pkg == thisPackage dflags =
213 -- Imported module is from the home package
214 -- Take its dependent modules and add imp_mod itself
215 -- Take its dependent packages unchanged
217 -- NB: (dep_mods deps) might include a hi-boot file
218 -- for the module being compiled, CM. Do *not* filter
219 -- this out (as we used to), because when we've
220 -- finished dealing with the direct imports we want to
221 -- know if any of them depended on CM.hi-boot, in
222 -- which case we should do the hi-boot consistency
223 -- check. See LoadIface.loadHiBootInterface
224 ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)
227 -- Imported module is from another package
228 -- Dump the dependent modules
229 -- Add the package imp_mod comes from to the dependent packages
230 ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
231 ([], pkg : dep_pkgs deps)
233 -- True <=> import M ()
234 import_all = case imp_details of
235 Just (is_hiding, ls) -> not is_hiding && null ls
238 imports = ImportAvails {
239 imp_mods = unitModuleEnv imp_mod (imp_mod, [(qual_mod_name, import_all, loc)]),
242 imp_dep_mods = mkModDeps dependent_mods,
243 imp_dep_pkgs = dependent_pkgs
246 -- Complain if we import a deprecated module
247 ifOptM Opt_WarnDeprecations (
249 DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
253 let new_imp_decl = L loc (ImportDecl loc_imp_mod_name want_boot
254 qual_only as_mod new_imp_details)
256 returnM (new_imp_decl, gbl_env, imports, mi_hpc iface)
259 warnRedundantSourceImport mod_name
260 = ptext SLIT("Unnecessary {-# SOURCE #-} in the import of module")
261 <+> quotes (ppr mod_name)
265 %************************************************************************
267 importsFromLocalDecls
269 %************************************************************************
271 From the top-level declarations of this module produce
272 * the lexical environment
274 created by its bindings.
276 Complain about duplicate bindings
279 importsFromLocalDecls :: HsGroup RdrName -> RnM TcGblEnv
280 importsFromLocalDecls group
281 = do { gbl_env <- getGblEnv
283 ; avails <- getLocalDeclBinders gbl_env group
285 ; rdr_env' <- extendRdrEnvRn (tcg_rdr_env gbl_env) avails
287 ; traceRn (text "local avails: " <> ppr avails)
289 ; returnM (gbl_env { tcg_rdr_env = rdr_env' })
292 extendRdrEnvRn :: GlobalRdrEnv -> [AvailInfo] -> RnM GlobalRdrEnv
293 -- Add the new locally-bound names one by one, checking for duplicates as
294 -- we do so. Remember that in Template Haskell the duplicates
295 -- might *already be* in the GlobalRdrEnv from higher up the module
296 extendRdrEnvRn rdr_env avails
297 = foldlM add_local rdr_env (gresFromAvails LocalDef avails)
299 add_local rdr_env gre
300 | gres <- lookupGlobalRdrEnv rdr_env (nameOccName (gre_name gre))
301 , (dup_gre:_) <- filter isLocalGRE gres -- Check for existing *local* defns
302 = do { addDupDeclErr (gre_name dup_gre) (gre_name gre)
305 = return (extendGlobalRdrEnv rdr_env gre)
308 @getLocalDeclBinders@ returns the names for an @HsDecl@. It's
309 used for source code.
311 *** See "THE NAMING STORY" in HsDecls ****
313 Instances of type families
314 ~~~~~~~~~~~~~~~~~~~~~~~~~~
315 Indexed data/newtype instances contain data constructors that we need to
316 collect, too. Moreover, we need to descend into the data/newtypes instances
317 of associated families.
319 We need to be careful with the handling of the type constructor of each type
320 instance as the family constructor is already defined, and we want to avoid
321 raising a duplicate declaration error. So, we make a new name for it, but
322 don't return it in the 'AvailInfo'.
325 getLocalDeclBinders :: TcGblEnv -> HsGroup RdrName -> RnM [AvailInfo]
326 getLocalDeclBinders gbl_env (HsGroup {hs_valds = ValBindsIn val_decls val_sigs,
327 hs_tyclds = tycl_decls,
328 hs_instds = inst_decls,
329 hs_fords = foreign_decls })
330 = do { tc_names_s <- mappM new_tc tycl_decls
331 ; at_names_s <- mappM inst_ats inst_decls
332 ; val_names <- mappM new_simple val_bndrs
333 ; return (val_names ++ tc_names_s ++ concat at_names_s) }
335 mod = tcg_mod gbl_env
336 is_hs_boot = isHsBoot (tcg_src gbl_env) ;
337 val_bndrs | is_hs_boot = sig_hs_bndrs
338 | otherwise = for_hs_bndrs ++ val_hs_bndrs
339 -- In a hs-boot file, the value binders come from the
340 -- *signatures*, and there should be no foreign binders
342 new_simple rdr_name = do
343 nm <- newTopSrcBinder mod rdr_name
346 sig_hs_bndrs = [nm | L _ (TypeSig nm _) <- val_sigs]
347 val_hs_bndrs = collectHsBindLocatedBinders val_decls
348 for_hs_bndrs = [nm | L _ (ForeignImport nm _ _) <- foreign_decls]
351 | isFamInstDecl (unLoc tc_decl)
352 = do { main_name <- lookupFamInstDeclBndr mod main_rdr
353 ; sub_names <- mappM (newTopSrcBinder mod) sub_rdrs
354 ; return (AvailTC main_name sub_names) }
355 -- main_name is not bound here!
357 = do { main_name <- newTopSrcBinder mod main_rdr
358 ; sub_names <- mappM (newTopSrcBinder mod) sub_rdrs
359 ; return (AvailTC main_name (main_name : sub_names)) }
361 (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
364 = mappM new_tc (instDeclATs (unLoc inst_decl))
366 getLocalDeclBinders _ _ = panic "getLocalDeclBinders" -- ValBindsOut can't happen
370 %************************************************************************
372 \subsection{Filtering imports}
374 %************************************************************************
376 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
377 available, and filters it through the import spec (if any).
380 filterImports :: ModIface
381 -> ImpDeclSpec -- The span for the entire import decl
382 -> Maybe (Bool, [LIE RdrName]) -- Import spec; True => hiding
383 -> [AvailInfo] -- What's available
384 -> RnM (Maybe (Bool, [LIE Name]), -- Import spec w/ Names
385 GlobalRdrEnv) -- Same again, but in GRE form
387 filterImports iface decl_spec Nothing all_avails
388 = return (Nothing, mkGlobalRdrEnv (gresFromAvails prov all_avails))
390 prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
393 filterImports iface decl_spec (Just (want_hiding, import_items)) all_avails
394 = do -- check for errors, convert RdrNames to Names
395 opt_typeFamilies <- doptM Opt_TypeFamilies
396 items1 <- mapM (lookup_lie opt_typeFamilies) import_items
398 let items2 :: [(LIE Name, AvailInfo)]
399 items2 = concat items1
400 -- NB the AvailInfo may have duplicates, and several items
401 -- for the same parent; e.g N(x) and N(y)
403 names = availsToNameSet (map snd items2)
404 keep n = not (n `elemNameSet` names)
405 pruned_avails = filterAvails keep all_avails
406 hiding_prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
408 gres | want_hiding = gresFromAvails hiding_prov pruned_avails
409 | otherwise = concatMap (gresFromIE decl_spec) items2
411 return (Just (want_hiding, map fst items2), mkGlobalRdrEnv gres)
413 -- This environment is how we map names mentioned in the import
414 -- list to the actual Name they correspond to, and the name family
415 -- that the Name belongs to (the AvailInfo). The situation is
416 -- complicated by associated families, which introduce a three-level
417 -- hierachy, where class = grand parent, assoc family = parent, and
418 -- data constructors = children. The occ_env entries for associated
419 -- families needs to capture all this information; hence, we have the
420 -- third component of the environment that gives the class name (=
421 -- grand parent) in case of associated families.
423 -- This env will have entries for data constructors too,
424 -- they won't make any difference because naked entities like T
425 -- in an import list map to TcOccs, not VarOccs.
426 occ_env :: OccEnv (Name, -- the name
427 AvailInfo, -- the export item providing the name
428 Maybe Name) -- the parent of associated types
429 occ_env = mkOccEnv_C combine [ (nameOccName n, (n, a, Nothing))
430 | a <- all_avails, n <- availNames a]
432 -- we know that (1) there are at most entries for one name, (2) their
433 -- first component is identical, (3) they are for tys/cls, and (4) one
434 -- entry has the name in its parent position (the other doesn't)
435 combine (name, AvailTC p1 subs1, Nothing)
436 (_ , AvailTC p2 subs2, Nothing)
438 (parent, subs) = if p1 == name then (p2, subs1) else (p1, subs2)
440 (name, AvailTC name subs, Just parent)
442 lookup_lie :: Bool -> LIE RdrName -> TcRn [(LIE Name, AvailInfo)]
443 lookup_lie opt_typeFamilies (L loc ieRdr)
445 stuff <- setSrcSpan loc $
446 case lookup_ie opt_typeFamilies ieRdr of
447 Failed err -> addErr err >> return []
448 Succeeded a -> return a
449 checkDodgyImport stuff
450 return [ (L loc ie, avail) | (ie,avail) <- stuff ]
452 -- Warn when importing T(..) if T was exported abstractly
453 checkDodgyImport stuff
454 | IEThingAll n <- ieRdr, (_, AvailTC _ [one]):_ <- stuff
455 = ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn n))
456 -- NB. use the RdrName for reporting the warning
460 -- For each import item, we convert its RdrNames to Names,
461 -- and at the same time construct an AvailInfo corresponding
462 -- to what is actually imported by this item.
463 -- Returns Nothing on error.
464 -- We return a list here, because in the case of an import
465 -- item like C, if we are hiding, then C refers to *both* a
466 -- type/class and a data constructor. Moreover, when we import
467 -- data constructors of an associated family, we need separate
468 -- AvailInfos for the data constructors and the family (as they have
469 -- different parents). See the discussion at occ_env.
470 lookup_ie :: Bool -> IE RdrName -> MaybeErr Message [(IE Name,AvailInfo)]
471 lookup_ie opt_typeFamilies ie
472 = let bad_ie = Failed (badImportItemErr iface decl_spec ie)
474 lookup_name rdrName =
475 case lookupOccEnv occ_env (rdrNameOcc rdrName) of
481 (name, avail, _) <- lookup_name n
482 return [(IEVar name, trimAvail avail name)]
485 (name, avail@(AvailTC name2 subs), mb_parent) <- lookup_name tc
487 -- non-associated ty/cls
488 Nothing -> return [(IEThingAll name, avail)]
490 Just parent -> return [(IEThingAll name,
491 AvailTC name2 (subs \\ [name])),
492 (IEThingAll name, AvailTC parent [name])]
495 | want_hiding -- hiding ( C )
496 -- Here the 'C' can be a data constructor
497 -- *or* a type/class, or even both
498 -> let tc_name = lookup_name tc
499 dc_name = lookup_name (setRdrNameSpace tc srcDataName)
501 case catMaybeErr [ tc_name, dc_name ] of
503 names -> return [mkIEThingAbs name | name <- names]
505 -> do nameAvail <- lookup_name tc
506 return [mkIEThingAbs nameAvail]
508 IEThingWith tc ns -> do
509 (name, AvailTC name2 subnames, mb_parent) <- lookup_name tc
511 env = mkOccEnv [(nameOccName s, s) | s <- subnames]
512 mb_children = map (lookupOccEnv env . rdrNameOcc) ns
513 children <- if any isNothing mb_children
515 else return (catMaybes mb_children)
516 -- check for proper import of type families
517 when (not opt_typeFamilies && any isTyConName children) $
518 Failed (typeItemErr (head . filter isTyConName $ children)
519 (text "in import list"))
521 -- non-associated ty/cls
522 Nothing -> return [(IEThingWith name children,
523 AvailTC name (name:children))]
525 Just parent -> return [(IEThingWith name children,
526 AvailTC name children),
527 (IEThingWith name children,
528 AvailTC parent [name])]
530 _other -> Failed illegalImportItemErr
531 -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed
535 mkIEThingAbs (n, av, Nothing ) = (IEThingAbs n, trimAvail av n)
536 mkIEThingAbs (n, av, Just parent) = (IEThingAbs n, AvailTC parent [n])
539 catMaybeErr :: [MaybeErr err a] -> [a]
540 catMaybeErr ms = [ a | Succeeded a <- ms ]
543 %************************************************************************
547 %************************************************************************
550 -- | make a 'GlobalRdrEnv' where all the elements point to the same
551 -- import declaration (useful for "hiding" imports, or imports with
553 gresFromAvails :: Provenance -> [AvailInfo] -> [GlobalRdrElt]
554 gresFromAvails prov avails
555 = concatMap (gresFromAvail (const prov)) avails
557 gresFromAvail :: (Name -> Provenance) -> AvailInfo -> [GlobalRdrElt]
558 gresFromAvail prov_fn avail
559 = [ GRE {gre_name = n,
560 gre_par = availParent n avail,
561 gre_prov = prov_fn n}
562 | n <- availNames avail ]
564 greAvail :: GlobalRdrElt -> AvailInfo
565 greAvail gre = mkUnitAvail (gre_name gre) (gre_par gre)
567 mkUnitAvail :: Name -> Parent -> AvailInfo
568 mkUnitAvail me (ParentIs p) = AvailTC p [me]
569 mkUnitAvail me NoParent | isTyConName me = AvailTC me [me]
570 | otherwise = Avail me
572 plusAvail (Avail n1) (Avail n2) = Avail n1
573 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
574 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
576 availParent :: Name -> AvailInfo -> Parent
577 availParent n (Avail _) = NoParent
578 availParent n (AvailTC m ms) | n==m = NoParent
579 | otherwise = ParentIs m
581 trimAvail :: AvailInfo -> Name -> AvailInfo
582 trimAvail (Avail n) m = Avail n
583 trimAvail (AvailTC n ns) m = ASSERT( m `elem` ns) AvailTC n [m]
585 -- | filters 'AvailInfo's by the given predicate
586 filterAvails :: (Name -> Bool) -> [AvailInfo] -> [AvailInfo]
587 filterAvails keep avails = foldr (filterAvail keep) [] avails
589 -- | filters an 'AvailInfo' by the given predicate
590 filterAvail :: (Name -> Bool) -> AvailInfo -> [AvailInfo] -> [AvailInfo]
591 filterAvail keep ie rest =
593 Avail n | keep n -> ie : rest
596 let left = filter keep ns in
597 if null left then rest else AvailTC tc left : rest
599 -- | Given an import/export spec, construct the appropriate 'GlobalRdrElt's.
600 gresFromIE :: ImpDeclSpec -> (LIE Name, AvailInfo) -> [GlobalRdrElt]
601 gresFromIE decl_spec (L loc ie, avail)
602 = gresFromAvail prov_fn avail
604 is_explicit = case ie of
605 IEThingAll name -> \n -> n==name
607 prov_fn name = Imported [imp_spec]
609 imp_spec = ImpSpec { is_decl = decl_spec, is_item = item_spec }
610 item_spec = ImpSome { is_explicit = is_explicit name, is_iloc = loc }
612 mkChildEnv :: [GlobalRdrElt] -> NameEnv [Name]
613 mkChildEnv gres = foldr add emptyNameEnv gres
615 add (GRE { gre_name = n, gre_par = ParentIs p }) env = extendNameEnv_C (++) env p [n]
616 add other_gre env = env
618 findChildren :: NameEnv [Name] -> Name -> [Name]
619 findChildren env n = lookupNameEnv env n `orElse` []
622 ---------------------------------------
625 All this AvailEnv stuff is hardly used; only in a very small
626 part of RnNames. Todo: remove?
627 ---------------------------------------
630 type AvailEnv = NameEnv AvailInfo -- Maps a Name to the AvailInfo that contains it
632 emptyAvailEnv :: AvailEnv
633 emptyAvailEnv = emptyNameEnv
635 unitAvailEnv :: AvailInfo -> AvailEnv
636 unitAvailEnv a = unitNameEnv (availName a) a
638 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
639 plusAvailEnv = plusNameEnv_C plusAvail
641 availEnvElts :: AvailEnv -> [AvailInfo]
642 availEnvElts = nameEnvElts
644 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
645 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
647 mkAvailEnv :: [AvailInfo] -> AvailEnv
648 -- 'avails' may have several items with the same availName
649 -- E.g import Ix( Ix(..), index )
650 -- will give Ix(Ix,index,range) and Ix(index)
651 -- We want to combine these; addAvail does that
652 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
654 -- After combining the avails, we need to ensure that the parent name is the
655 -- first entry in the list of subnames, if it is included at all. (Subsequent
656 -- functions rely on that.)
657 normaliseAvail :: AvailInfo -> AvailInfo
658 normaliseAvail avail@(Avail _) = avail
659 normaliseAvail (AvailTC name subs) = AvailTC name subs'
661 subs' = if name `elem` subs then name : (delete name subs) else subs
663 -- | combines 'AvailInfo's from the same family
664 nubAvails :: [AvailInfo] -> [AvailInfo]
665 nubAvails avails = map normaliseAvail . nameEnvElts . mkAvailEnv $ avails
669 %************************************************************************
671 \subsection{Export list processing}
673 %************************************************************************
675 Processing the export list.
677 You might think that we should record things that appear in the export
678 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
679 wrong. We do check (here) that they are in scope, but there is no
680 need to slurp in their actual declaration (which is what
681 @addOccurrenceName@ forces).
683 Indeed, doing so would big trouble when compiling @PrelBase@, because
684 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
685 @ConcBase.StateAndSynchVar#@, and so on...
688 type ExportAccum -- The type of the accumulating parameter of
689 -- the main worker function in rnExports
690 = ([LIE Name], -- Export items with Names
691 ExportOccMap, -- Tracks exported occurrence names
692 [AvailInfo]) -- The accumulated exported stuff
695 emptyExportAccum = ([], emptyOccEnv, [])
697 type ExportOccMap = OccEnv (Name, IE RdrName)
698 -- Tracks what a particular exported OccName
699 -- in an export list refers to, and which item
700 -- it came from. It's illegal to export two distinct things
701 -- that have the same occurrence name
703 rnExports :: Bool -- False => no 'module M(..) where' header at all
704 -> Maybe [LIE RdrName] -- Nothing => no explicit export list
708 -- Complains if two distinct exports have same OccName
709 -- Warns about identical exports.
710 -- Complains about exports items not in scope
712 rnExports explicit_mod exports
713 tcg_env@(TcGblEnv { tcg_mod = this_mod,
714 tcg_rdr_env = rdr_env,
715 tcg_imports = imports })
717 -- If the module header is omitted altogether, then behave
718 -- as if the user had written "module Main(main) where..."
719 -- EXCEPT in interactive mode, when we behave as if he had
720 -- written "module Main where ..."
721 -- Reason: don't want to complain about 'main' not in scope
722 -- in interactive mode
725 | explicit_mod = exports
726 | ghcLink dflags == LinkInMemory = Nothing
727 | otherwise = Just ([noLoc (IEVar main_RDR_Unqual)])
728 -- ToDo: the 'noLoc' here is unhelpful if 'main'
729 -- turns out to be out of scope
731 ; (rn_exports, avails) <- exports_from_avail real_exports rdr_env imports this_mod
732 ; let final_avails = nubAvails avails -- Combine families
734 ; return (tcg_env { tcg_exports = final_avails,
735 tcg_rn_exports = case tcg_rn_exports tcg_env of
737 Just _ -> rn_exports,
738 tcg_dus = tcg_dus tcg_env `plusDU`
739 usesOnly (availsToNameSet final_avails) }) }
742 exports_from_avail :: Maybe [LIE RdrName]
743 -- Nothing => no explicit export list
747 -> RnM (Maybe [LIE Name], [AvailInfo])
749 exports_from_avail Nothing rdr_env imports this_mod
750 = -- The same as (module M) where M is the current module name,
751 -- so that's how we handle it.
753 avails = [ greAvail gre | gre <- globalRdrEnvElts rdr_env,
756 return (Nothing, avails)
758 exports_from_avail (Just rdr_items) rdr_env imports this_mod
759 = do (ie_names, _, exports) <- foldlM do_litem emptyExportAccum rdr_items
761 return (Just ie_names, exports)
763 do_litem :: ExportAccum -> LIE RdrName -> RnM ExportAccum
764 do_litem acc lie = setSrcSpan (getLoc lie) (exports_from_item acc lie)
766 kids_env :: NameEnv [Name] -- Maps a parent to its in-scope children
767 kids_env = mkChildEnv (globalRdrEnvElts rdr_env)
769 imported_modules = [ qual_name
770 | (_, xs) <- moduleEnvElts $ imp_mods imports,
771 (qual_name, _, _) <- xs ]
773 exports_from_item :: ExportAccum -> LIE RdrName -> RnM ExportAccum
774 exports_from_item acc@(ie_names, occs, exports)
775 (L loc ie@(IEModuleContents mod))
776 | let earlier_mods = [ mod | (L _ (IEModuleContents mod)) <- ie_names ]
777 , mod `elem` earlier_mods -- Duplicate export of M
778 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
779 warnIf warn_dup_exports (dupModuleExport mod) ;
783 = do { implicit_prelude <- doptM Opt_ImplicitPrelude
784 ; let { exportValid = (mod `elem` imported_modules)
785 || (moduleName this_mod == mod)
786 ; gres = filter (isModuleExported implicit_prelude mod)
787 (globalRdrEnvElts rdr_env)
790 ; checkErr exportValid (moduleNotImported mod)
791 ; warnIf (exportValid && null gres) (nullModuleExport mod)
793 ; occs' <- check_occs ie occs (map gre_name gres)
794 -- This check_occs not only finds conflicts
795 -- between this item and others, but also
796 -- internally within this item. That is, if
797 -- 'M.x' is in scope in several ways, we'll have
798 -- several members of mod_avails with the same
800 ; return (L loc (IEModuleContents mod) : ie_names,
801 occs', map greAvail gres ++ exports) }
803 exports_from_item acc@(lie_names, occs, exports) (L loc ie)
805 = do new_ie <- lookup_doc_ie ie
806 return (L loc new_ie : lie_names, occs, exports)
809 = do (new_ie, avail) <- lookup_ie ie
810 if isUnboundName (ieName new_ie)
811 then return acc -- Avoid error cascade
814 occs' <- check_occs ie occs (availNames avail)
816 return (L loc new_ie : lie_names, occs', avail : exports)
819 lookup_ie :: IE RdrName -> RnM (IE Name, AvailInfo)
820 lookup_ie (IEVar rdr)
821 = do gre <- lookupGreRn rdr
822 return (IEVar (gre_name gre), greAvail gre)
824 lookup_ie (IEThingAbs rdr)
825 = do gre <- lookupGreRn rdr
826 let name = gre_name gre
828 NoParent -> return (IEThingAbs name,
830 ParentIs p -> return (IEThingAbs name,
833 lookup_ie ie@(IEThingAll rdr)
834 = do name <- lookupGlobalOccRn rdr
835 let kids = findChildren kids_env name
837 (if (isTyConName name) then addWarn (dodgyExportWarn name)
838 -- This occurs when you export T(..), but
839 -- only import T abstractly, or T is a synonym.
840 else addErr (exportItemErr ie))
842 return (IEThingAll name, AvailTC name (name:kids))
844 lookup_ie ie@(IEThingWith rdr sub_rdrs)
845 = do name <- lookupGlobalOccRn rdr
846 if isUnboundName name
847 then return (IEThingWith name [], AvailTC name [name])
849 let env = mkOccEnv [ (nameOccName s, s)
850 | s <- findChildren kids_env name ]
851 mb_names = map (lookupOccEnv env . rdrNameOcc) sub_rdrs
852 if any isNothing mb_names
853 then do addErr (exportItemErr ie)
854 return (IEThingWith name [], AvailTC name [name])
855 else do let names = catMaybes mb_names
856 optTyFam <- doptM Opt_TypeFamilies
857 when (not optTyFam && any isTyConName names) $
858 addErr (typeItemErr ( head
861 (text "in export list"))
862 return (IEThingWith name names, AvailTC name (name:names))
864 lookup_ie ie = panic "lookup_ie" -- Other cases covered earlier
867 lookup_doc_ie :: IE RdrName -> RnM (IE Name)
868 lookup_doc_ie (IEGroup lev doc) = do rn_doc <- rnHsDoc doc
869 return (IEGroup lev rn_doc)
870 lookup_doc_ie (IEDoc doc) = do rn_doc <- rnHsDoc doc
871 return (IEDoc rn_doc)
872 lookup_doc_ie (IEDocNamed str) = return (IEDocNamed str)
873 lookup_doc_ie ie = panic "lookup_doc_ie" -- Other cases covered earlier
876 isDoc (IEDoc _) = True
877 isDoc (IEDocNamed _) = True
878 isDoc (IEGroup _ _) = True
881 -------------------------------
882 isModuleExported :: Bool -> ModuleName -> GlobalRdrElt -> Bool
883 -- True if the thing is in scope *both* unqualified, *and* with qualifier M
884 isModuleExported implicit_prelude mod (GRE { gre_name = name, gre_prov = prov })
885 | implicit_prelude && isBuiltInSyntax name = False
886 -- Optimisation: filter out names for built-in syntax
887 -- They just clutter up the environment (esp tuples), and the parser
888 -- will generate Exact RdrNames for them, so the cluttered
889 -- envt is no use. To avoid doing this filter all the time,
890 -- we use -fno-implicit-prelude as a clue that the filter is
891 -- worth while. Really, it's only useful for GHC.Base and GHC.Tuple.
893 -- It's worth doing because it makes the environment smaller for
894 -- every module that imports the Prelude
897 LocalDef -> moduleName (nameModule name) == mod
898 Imported is -> any unQualSpecOK is && any (qualSpecOK mod) is
900 -------------------------------
901 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
902 check_occs ie occs names
903 = foldlM check occs names
906 = case lookupOccEnv occs name_occ of
907 Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
910 | name == name' -- Duplicate export
911 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
912 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
915 | otherwise -- Same occ name but different names: an error
916 -> do { global_env <- getGlobalRdrEnv ;
917 addErr (exportClashErr global_env name' name ie' ie) ;
920 name_occ = nameOccName name
923 %*********************************************************
927 %*********************************************************
930 finishDeprecations :: DynFlags -> Maybe DeprecTxt
931 -> TcGblEnv -> RnM TcGblEnv
932 -- (a) Report usasge of deprecated imports
933 -- (b) If the whole module is deprecated, update tcg_deprecs
934 -- All this happens only once per module
935 finishDeprecations dflags mod_deprec tcg_env
936 = do { (eps,hpt) <- getEpsAndHpt
937 ; ifOptM Opt_WarnDeprecations $
938 mapM_ (check hpt (eps_PIT eps)) all_gres
939 -- By this time, typechecking is complete,
940 -- so the PIT is fully populated
942 -- Deal with a module deprecation; it overrides all existing deprecs
943 ; let new_deprecs = case mod_deprec of
944 Just txt -> DeprecAll txt
945 Nothing -> tcg_deprecs tcg_env
946 ; return (tcg_env { tcg_deprecs = new_deprecs }) }
948 used_names = allUses (tcg_dus tcg_env)
949 -- Report on all deprecated uses; hence allUses
950 all_gres = globalRdrEnvElts (tcg_rdr_env tcg_env)
952 check hpt pit gre@(GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
953 | name `elemNameSet` used_names
954 , Just deprec_txt <- lookupImpDeprec dflags hpt pit gre
955 = addWarnAt (importSpecLoc imp_spec)
956 (sep [ptext SLIT("Deprecated use of") <+>
957 pprNonVarNameSpace (occNameSpace (nameOccName name)) <+>
959 (parens imp_msg) <> colon,
962 name_mod = nameModule name
963 imp_mod = importSpecModule imp_spec
964 imp_msg = ptext SLIT("imported from") <+> ppr imp_mod <> extra
965 extra | imp_mod == moduleName name_mod = empty
966 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
968 check hpt pit ok_gre = returnM () -- Local, or not used, or not deprectated
969 -- The Imported pattern-match: don't deprecate locally defined names
970 -- For a start, we may be exporting a deprecated thing
971 -- Also we may use a deprecated thing in the defn of another
972 -- deprecated things. We may even use a deprecated thing in
973 -- the defn of a non-deprecated thing, when changing a module's
976 lookupImpDeprec :: DynFlags -> HomePackageTable -> PackageIfaceTable
977 -> GlobalRdrElt -> Maybe DeprecTxt
978 -- The name is definitely imported, so look in HPT, PIT
979 lookupImpDeprec dflags hpt pit gre
980 = case lookupIfaceByModule dflags hpt pit (nameModule name) of
981 Just iface -> mi_dep_fn iface name `seqMaybe` -- Bleat if the thing, *or
983 ParentIs p -> mi_dep_fn iface p -- its parent*, is deprec'd
986 Nothing -> Nothing -- See Note [Used names with interface not loaded]
991 Note [Used names with interface not loaded]
992 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
993 By now all the interfaces should have been loaded,
994 because reportDeprecations happens after typechecking.
995 However, it's still (just) possible to to find a used
996 Name whose interface hasn't been loaded:
998 a) It might be a WiredInName; in that case we may not load
999 its interface (although we could).
1001 b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
1002 These are seen as "used" by the renamer (if -fno-implicit-prelude)
1003 is on), but the typechecker may discard their uses
1004 if in fact the in-scope fromRational is GHC.Read.fromRational,
1005 (see tcPat.tcOverloadedLit), and the typechecker sees that the type
1006 is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
1007 In that obscure case it won't force the interface in.
1009 In both cases we simply don't permit deprecations;
1010 this is, after all, wired-in stuff.
1013 %*********************************************************
1017 %*********************************************************
1020 reportUnusedNames :: Maybe [LIE RdrName] -- Export list
1021 -> TcGblEnv -> RnM ()
1022 reportUnusedNames export_decls gbl_env
1023 = do { traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env)))
1024 ; warnUnusedTopBinds unused_locals
1025 ; warnUnusedModules unused_imp_mods
1026 ; warnUnusedImports unused_imports
1027 ; warnDuplicateImports defined_and_used
1028 ; printMinimalImports minimal_imports }
1030 used_names :: NameSet
1031 used_names = findUses (tcg_dus gbl_env) emptyNameSet
1032 -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
1035 -- Collect the defined names from the in-scope environment
1036 defined_names :: [GlobalRdrElt]
1037 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
1039 -- Note that defined_and_used, defined_but_not_used
1040 -- are both [GRE]; that's why we need defined_and_used
1041 -- rather than just used_names
1042 defined_and_used, defined_but_not_used :: [GlobalRdrElt]
1043 (defined_and_used, defined_but_not_used)
1044 = partition (gre_is_used used_names) defined_names
1046 kids_env = mkChildEnv defined_names
1047 -- This is done in mkExports too; duplicated work
1049 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
1050 gre_is_used used_names (GRE {gre_name = name})
1051 = name `elemNameSet` used_names
1052 || any (`elemNameSet` used_names) (findChildren kids_env name)
1053 -- A use of C implies a use of T,
1054 -- if C was brought into scope by T(..) or T(C)
1056 -- Filter out the ones that are
1057 -- (a) defined in this module, and
1058 -- (b) not defined by a 'deriving' clause
1059 -- The latter have an Internal Name, so we can filter them out easily
1060 unused_locals :: [GlobalRdrElt]
1061 unused_locals = filter is_unused_local defined_but_not_used
1062 is_unused_local :: GlobalRdrElt -> Bool
1063 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
1065 unused_imports :: [GlobalRdrElt]
1066 unused_imports = mapCatMaybes unused_imp defined_but_not_used
1067 unused_imp :: GlobalRdrElt -> Maybe GlobalRdrElt -- Result has trimmed Imported provenances
1068 unused_imp gre@(GRE {gre_prov = LocalDef}) = Nothing
1069 unused_imp gre@(GRE {gre_prov = Imported imp_specs})
1070 | null trimmed_specs = Nothing
1071 | otherwise = Just (gre {gre_prov = Imported trimmed_specs})
1073 trimmed_specs = filter report_if_unused imp_specs
1075 -- To figure out the minimal set of imports, start with the things
1076 -- that are in scope (i.e. in gbl_env). Then just combine them
1077 -- into a bunch of avails, so they are properly grouped
1079 -- BUG WARNING: this does not deal properly with qualified imports!
1080 minimal_imports :: FiniteMap ModuleName AvailEnv
1081 minimal_imports0 = foldr add_expall emptyFM expall_mods
1082 minimal_imports1 = foldr add_name minimal_imports0 defined_and_used
1083 minimal_imports = foldr add_inst_mod minimal_imports1 direct_import_mods
1084 -- The last line makes sure that we retain all direct imports
1085 -- even if we import nothing explicitly.
1086 -- It's not necessarily redundant to import such modules. Consider
1090 -- The import M() is not *necessarily* redundant, even if
1091 -- we suck in no instance decls from M (e.g. it contains
1092 -- no instance decls, or This contains no code). It may be
1093 -- that we import M solely to ensure that M's orphan instance
1094 -- decls (or those in its imports) are visible to people who
1095 -- import This. Sigh.
1096 -- There's really no good way to detect this, so the error message
1097 -- in RnEnv.warnUnusedModules is weakened instead
1099 -- We've carefully preserved the provenance so that we can
1100 -- construct minimal imports that import the name by (one of)
1101 -- the same route(s) as the programmer originally did.
1102 add_name gre@(GRE {gre_prov = Imported (imp_spec:_)}) acc
1103 = addToFM_C plusAvailEnv acc
1104 (importSpecModule imp_spec) (unitAvailEnv (greAvail gre))
1105 add_name gre acc = acc -- Local
1107 -- Modules mentioned as 'module M' in the export list
1108 expall_mods = case export_decls of
1110 Just es -> [m | L _ (IEModuleContents m) <- es]
1112 -- This is really bogus. The idea is that if we see 'module M' in
1113 -- the export list we must retain the import decls that drive it
1114 -- If we aren't careful we might see
1115 -- module A( module M ) where
1118 -- and suppose that N exports everything that M does. Then we
1119 -- must not drop the import of M even though N brings it all into
1122 -- BUG WARNING: 'module M' exports aside, what if M.x is mentioned?!
1124 -- The reason that add_expall is bogus is that it doesn't take
1125 -- qualified imports into account. But it's an improvement.
1126 add_expall mod acc = addToFM_C plusAvailEnv acc mod emptyAvailEnv
1128 add_inst_mod (mod, _) acc
1129 | mod_name `elemFM` acc = acc -- We import something already
1130 | otherwise = addToFM acc mod_name emptyAvailEnv
1132 mod_name = moduleName mod
1133 -- Add an empty collection of imports for a module
1134 -- from which we have sucked only instance decls
1136 imports = tcg_imports gbl_env
1138 direct_import_mods :: [(Module, [(ModuleName, Bool, SrcSpan)])]
1139 -- See the type of the imp_mods for this triple
1140 direct_import_mods = moduleEnvElts (imp_mods imports)
1142 -- unused_imp_mods are the directly-imported modules
1143 -- that are not mentioned in minimal_imports1
1144 -- [Note: not 'minimal_imports', because that includes directly-imported
1145 -- modules even if we use nothing from them; see notes above]
1147 -- BUG WARNING: this code is generally buggy
1148 unused_imp_mods :: [(ModuleName, SrcSpan)]
1149 unused_imp_mods = [(mod_name,loc)
1150 | (mod, xs) <- direct_import_mods,
1151 (_, no_imp, loc) <- xs,
1152 let mod_name = moduleName mod,
1153 not (mod_name `elemFM` minimal_imports1),
1156 -- The not no_imp part is not to complain about
1157 -- import M (), which is an idiom for importing
1158 -- instance declarations
1160 module_unused :: ModuleName -> Bool
1161 module_unused mod = any (((==) mod) . fst) unused_imp_mods
1163 report_if_unused :: ImportSpec -> Bool
1164 -- Do we want to report this as an unused import?
1165 report_if_unused (ImpSpec {is_decl = d, is_item = i})
1166 = not (module_unused (is_mod d)) -- Not if we've already said entire import is unused
1167 && isExplicitItem i -- Only if the import was explicit
1169 ---------------------
1170 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
1171 -- Given the GREs for names that are used, figure out which imports
1172 -- could be omitted without changing the top-level environment.
1174 -- NB: Given import Foo( T )
1175 -- import qualified Foo
1176 -- we do not report a duplicate import, even though Foo.T is brought
1177 -- into scope by both, because there's nothing you can *omit* without
1178 -- changing the top-level environment. So we complain only if it's
1179 -- explicitly named in both imports or neither.
1181 -- Furthermore, we complain about Foo.T only if
1182 -- there is no complaint about (unqualified) T
1184 warnDuplicateImports gres
1185 = ifOptM Opt_WarnUnusedImports $
1186 sequenceM_ [ warn name pr
1187 | GRE { gre_name = name, gre_prov = Imported imps } <- gres
1188 , pr <- redundants imps ]
1190 warn name (red_imp, cov_imp)
1191 = addWarnAt (importSpecLoc red_imp)
1192 (vcat [ptext SLIT("Redundant import of:") <+> quotes pp_name,
1193 ptext SLIT("It is also") <+> ppr cov_imp])
1195 pp_name | is_qual red_decl = ppr (is_as red_decl) <> dot <> ppr occ
1196 | otherwise = ppr occ
1197 occ = nameOccName name
1198 red_decl = is_decl red_imp
1200 redundants :: [ImportSpec] -> [(ImportSpec,ImportSpec)]
1201 -- The returned pair is (redundant-import, covering-import)
1203 = [ (red_imp, cov_imp)
1205 , isExplicitItem (is_item red_imp)
1206 -- Complain only about redundant imports
1207 -- mentioned explicitly by the user
1208 , cov_imp <- take 1 (filter (covers red_imp) imps) ]
1209 -- The 'take 1' picks the first offending group
1210 -- for this particular name
1212 -- "red_imp" is a putative redundant import
1213 -- "cov_imp" potentially covers it
1214 -- This test decides whether red_imp could be dropped
1216 -- NOTE: currently the test does not warn about
1219 -- even if the same underlying 'x' is involved, because dropping
1220 -- either import would change the qualified names in scope (M.x, N.x)
1221 -- But if the qualified names aren't used, the import is indeed redundant
1222 -- Sadly we don't know that. Oh well.
1223 covers red_imp@(ImpSpec { is_decl = red_decl, is_item = red_item })
1224 cov_imp@(ImpSpec { is_decl = cov_decl, is_item = cov_item })
1225 | red_loc == cov_loc
1226 = False -- Ignore diagonal elements
1227 | not (is_as red_decl == is_as cov_decl)
1228 = False -- They bring into scope different qualified names
1229 | not (is_qual red_decl) && is_qual cov_decl
1230 = False -- Covering one doesn't bring unqualified name into scope
1232 = not (isExplicitItem cov_item) -- Redundant one is selective and covering one isn't
1233 || red_later -- or both are explicit; tie-break using red_later
1236 = not cov_selective -- Redundant one is selective and covering one isn't
1237 || red_later -- Both are explicit; tie-break using red_later
1239 = not cov_selective -- Neither import is selective
1240 && (is_mod red_decl == is_mod cov_decl) -- They import the same module
1241 && red_later -- Tie-break
1244 red_loc = importSpecLoc red_imp
1245 cov_loc = importSpecLoc cov_imp
1246 red_later = red_loc > cov_loc
1248 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
1249 printMinimalImports :: FiniteMap ModuleName AvailEnv -- Minimal imports
1251 printMinimalImports imps
1252 = ifOptM Opt_D_dump_minimal_imports $ do {
1254 mod_ies <- initIfaceTcRn $ mappM to_ies (fmToList imps) ;
1255 this_mod <- getModule ;
1256 rdr_env <- getGlobalRdrEnv ;
1257 dflags <- getDOpts ;
1258 ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
1259 printForUser h (mkPrintUnqualified dflags rdr_env)
1260 (vcat (map ppr_mod_ie mod_ies)) })
1263 mkFilename this_mod = moduleNameString (moduleName this_mod) ++ ".imports"
1264 ppr_mod_ie (mod_name, ies)
1265 | mod_name == moduleName pRELUDE
1267 | null ies -- Nothing except instances comes from here
1268 = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("() -- Instances only")
1270 = ptext SLIT("import") <+> ppr mod_name <>
1271 parens (fsep (punctuate comma (map ppr ies)))
1273 to_ies (mod, avail_env) = do ies <- mapM to_ie (availEnvElts avail_env)
1276 to_ie :: AvailInfo -> IfG (IE Name)
1277 -- The main trick here is that if we're importing all the constructors
1278 -- we want to say "T(..)", but if we're importing only a subset we want
1279 -- to say "T(A,B,C)". So we have to find out what the module exports.
1280 to_ie (Avail n) = returnM (IEVar n)
1281 to_ie (AvailTC n [m]) = ASSERT( n==m )
1282 returnM (IEThingAbs n)
1283 to_ie (AvailTC n ns)
1284 = loadSysInterface doc n_mod `thenM` \ iface ->
1285 case [xs | (m,as) <- mi_exports iface,
1288 x == nameOccName n] of
1289 [xs] | all_used xs -> returnM (IEThingAll n)
1290 | otherwise -> returnM (IEThingWith n (filter (/= n) ns))
1291 other -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
1294 all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
1295 doc = text "Compute minimal imports from" <+> ppr n
1296 n_mod = nameModule n
1300 %************************************************************************
1304 %************************************************************************
1307 badImportItemErr iface decl_spec ie
1308 = sep [ptext SLIT("Module"), quotes (ppr (is_mod decl_spec)), source_import,
1309 ptext SLIT("does not export"), quotes (ppr ie)]
1311 source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
1314 illegalImportItemErr = ptext SLIT("Illegal import item")
1316 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
1317 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
1320 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
1321 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructors or class methods,"),
1322 ptext SLIT("but it has none") ]
1324 exportItemErr export_item
1325 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
1326 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
1328 typeItemErr name wherestr
1329 = sep [ ptext SLIT("Using 'type' tag on") <+> quotes (ppr name) <+> wherestr,
1330 ptext SLIT("Use -ftype-families to enable this extension") ]
1332 exportClashErr :: GlobalRdrEnv -> Name -> Name -> IE RdrName -> IE RdrName
1334 exportClashErr global_env name1 name2 ie1 ie2
1335 = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
1336 , ppr_export ie1' name1'
1337 , ppr_export ie2' name2' ]
1339 occ = nameOccName name1
1340 ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+>
1341 quotes (ppr name) <+> pprNameProvenance (get_gre name))
1343 -- get_gre finds a GRE for the Name, so that we can show its provenance
1345 = case lookupGRE_Name global_env name of
1347 [] -> pprPanic "exportClashErr" (ppr name)
1348 get_loc name = nameSrcLoc $ gre_name $ get_gre name
1349 (name1', ie1', name2', ie2') = if get_loc name1 < get_loc name2
1350 then (name1, ie1, name2, ie2)
1351 else (name2, ie2, name1, ie1)
1353 addDupDeclErr :: Name -> Name -> TcRn ()
1354 addDupDeclErr name_a name_b
1355 = addErrAt (srcLocSpan loc2) $
1356 vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
1357 ptext SLIT("Declared at:") <+> vcat [ppr (nameSrcLoc name1), ppr loc2]]
1359 loc2 = nameSrcLoc name2
1360 (name1,name2) | nameSrcLoc name_a > nameSrcLoc name_b = (name_b,name_a)
1361 | otherwise = (name_a,name_b)
1362 -- Report the error at the later location
1364 dupExportWarn occ_name ie1 ie2
1365 = hsep [quotes (ppr occ_name),
1366 ptext SLIT("is exported by"), quotes (ppr ie1),
1367 ptext SLIT("and"), quotes (ppr ie2)]
1370 = hsep [ptext SLIT("Duplicate"),
1371 quotes (ptext SLIT("Module") <+> ppr mod),
1372 ptext SLIT("in export list")]
1374 moduleNotImported :: ModuleName -> SDoc
1375 moduleNotImported mod
1376 = ptext SLIT("The export item `module") <+> ppr mod <>
1377 ptext SLIT("' is not imported")
1379 nullModuleExport mod
1380 = ptext SLIT("The export item `module") <+> ppr mod <> ptext SLIT("' exports nothing")
1382 moduleDeprec mod txt
1383 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),
1387 = ptext SLIT("Module `Prelude' implicitly imported")