2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnNames]{Extracting imported and top-level names in scope}
8 rnImports, importsFromLocalDecls,
10 getLocalDeclBinders, extendRdrEnvRn,
11 reportUnusedNames, finishDeprecations
14 #include "HsVersions.h"
17 import HsSyn ( IE(..), ieName, ImportDecl(..), LImportDecl,
18 ForeignDecl(..), HsGroup(..), HsValBinds(..),
19 Sig(..), collectHsBindLocatedBinders, tyClDeclNames,
20 instDeclATs, isFamInstDecl,
23 import RnHsDoc ( rnHsDoc )
24 import IfaceEnv ( ifaceExportNames )
25 import LoadIface ( loadSrcInterface, loadSysInterface )
26 import TcRnMonad hiding (LIE)
41 import BasicTypes ( DeprecTxt )
42 import DriverPhases ( isHsBoot )
45 import Data.List ( partition, concatMap, (\\), delete )
46 import IO ( openFile, IOMode(..) )
52 %************************************************************************
56 %************************************************************************
59 rnImports :: [LImportDecl RdrName]
60 -> RnM ([LImportDecl Name], GlobalRdrEnv, ImportAvails,AnyHpcUsage)
63 -- PROCESS IMPORT DECLS
64 -- Do the non {- SOURCE -} ones first, so that we get a helpful
65 -- warning for {- SOURCE -} ones that are unnecessary
66 = do this_mod <- getModule
67 implicit_prelude <- doptM Opt_ImplicitPrelude
68 let prel_imports = mkPrelImports this_mod implicit_prelude imports
69 (source, ordinary) = partition is_source_import imports
70 is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot
72 ifOptM Opt_WarnImplicitPrelude (
73 when (notNull prel_imports) $ addWarn (implicitPreludeWarn)
76 stuff1 <- mapM (rnImportDecl this_mod) (prel_imports ++ ordinary)
77 stuff2 <- mapM (rnImportDecl this_mod) source
78 let (decls, rdr_env, imp_avails,hpc_usage) = combine (stuff1 ++ stuff2)
79 return (decls, rdr_env, imp_avails,hpc_usage)
82 combine :: [(LImportDecl Name, GlobalRdrEnv, ImportAvails,AnyHpcUsage)]
83 -> ([LImportDecl Name], GlobalRdrEnv, ImportAvails,AnyHpcUsage)
84 combine = foldr plus ([], emptyGlobalRdrEnv, emptyImportAvails,False)
85 where plus (decl, gbl_env1, imp_avails1,hpc_usage1)
86 (decls, gbl_env2, imp_avails2,hpc_usage2)
88 gbl_env1 `plusGlobalRdrEnv` gbl_env2,
89 imp_avails1 `plusImportAvails` imp_avails2,
90 hpc_usage1 || hpc_usage2)
92 mkPrelImports :: Module -> Bool -> [LImportDecl RdrName] -> [LImportDecl RdrName]
93 -- Consruct the implicit declaration "import Prelude" (or not)
95 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
96 -- because the former doesn't even look at Prelude.hi for instance
97 -- declarations, whereas the latter does.
98 mkPrelImports this_mod implicit_prelude import_decls
100 || explicit_prelude_import
101 || not implicit_prelude
103 | otherwise = [preludeImportDecl]
105 explicit_prelude_import
106 = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- import_decls,
107 unLoc mod == pRELUDE_NAME ]
109 preludeImportDecl :: LImportDecl RdrName
112 ImportDecl (L loc pRELUDE_NAME)
113 False {- Not a boot interface -}
114 False {- Not qualified -}
115 Nothing {- No "as" -}
116 Nothing {- No import list -}
118 loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")
121 rnImportDecl :: Module
122 -> LImportDecl RdrName
123 -> RnM (LImportDecl Name, GlobalRdrEnv, ImportAvails,AnyHpcUsage)
125 rnImportDecl this_mod (L loc (ImportDecl loc_imp_mod_name want_boot
126 qual_only as_mod imp_details))
130 -- If there's an error in loadInterface, (e.g. interface
131 -- file not found) we get lots of spurious errors from 'filterImports'
133 imp_mod_name = unLoc loc_imp_mod_name
134 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
136 iface <- loadSrcInterface doc imp_mod_name want_boot
138 -- Compiler sanity check: if the import didn't say
139 -- {-# SOURCE #-} we should not get a hi-boot file
140 WARN( not want_boot && mi_boot iface, ppr imp_mod_name ) (do
142 -- Issue a user warning for a redundant {- SOURCE -} import
143 -- NB that we arrange to read all the ordinary imports before
144 -- any of the {- SOURCE -} imports
145 warnIf (want_boot && not (mi_boot iface))
146 (warnRedundantSourceImport imp_mod_name)
149 imp_mod = mi_module iface
150 deprecs = mi_deprecs iface
151 orph_iface = mi_orphan iface
152 has_finsts = mi_finsts iface
155 filtered_exports = filter not_this_mod (mi_exports iface)
156 not_this_mod (mod,_) = mod /= this_mod
157 -- If the module exports anything defined in this module, just
158 -- ignore it. Reason: otherwise it looks as if there are two
159 -- local definition sites for the thing, and an error gets
160 -- reported. Easiest thing is just to filter them out up
161 -- front. This situation only arises if a module imports
162 -- itself, or another module that imported it. (Necessarily,
163 -- this invoves a loop.)
165 -- Tiresome consequence: if you say
170 -- module B( AType ) where
171 -- import {-# SOURCE #-} A( AType )
173 -- then you'll get a 'B does not export AType' message. Oh well.
175 qual_mod_name = case as_mod of
176 Nothing -> imp_mod_name
177 Just another_name -> another_name
178 imp_spec = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,
179 is_dloc = loc, is_as = qual_mod_name }
182 -- Get the total exports from this module
183 total_avails <- ifaceExportNames filtered_exports
185 -- filter the imports according to the import declaration
186 (new_imp_details, gbl_env) <-
187 filterImports iface imp_spec imp_details total_avails
192 -- Compute new transitive dependencies
194 orphans | orph_iface = ASSERT( not (imp_mod `elem` dep_orphs deps) )
195 imp_mod : dep_orphs deps
196 | otherwise = dep_orphs deps
198 finsts | has_finsts = ASSERT( not (imp_mod `elem` dep_finsts deps) )
199 imp_mod : dep_finsts deps
200 | otherwise = dep_finsts deps
202 pkg = modulePackageId (mi_module iface)
204 (dependent_mods, dependent_pkgs)
205 | pkg == thisPackage dflags =
206 -- Imported module is from the home package
207 -- Take its dependent modules and add imp_mod itself
208 -- Take its dependent packages unchanged
210 -- NB: (dep_mods deps) might include a hi-boot file
211 -- for the module being compiled, CM. Do *not* filter
212 -- this out (as we used to), because when we've
213 -- finished dealing with the direct imports we want to
214 -- know if any of them depended on CM.hi-boot, in
215 -- which case we should do the hi-boot consistency
216 -- check. See LoadIface.loadHiBootInterface
217 ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)
220 -- Imported module is from another package
221 -- Dump the dependent modules
222 -- Add the package imp_mod comes from to the dependent packages
223 ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
224 ([], pkg : dep_pkgs deps)
226 -- True <=> import M ()
227 import_all = case imp_details of
228 Just (is_hiding, ls) -> not is_hiding && null ls
231 imports = ImportAvails {
232 imp_mods = unitModuleEnv imp_mod (imp_mod, [(qual_mod_name, import_all, loc)]),
235 imp_dep_mods = mkModDeps dependent_mods,
236 imp_dep_pkgs = dependent_pkgs
239 -- Complain if we import a deprecated module
240 ifOptM Opt_WarnDeprecations (
242 DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
246 let new_imp_decl = L loc (ImportDecl loc_imp_mod_name want_boot
247 qual_only as_mod new_imp_details)
249 returnM (new_imp_decl, gbl_env, imports, mi_hpc iface)
252 warnRedundantSourceImport mod_name
253 = ptext SLIT("Unnecessary {-# SOURCE #-} in the import of module")
254 <+> quotes (ppr mod_name)
258 %************************************************************************
260 importsFromLocalDecls
262 %************************************************************************
264 From the top-level declarations of this module produce
265 * the lexical environment
267 created by its bindings.
269 Complain about duplicate bindings
272 importsFromLocalDecls :: HsGroup RdrName -> RnM TcGblEnv
273 importsFromLocalDecls group
274 = do { gbl_env <- getGblEnv
276 ; avails <- getLocalDeclBinders gbl_env group
278 ; rdr_env' <- extendRdrEnvRn (tcg_rdr_env gbl_env) avails
280 ; traceRn (text "local avails: " <> ppr avails)
282 ; returnM (gbl_env { tcg_rdr_env = rdr_env' })
285 extendRdrEnvRn :: GlobalRdrEnv -> [AvailInfo] -> RnM GlobalRdrEnv
286 -- Add the new locally-bound names one by one, checking for duplicates as
287 -- we do so. Remember that in Template Haskell the duplicates
288 -- might *already be* in the GlobalRdrEnv from higher up the module
289 extendRdrEnvRn rdr_env avails
290 = foldlM add_local rdr_env (gresFromAvails LocalDef avails)
292 add_local rdr_env gre
293 | gres <- lookupGlobalRdrEnv rdr_env (nameOccName (gre_name gre))
294 , (dup_gre:_) <- filter isLocalGRE gres -- Check for existing *local* defns
295 = do { addDupDeclErr (gre_name dup_gre) (gre_name gre)
298 = return (extendGlobalRdrEnv rdr_env gre)
301 @getLocalDeclBinders@ returns the names for an @HsDecl@. It's
302 used for source code.
304 *** See "THE NAMING STORY" in HsDecls ****
306 Instances of type families
307 ~~~~~~~~~~~~~~~~~~~~~~~~~~
308 Indexed data/newtype instances contain data constructors that we need to
309 collect, too. Moreover, we need to descend into the data/newtypes instances
310 of associated families.
312 We need to be careful with the handling of the type constructor of each type
313 instance as the family constructor is already defined, and we want to avoid
314 raising a duplicate declaration error. So, we make a new name for it, but
315 don't return it in the 'AvailInfo'.
318 getLocalDeclBinders :: TcGblEnv -> HsGroup RdrName -> RnM [AvailInfo]
319 getLocalDeclBinders gbl_env (HsGroup {hs_valds = ValBindsIn val_decls val_sigs,
320 hs_tyclds = tycl_decls,
321 hs_instds = inst_decls,
322 hs_fords = foreign_decls })
323 = do { tc_names_s <- mappM new_tc tycl_decls
324 ; at_names_s <- mappM inst_ats inst_decls
325 ; val_names <- mappM new_simple val_bndrs
326 ; return (val_names ++ tc_names_s ++ concat at_names_s) }
328 mod = tcg_mod gbl_env
329 is_hs_boot = isHsBoot (tcg_src gbl_env) ;
330 val_bndrs | is_hs_boot = sig_hs_bndrs
331 | otherwise = for_hs_bndrs ++ val_hs_bndrs
332 -- In a hs-boot file, the value binders come from the
333 -- *signatures*, and there should be no foreign binders
335 new_simple rdr_name = do
336 nm <- newTopSrcBinder mod rdr_name
339 sig_hs_bndrs = [nm | L _ (TypeSig nm _) <- val_sigs]
340 val_hs_bndrs = collectHsBindLocatedBinders val_decls
341 for_hs_bndrs = [nm | L _ (ForeignImport nm _ _) <- foreign_decls]
344 | isFamInstDecl (unLoc tc_decl)
345 = do { main_name <- lookupFamInstDeclBndr mod main_rdr
346 ; sub_names <- mappM (newTopSrcBinder mod) sub_rdrs
347 ; return (AvailTC main_name sub_names) }
348 -- main_name is not bound here!
350 = do { main_name <- newTopSrcBinder mod main_rdr
351 ; sub_names <- mappM (newTopSrcBinder mod) sub_rdrs
352 ; return (AvailTC main_name (main_name : sub_names)) }
354 (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
357 = mappM new_tc (instDeclATs (unLoc inst_decl))
359 getLocalDeclBinders _ _ = panic "getLocalDeclBinders" -- ValBindsOut can't happen
363 %************************************************************************
365 \subsection{Filtering imports}
367 %************************************************************************
369 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
370 available, and filters it through the import spec (if any).
373 filterImports :: ModIface
374 -> ImpDeclSpec -- The span for the entire import decl
375 -> Maybe (Bool, [LIE RdrName]) -- Import spec; True => hiding
376 -> [AvailInfo] -- What's available
377 -> RnM (Maybe (Bool, [LIE Name]), -- Import spec w/ Names
378 GlobalRdrEnv) -- Same again, but in GRE form
380 filterImports iface decl_spec Nothing all_avails
381 = return (Nothing, mkGlobalRdrEnv (gresFromAvails prov all_avails))
383 prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
386 filterImports iface decl_spec (Just (want_hiding, import_items)) all_avails
387 = do -- check for errors, convert RdrNames to Names
388 opt_typeFamilies <- doptM Opt_TypeFamilies
389 items1 <- mapM (lookup_lie opt_typeFamilies) import_items
391 let items2 :: [(LIE Name, AvailInfo)]
392 items2 = concat items1
393 -- NB the AvailInfo may have duplicates, and several items
394 -- for the same parent; e.g N(x) and N(y)
396 names = availsToNameSet (map snd items2)
397 keep n = not (n `elemNameSet` names)
398 pruned_avails = filterAvails keep all_avails
399 hiding_prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
401 gres | want_hiding = gresFromAvails hiding_prov pruned_avails
402 | otherwise = concatMap (gresFromIE decl_spec) items2
404 return (Just (want_hiding, map fst items2), mkGlobalRdrEnv gres)
406 -- This environment is how we map names mentioned in the import
407 -- list to the actual Name they correspond to, and the name family
408 -- that the Name belongs to (the AvailInfo). The situation is
409 -- complicated by associated families, which introduce a three-level
410 -- hierachy, where class = grand parent, assoc family = parent, and
411 -- data constructors = children. The occ_env entries for associated
412 -- families needs to capture all this information; hence, we have the
413 -- third component of the environment that gives the class name (=
414 -- grand parent) in case of associated families.
416 -- This env will have entries for data constructors too,
417 -- they won't make any difference because naked entities like T
418 -- in an import list map to TcOccs, not VarOccs.
419 occ_env :: OccEnv (Name, -- the name
420 AvailInfo, -- the export item providing the name
421 Maybe Name) -- the parent of associated types
422 occ_env = mkOccEnv_C combine [ (nameOccName n, (n, a, Nothing))
423 | a <- all_avails, n <- availNames a]
425 -- we know that (1) there are at most entries for one name, (2) their
426 -- first component is identical, (3) they are for tys/cls, and (4) one
427 -- entry has the name in its parent position (the other doesn't)
428 combine (name, AvailTC p1 subs1, Nothing)
429 (_ , AvailTC p2 subs2, Nothing)
431 (parent, subs) = if p1 == name then (p2, subs1) else (p1, subs2)
433 (name, AvailTC name subs, Just parent)
435 lookup_lie :: Bool -> LIE RdrName -> TcRn [(LIE Name, AvailInfo)]
436 lookup_lie opt_typeFamilies (L loc ieRdr)
438 stuff <- setSrcSpan loc $
439 case lookup_ie opt_typeFamilies ieRdr of
440 Failed err -> addErr err >> return []
441 Succeeded a -> return a
442 checkDodgyImport stuff
443 return [ (L loc ie, avail) | (ie,avail) <- stuff ]
445 -- Warn when importing T(..) if T was exported abstractly
446 checkDodgyImport stuff
447 | IEThingAll n <- ieRdr, (_, AvailTC _ [one]):_ <- stuff
448 = ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn n))
449 -- NB. use the RdrName for reporting the warning
453 -- For each import item, we convert its RdrNames to Names,
454 -- and at the same time construct an AvailInfo corresponding
455 -- to what is actually imported by this item.
456 -- Returns Nothing on error.
457 -- We return a list here, because in the case of an import
458 -- item like C, if we are hiding, then C refers to *both* a
459 -- type/class and a data constructor. Moreover, when we import
460 -- data constructors of an associated family, we need separate
461 -- AvailInfos for the data constructors and the family (as they have
462 -- different parents). See the discussion at occ_env.
463 lookup_ie :: Bool -> IE RdrName -> MaybeErr Message [(IE Name,AvailInfo)]
464 lookup_ie opt_typeFamilies ie
465 = let bad_ie = Failed (badImportItemErr iface decl_spec ie)
467 lookup_name rdrName =
468 case lookupOccEnv occ_env (rdrNameOcc rdrName) of
474 (name, avail, _) <- lookup_name n
475 return [(IEVar name, trimAvail avail name)]
478 (name, avail@(AvailTC name2 subs), mb_parent) <- lookup_name tc
480 -- non-associated ty/cls
481 Nothing -> return [(IEThingAll name, avail)]
483 Just parent -> return [(IEThingAll name,
484 AvailTC name2 (subs \\ [name])),
485 (IEThingAll name, AvailTC parent [name])]
488 | want_hiding -- hiding ( C )
489 -- Here the 'C' can be a data constructor
490 -- *or* a type/class, or even both
491 -> let tc_name = lookup_name tc
492 dc_name = lookup_name (setRdrNameSpace tc srcDataName)
494 case catMaybeErr [ tc_name, dc_name ] of
496 names -> return [mkIEThingAbs name | name <- names]
498 -> do nameAvail <- lookup_name tc
499 return [mkIEThingAbs nameAvail]
501 IEThingWith tc ns -> do
502 (name, AvailTC name2 subnames, mb_parent) <- lookup_name tc
504 env = mkOccEnv [(nameOccName s, s) | s <- subnames]
505 mb_children = map (lookupOccEnv env . rdrNameOcc) ns
506 children <- if any isNothing mb_children
508 else return (catMaybes mb_children)
509 -- check for proper import of type families
510 when (not opt_typeFamilies && any isTyConName children) $
511 Failed (typeItemErr (head . filter isTyConName $ children)
512 (text "in import list"))
514 -- non-associated ty/cls
515 Nothing -> return [(IEThingWith name children,
516 AvailTC name (name:children))]
518 Just parent -> return [(IEThingWith name children,
519 AvailTC name children),
520 (IEThingWith name children,
521 AvailTC parent [name])]
523 _other -> Failed illegalImportItemErr
524 -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed
528 mkIEThingAbs (n, av, Nothing ) = (IEThingAbs n, trimAvail av n)
529 mkIEThingAbs (n, av, Just parent) = (IEThingAbs n, AvailTC parent [n])
532 catMaybeErr :: [MaybeErr err a] -> [a]
533 catMaybeErr ms = [ a | Succeeded a <- ms ]
536 %************************************************************************
540 %************************************************************************
543 -- | make a 'GlobalRdrEnv' where all the elements point to the same
544 -- import declaration (useful for "hiding" imports, or imports with
546 gresFromAvails :: Provenance -> [AvailInfo] -> [GlobalRdrElt]
547 gresFromAvails prov avails
548 = concatMap (gresFromAvail (const prov)) avails
550 gresFromAvail :: (Name -> Provenance) -> AvailInfo -> [GlobalRdrElt]
551 gresFromAvail prov_fn avail
552 = [ GRE {gre_name = n,
553 gre_par = availParent n avail,
554 gre_prov = prov_fn n}
555 | n <- availNames avail ]
557 greAvail :: GlobalRdrElt -> AvailInfo
558 greAvail gre = mkUnitAvail (gre_name gre) (gre_par gre)
560 mkUnitAvail :: Name -> Parent -> AvailInfo
561 mkUnitAvail me (ParentIs p) = AvailTC p [me]
562 mkUnitAvail me NoParent | isTyConName me = AvailTC me [me]
563 | otherwise = Avail me
565 plusAvail (Avail n1) (Avail n2) = Avail n1
566 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
567 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
569 availParent :: Name -> AvailInfo -> Parent
570 availParent n (Avail _) = NoParent
571 availParent n (AvailTC m ms) | n==m = NoParent
572 | otherwise = ParentIs m
574 trimAvail :: AvailInfo -> Name -> AvailInfo
575 trimAvail (Avail n) m = Avail n
576 trimAvail (AvailTC n ns) m = ASSERT( m `elem` ns) AvailTC n [m]
578 -- | filters 'AvailInfo's by the given predicate
579 filterAvails :: (Name -> Bool) -> [AvailInfo] -> [AvailInfo]
580 filterAvails keep avails = foldr (filterAvail keep) [] avails
582 -- | filters an 'AvailInfo' by the given predicate
583 filterAvail :: (Name -> Bool) -> AvailInfo -> [AvailInfo] -> [AvailInfo]
584 filterAvail keep ie rest =
586 Avail n | keep n -> ie : rest
589 let left = filter keep ns in
590 if null left then rest else AvailTC tc left : rest
592 -- | Given an import/export spec, construct the appropriate 'GlobalRdrElt's.
593 gresFromIE :: ImpDeclSpec -> (LIE Name, AvailInfo) -> [GlobalRdrElt]
594 gresFromIE decl_spec (L loc ie, avail)
595 = gresFromAvail prov_fn avail
597 is_explicit = case ie of
598 IEThingAll name -> \n -> n==name
600 prov_fn name = Imported [imp_spec]
602 imp_spec = ImpSpec { is_decl = decl_spec, is_item = item_spec }
603 item_spec = ImpSome { is_explicit = is_explicit name, is_iloc = loc }
605 mkChildEnv :: [GlobalRdrElt] -> NameEnv [Name]
606 mkChildEnv gres = foldr add emptyNameEnv gres
608 add (GRE { gre_name = n, gre_par = ParentIs p }) env = extendNameEnv_C (++) env p [n]
609 add other_gre env = env
611 findChildren :: NameEnv [Name] -> Name -> [Name]
612 findChildren env n = lookupNameEnv env n `orElse` []
615 ---------------------------------------
618 All this AvailEnv stuff is hardly used; only in a very small
619 part of RnNames. Todo: remove?
620 ---------------------------------------
623 type AvailEnv = NameEnv AvailInfo -- Maps a Name to the AvailInfo that contains it
625 emptyAvailEnv :: AvailEnv
626 emptyAvailEnv = emptyNameEnv
628 unitAvailEnv :: AvailInfo -> AvailEnv
629 unitAvailEnv a = unitNameEnv (availName a) a
631 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
632 plusAvailEnv = plusNameEnv_C plusAvail
634 availEnvElts :: AvailEnv -> [AvailInfo]
635 availEnvElts = nameEnvElts
637 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
638 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
640 mkAvailEnv :: [AvailInfo] -> AvailEnv
641 -- 'avails' may have several items with the same availName
642 -- E.g import Ix( Ix(..), index )
643 -- will give Ix(Ix,index,range) and Ix(index)
644 -- We want to combine these; addAvail does that
645 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
647 -- After combining the avails, we need to ensure that the parent name is the
648 -- first entry in the list of subnames, if it is included at all. (Subsequent
649 -- functions rely on that.)
650 normaliseAvail :: AvailInfo -> AvailInfo
651 normaliseAvail avail@(Avail _) = avail
652 normaliseAvail (AvailTC name subs) = AvailTC name subs'
654 subs' = if name `elem` subs then name : (delete name subs) else subs
656 -- | combines 'AvailInfo's from the same family
657 nubAvails :: [AvailInfo] -> [AvailInfo]
658 nubAvails avails = map normaliseAvail . nameEnvElts . mkAvailEnv $ avails
662 %************************************************************************
664 \subsection{Export list processing}
666 %************************************************************************
668 Processing the export list.
670 You might think that we should record things that appear in the export
671 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
672 wrong. We do check (here) that they are in scope, but there is no
673 need to slurp in their actual declaration (which is what
674 @addOccurrenceName@ forces).
676 Indeed, doing so would big trouble when compiling @PrelBase@, because
677 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
678 @ConcBase.StateAndSynchVar#@, and so on...
681 type ExportAccum -- The type of the accumulating parameter of
682 -- the main worker function in rnExports
683 = ([LIE Name], -- Export items with Names
684 ExportOccMap, -- Tracks exported occurrence names
685 [AvailInfo]) -- The accumulated exported stuff
688 emptyExportAccum = ([], emptyOccEnv, [])
690 type ExportOccMap = OccEnv (Name, IE RdrName)
691 -- Tracks what a particular exported OccName
692 -- in an export list refers to, and which item
693 -- it came from. It's illegal to export two distinct things
694 -- that have the same occurrence name
696 rnExports :: Bool -- False => no 'module M(..) where' header at all
697 -> Maybe [LIE RdrName] -- Nothing => no explicit export list
701 -- Complains if two distinct exports have same OccName
702 -- Warns about identical exports.
703 -- Complains about exports items not in scope
705 rnExports explicit_mod exports
706 tcg_env@(TcGblEnv { tcg_mod = this_mod,
707 tcg_rdr_env = rdr_env,
708 tcg_imports = imports })
710 -- If the module header is omitted altogether, then behave
711 -- as if the user had written "module Main(main) where..."
712 -- EXCEPT in interactive mode, when we behave as if he had
713 -- written "module Main where ..."
714 -- Reason: don't want to complain about 'main' not in scope
715 -- in interactive mode
718 | explicit_mod = exports
719 | ghcLink dflags == LinkInMemory = Nothing
720 | otherwise = Just ([noLoc (IEVar main_RDR_Unqual)])
721 -- ToDo: the 'noLoc' here is unhelpful if 'main'
722 -- turns out to be out of scope
724 ; (rn_exports, avails) <- exports_from_avail real_exports rdr_env imports this_mod
725 ; let final_avails = nubAvails avails -- Combine families
727 ; return (tcg_env { tcg_exports = final_avails,
728 tcg_rn_exports = case tcg_rn_exports tcg_env of
730 Just _ -> rn_exports,
731 tcg_dus = tcg_dus tcg_env `plusDU`
732 usesOnly (availsToNameSet final_avails) }) }
735 exports_from_avail :: Maybe [LIE RdrName]
736 -- Nothing => no explicit export list
740 -> RnM (Maybe [LIE Name], [AvailInfo])
742 exports_from_avail Nothing rdr_env imports this_mod
743 = -- The same as (module M) where M is the current module name,
744 -- so that's how we handle it.
746 avails = [ greAvail gre | gre <- globalRdrEnvElts rdr_env,
749 return (Nothing, avails)
751 exports_from_avail (Just rdr_items) rdr_env imports this_mod
752 = do (ie_names, _, exports) <- foldlM do_litem emptyExportAccum rdr_items
754 return (Just ie_names, exports)
756 do_litem :: ExportAccum -> LIE RdrName -> RnM ExportAccum
757 do_litem acc lie = setSrcSpan (getLoc lie) (exports_from_item acc lie)
759 kids_env :: NameEnv [Name] -- Maps a parent to its in-scope children
760 kids_env = mkChildEnv (globalRdrEnvElts rdr_env)
762 imported_modules = [ qual_name
763 | (_, xs) <- moduleEnvElts $ imp_mods imports,
764 (qual_name, _, _) <- xs ]
766 exports_from_item :: ExportAccum -> LIE RdrName -> RnM ExportAccum
767 exports_from_item acc@(ie_names, occs, exports)
768 (L loc ie@(IEModuleContents mod))
769 | let earlier_mods = [ mod | (L _ (IEModuleContents mod)) <- ie_names ]
770 , mod `elem` earlier_mods -- Duplicate export of M
771 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
772 warnIf warn_dup_exports (dupModuleExport mod) ;
776 = do { implicit_prelude <- doptM Opt_ImplicitPrelude
777 ; let { exportValid = (mod `elem` imported_modules)
778 || (moduleName this_mod == mod)
779 ; gres = filter (isModuleExported implicit_prelude mod)
780 (globalRdrEnvElts rdr_env)
783 ; checkErr exportValid (moduleNotImported mod)
784 ; warnIf (exportValid && null gres) (nullModuleExport mod)
786 ; occs' <- check_occs ie occs (map gre_name gres)
787 -- This check_occs not only finds conflicts
788 -- between this item and others, but also
789 -- internally within this item. That is, if
790 -- 'M.x' is in scope in several ways, we'll have
791 -- several members of mod_avails with the same
793 ; return (L loc (IEModuleContents mod) : ie_names,
794 occs', map greAvail gres ++ exports) }
796 exports_from_item acc@(lie_names, occs, exports) (L loc ie)
798 = do new_ie <- lookup_doc_ie ie
799 return (L loc new_ie : lie_names, occs, exports)
802 = do (new_ie, avail) <- lookup_ie ie
803 if isUnboundName (ieName new_ie)
804 then return acc -- Avoid error cascade
807 occs' <- check_occs ie occs (availNames avail)
809 return (L loc new_ie : lie_names, occs', avail : exports)
812 lookup_ie :: IE RdrName -> RnM (IE Name, AvailInfo)
813 lookup_ie (IEVar rdr)
814 = do gre <- lookupGreRn rdr
815 return (IEVar (gre_name gre), greAvail gre)
817 lookup_ie (IEThingAbs rdr)
818 = do gre <- lookupGreRn rdr
819 let name = gre_name gre
821 NoParent -> return (IEThingAbs name,
823 ParentIs p -> return (IEThingAbs name,
826 lookup_ie ie@(IEThingAll rdr)
827 = do name <- lookupGlobalOccRn rdr
828 let kids = findChildren kids_env name
830 (if (isTyConName name) then addWarn (dodgyExportWarn name)
831 -- This occurs when you export T(..), but
832 -- only import T abstractly, or T is a synonym.
833 else addErr (exportItemErr ie))
835 return (IEThingAll name, AvailTC name (name:kids))
837 lookup_ie ie@(IEThingWith rdr sub_rdrs)
838 = do name <- lookupGlobalOccRn rdr
839 if isUnboundName name
840 then return (IEThingWith name [], AvailTC name [name])
842 let env = mkOccEnv [ (nameOccName s, s)
843 | s <- findChildren kids_env name ]
844 mb_names = map (lookupOccEnv env . rdrNameOcc) sub_rdrs
845 if any isNothing mb_names
846 then do addErr (exportItemErr ie)
847 return (IEThingWith name [], AvailTC name [name])
848 else do let names = catMaybes mb_names
849 optTyFam <- doptM Opt_TypeFamilies
850 when (not optTyFam && any isTyConName names) $
851 addErr (typeItemErr ( head
854 (text "in export list"))
855 return (IEThingWith name names, AvailTC name (name:names))
857 lookup_ie ie = panic "lookup_ie" -- Other cases covered earlier
860 lookup_doc_ie :: IE RdrName -> RnM (IE Name)
861 lookup_doc_ie (IEGroup lev doc) = do rn_doc <- rnHsDoc doc
862 return (IEGroup lev rn_doc)
863 lookup_doc_ie (IEDoc doc) = do rn_doc <- rnHsDoc doc
864 return (IEDoc rn_doc)
865 lookup_doc_ie (IEDocNamed str) = return (IEDocNamed str)
866 lookup_doc_ie ie = panic "lookup_doc_ie" -- Other cases covered earlier
869 isDoc (IEDoc _) = True
870 isDoc (IEDocNamed _) = True
871 isDoc (IEGroup _ _) = True
874 -------------------------------
875 isModuleExported :: Bool -> ModuleName -> GlobalRdrElt -> Bool
876 -- True if the thing is in scope *both* unqualified, *and* with qualifier M
877 isModuleExported implicit_prelude mod (GRE { gre_name = name, gre_prov = prov })
878 | implicit_prelude && isBuiltInSyntax name = False
879 -- Optimisation: filter out names for built-in syntax
880 -- They just clutter up the environment (esp tuples), and the parser
881 -- will generate Exact RdrNames for them, so the cluttered
882 -- envt is no use. To avoid doing this filter all the time,
883 -- we use -fno-implicit-prelude as a clue that the filter is
884 -- worth while. Really, it's only useful for GHC.Base and GHC.Tuple.
886 -- It's worth doing because it makes the environment smaller for
887 -- every module that imports the Prelude
890 LocalDef -> moduleName (nameModule name) == mod
891 Imported is -> any unQualSpecOK is && any (qualSpecOK mod) is
893 -------------------------------
894 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
895 check_occs ie occs names
896 = foldlM check occs names
899 = case lookupOccEnv occs name_occ of
900 Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
903 | name == name' -- Duplicate export
904 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
905 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
908 | otherwise -- Same occ name but different names: an error
909 -> do { global_env <- getGlobalRdrEnv ;
910 addErr (exportClashErr global_env name' name ie' ie) ;
913 name_occ = nameOccName name
916 %*********************************************************
920 %*********************************************************
923 finishDeprecations :: DynFlags -> Maybe DeprecTxt
924 -> TcGblEnv -> RnM TcGblEnv
925 -- (a) Report usasge of deprecated imports
926 -- (b) If the whole module is deprecated, update tcg_deprecs
927 -- All this happens only once per module
928 finishDeprecations dflags mod_deprec tcg_env
929 = do { (eps,hpt) <- getEpsAndHpt
930 ; ifOptM Opt_WarnDeprecations $
931 mapM_ (check hpt (eps_PIT eps)) all_gres
932 -- By this time, typechecking is complete,
933 -- so the PIT is fully populated
935 -- Deal with a module deprecation; it overrides all existing deprecs
936 ; let new_deprecs = case mod_deprec of
937 Just txt -> DeprecAll txt
938 Nothing -> tcg_deprecs tcg_env
939 ; return (tcg_env { tcg_deprecs = new_deprecs }) }
941 used_names = allUses (tcg_dus tcg_env)
942 -- Report on all deprecated uses; hence allUses
943 all_gres = globalRdrEnvElts (tcg_rdr_env tcg_env)
945 check hpt pit gre@(GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
946 | name `elemNameSet` used_names
947 , Just deprec_txt <- lookupImpDeprec dflags hpt pit gre
948 = addWarnAt (importSpecLoc imp_spec)
949 (sep [ptext SLIT("Deprecated use of") <+>
950 pprNonVarNameSpace (occNameSpace (nameOccName name)) <+>
952 (parens imp_msg) <> colon,
955 name_mod = nameModule name
956 imp_mod = importSpecModule imp_spec
957 imp_msg = ptext SLIT("imported from") <+> ppr imp_mod <> extra
958 extra | imp_mod == moduleName name_mod = empty
959 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
961 check hpt pit ok_gre = returnM () -- Local, or not used, or not deprectated
962 -- The Imported pattern-match: don't deprecate locally defined names
963 -- For a start, we may be exporting a deprecated thing
964 -- Also we may use a deprecated thing in the defn of another
965 -- deprecated things. We may even use a deprecated thing in
966 -- the defn of a non-deprecated thing, when changing a module's
969 lookupImpDeprec :: DynFlags -> HomePackageTable -> PackageIfaceTable
970 -> GlobalRdrElt -> Maybe DeprecTxt
971 -- The name is definitely imported, so look in HPT, PIT
972 lookupImpDeprec dflags hpt pit gre
973 = case lookupIfaceByModule dflags hpt pit (nameModule name) of
974 Just iface -> mi_dep_fn iface name `seqMaybe` -- Bleat if the thing, *or
976 ParentIs p -> mi_dep_fn iface p -- its parent*, is deprec'd
979 Nothing -> Nothing -- See Note [Used names with interface not loaded]
984 Note [Used names with interface not loaded]
985 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
986 By now all the interfaces should have been loaded,
987 because reportDeprecations happens after typechecking.
988 However, it's still (just) possible to to find a used
989 Name whose interface hasn't been loaded:
991 a) It might be a WiredInName; in that case we may not load
992 its interface (although we could).
994 b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
995 These are seen as "used" by the renamer (if -fno-implicit-prelude)
996 is on), but the typechecker may discard their uses
997 if in fact the in-scope fromRational is GHC.Read.fromRational,
998 (see tcPat.tcOverloadedLit), and the typechecker sees that the type
999 is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
1000 In that obscure case it won't force the interface in.
1002 In both cases we simply don't permit deprecations;
1003 this is, after all, wired-in stuff.
1006 %*********************************************************
1010 %*********************************************************
1013 reportUnusedNames :: Maybe [LIE RdrName] -- Export list
1014 -> TcGblEnv -> RnM ()
1015 reportUnusedNames export_decls gbl_env
1016 = do { traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env)))
1017 ; warnUnusedTopBinds unused_locals
1018 ; warnUnusedModules unused_imp_mods
1019 ; warnUnusedImports unused_imports
1020 ; warnDuplicateImports defined_and_used
1021 ; printMinimalImports minimal_imports }
1023 used_names :: NameSet
1024 used_names = findUses (tcg_dus gbl_env) emptyNameSet
1025 -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
1028 -- Collect the defined names from the in-scope environment
1029 defined_names :: [GlobalRdrElt]
1030 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
1032 -- Note that defined_and_used, defined_but_not_used
1033 -- are both [GRE]; that's why we need defined_and_used
1034 -- rather than just used_names
1035 defined_and_used, defined_but_not_used :: [GlobalRdrElt]
1036 (defined_and_used, defined_but_not_used)
1037 = partition (gre_is_used used_names) defined_names
1039 kids_env = mkChildEnv defined_names
1040 -- This is done in mkExports too; duplicated work
1042 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
1043 gre_is_used used_names (GRE {gre_name = name})
1044 = name `elemNameSet` used_names
1045 || any (`elemNameSet` used_names) (findChildren kids_env name)
1046 -- A use of C implies a use of T,
1047 -- if C was brought into scope by T(..) or T(C)
1049 -- Filter out the ones that are
1050 -- (a) defined in this module, and
1051 -- (b) not defined by a 'deriving' clause
1052 -- The latter have an Internal Name, so we can filter them out easily
1053 unused_locals :: [GlobalRdrElt]
1054 unused_locals = filter is_unused_local defined_but_not_used
1055 is_unused_local :: GlobalRdrElt -> Bool
1056 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
1058 unused_imports :: [GlobalRdrElt]
1059 unused_imports = mapCatMaybes unused_imp defined_but_not_used
1060 unused_imp :: GlobalRdrElt -> Maybe GlobalRdrElt -- Result has trimmed Imported provenances
1061 unused_imp gre@(GRE {gre_prov = LocalDef}) = Nothing
1062 unused_imp gre@(GRE {gre_prov = Imported imp_specs})
1063 | null trimmed_specs = Nothing
1064 | otherwise = Just (gre {gre_prov = Imported trimmed_specs})
1066 trimmed_specs = filter report_if_unused imp_specs
1068 -- To figure out the minimal set of imports, start with the things
1069 -- that are in scope (i.e. in gbl_env). Then just combine them
1070 -- into a bunch of avails, so they are properly grouped
1072 -- BUG WARNING: this does not deal properly with qualified imports!
1073 minimal_imports :: FiniteMap ModuleName AvailEnv
1074 minimal_imports0 = foldr add_expall emptyFM expall_mods
1075 minimal_imports1 = foldr add_name minimal_imports0 defined_and_used
1076 minimal_imports = foldr add_inst_mod minimal_imports1 direct_import_mods
1077 -- The last line makes sure that we retain all direct imports
1078 -- even if we import nothing explicitly.
1079 -- It's not necessarily redundant to import such modules. Consider
1083 -- The import M() is not *necessarily* redundant, even if
1084 -- we suck in no instance decls from M (e.g. it contains
1085 -- no instance decls, or This contains no code). It may be
1086 -- that we import M solely to ensure that M's orphan instance
1087 -- decls (or those in its imports) are visible to people who
1088 -- import This. Sigh.
1089 -- There's really no good way to detect this, so the error message
1090 -- in RnEnv.warnUnusedModules is weakened instead
1092 -- We've carefully preserved the provenance so that we can
1093 -- construct minimal imports that import the name by (one of)
1094 -- the same route(s) as the programmer originally did.
1095 add_name gre@(GRE {gre_prov = Imported (imp_spec:_)}) acc
1096 = addToFM_C plusAvailEnv acc
1097 (importSpecModule imp_spec) (unitAvailEnv (greAvail gre))
1098 add_name gre acc = acc -- Local
1100 -- Modules mentioned as 'module M' in the export list
1101 expall_mods = case export_decls of
1103 Just es -> [m | L _ (IEModuleContents m) <- es]
1105 -- This is really bogus. The idea is that if we see 'module M' in
1106 -- the export list we must retain the import decls that drive it
1107 -- If we aren't careful we might see
1108 -- module A( module M ) where
1111 -- and suppose that N exports everything that M does. Then we
1112 -- must not drop the import of M even though N brings it all into
1115 -- BUG WARNING: 'module M' exports aside, what if M.x is mentioned?!
1117 -- The reason that add_expall is bogus is that it doesn't take
1118 -- qualified imports into account. But it's an improvement.
1119 add_expall mod acc = addToFM_C plusAvailEnv acc mod emptyAvailEnv
1121 add_inst_mod (mod, _) acc
1122 | mod_name `elemFM` acc = acc -- We import something already
1123 | otherwise = addToFM acc mod_name emptyAvailEnv
1125 mod_name = moduleName mod
1126 -- Add an empty collection of imports for a module
1127 -- from which we have sucked only instance decls
1129 imports = tcg_imports gbl_env
1131 direct_import_mods :: [(Module, [(ModuleName, Bool, SrcSpan)])]
1132 -- See the type of the imp_mods for this triple
1133 direct_import_mods = moduleEnvElts (imp_mods imports)
1135 -- unused_imp_mods are the directly-imported modules
1136 -- that are not mentioned in minimal_imports1
1137 -- [Note: not 'minimal_imports', because that includes directly-imported
1138 -- modules even if we use nothing from them; see notes above]
1140 -- BUG WARNING: this code is generally buggy
1141 unused_imp_mods :: [(ModuleName, SrcSpan)]
1142 unused_imp_mods = [(mod_name,loc)
1143 | (mod, xs) <- direct_import_mods,
1144 (_, no_imp, loc) <- xs,
1145 let mod_name = moduleName mod,
1146 not (mod_name `elemFM` minimal_imports1),
1149 -- The not no_imp part is not to complain about
1150 -- import M (), which is an idiom for importing
1151 -- instance declarations
1153 module_unused :: ModuleName -> Bool
1154 module_unused mod = any (((==) mod) . fst) unused_imp_mods
1156 report_if_unused :: ImportSpec -> Bool
1157 -- Do we want to report this as an unused import?
1158 report_if_unused (ImpSpec {is_decl = d, is_item = i})
1159 = not (module_unused (is_mod d)) -- Not if we've already said entire import is unused
1160 && isExplicitItem i -- Only if the import was explicit
1162 ---------------------
1163 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
1164 -- Given the GREs for names that are used, figure out which imports
1165 -- could be omitted without changing the top-level environment.
1167 -- NB: Given import Foo( T )
1168 -- import qualified Foo
1169 -- we do not report a duplicate import, even though Foo.T is brought
1170 -- into scope by both, because there's nothing you can *omit* without
1171 -- changing the top-level environment. So we complain only if it's
1172 -- explicitly named in both imports or neither.
1174 -- Furthermore, we complain about Foo.T only if
1175 -- there is no complaint about (unqualified) T
1177 warnDuplicateImports gres
1178 = ifOptM Opt_WarnUnusedImports $
1179 sequenceM_ [ warn name pr
1180 | GRE { gre_name = name, gre_prov = Imported imps } <- gres
1181 , pr <- redundants imps ]
1183 warn name (red_imp, cov_imp)
1184 = addWarnAt (importSpecLoc red_imp)
1185 (vcat [ptext SLIT("Redundant import of:") <+> quotes pp_name,
1186 ptext SLIT("It is also") <+> ppr cov_imp])
1188 pp_name | is_qual red_decl = ppr (is_as red_decl) <> dot <> ppr occ
1189 | otherwise = ppr occ
1190 occ = nameOccName name
1191 red_decl = is_decl red_imp
1193 redundants :: [ImportSpec] -> [(ImportSpec,ImportSpec)]
1194 -- The returned pair is (redundant-import, covering-import)
1196 = [ (red_imp, cov_imp)
1198 , isExplicitItem (is_item red_imp)
1199 -- Complain only about redundant imports
1200 -- mentioned explicitly by the user
1201 , cov_imp <- take 1 (filter (covers red_imp) imps) ]
1202 -- The 'take 1' picks the first offending group
1203 -- for this particular name
1205 -- "red_imp" is a putative redundant import
1206 -- "cov_imp" potentially covers it
1207 -- This test decides whether red_imp could be dropped
1209 -- NOTE: currently the test does not warn about
1212 -- even if the same underlying 'x' is involved, because dropping
1213 -- either import would change the qualified names in scope (M.x, N.x)
1214 -- But if the qualified names aren't used, the import is indeed redundant
1215 -- Sadly we don't know that. Oh well.
1216 covers red_imp@(ImpSpec { is_decl = red_decl, is_item = red_item })
1217 cov_imp@(ImpSpec { is_decl = cov_decl, is_item = cov_item })
1218 | red_loc == cov_loc
1219 = False -- Ignore diagonal elements
1220 | not (is_as red_decl == is_as cov_decl)
1221 = False -- They bring into scope different qualified names
1222 | not (is_qual red_decl) && is_qual cov_decl
1223 = False -- Covering one doesn't bring unqualified name into scope
1225 = not (isExplicitItem cov_item) -- Redundant one is selective and covering one isn't
1226 || red_later -- or both are explicit; tie-break using red_later
1229 = not cov_selective -- Redundant one is selective and covering one isn't
1230 || red_later -- Both are explicit; tie-break using red_later
1232 = not cov_selective -- Neither import is selective
1233 && (is_mod red_decl == is_mod cov_decl) -- They import the same module
1234 && red_later -- Tie-break
1237 red_loc = importSpecLoc red_imp
1238 cov_loc = importSpecLoc cov_imp
1239 red_later = red_loc > cov_loc
1241 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
1242 printMinimalImports :: FiniteMap ModuleName AvailEnv -- Minimal imports
1244 printMinimalImports imps
1245 = ifOptM Opt_D_dump_minimal_imports $ do {
1247 mod_ies <- initIfaceTcRn $ mappM to_ies (fmToList imps) ;
1248 this_mod <- getModule ;
1249 rdr_env <- getGlobalRdrEnv ;
1250 ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
1251 printForUser h (mkPrintUnqualified rdr_env)
1252 (vcat (map ppr_mod_ie mod_ies)) })
1255 mkFilename this_mod = moduleNameString (moduleName this_mod) ++ ".imports"
1256 ppr_mod_ie (mod_name, ies)
1257 | mod_name == moduleName pRELUDE
1259 | null ies -- Nothing except instances comes from here
1260 = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("() -- Instances only")
1262 = ptext SLIT("import") <+> ppr mod_name <>
1263 parens (fsep (punctuate comma (map ppr ies)))
1265 to_ies (mod, avail_env) = do ies <- mapM to_ie (availEnvElts avail_env)
1268 to_ie :: AvailInfo -> IfG (IE Name)
1269 -- The main trick here is that if we're importing all the constructors
1270 -- we want to say "T(..)", but if we're importing only a subset we want
1271 -- to say "T(A,B,C)". So we have to find out what the module exports.
1272 to_ie (Avail n) = returnM (IEVar n)
1273 to_ie (AvailTC n [m]) = ASSERT( n==m )
1274 returnM (IEThingAbs n)
1275 to_ie (AvailTC n ns)
1276 = loadSysInterface doc n_mod `thenM` \ iface ->
1277 case [xs | (m,as) <- mi_exports iface,
1280 x == nameOccName n] of
1281 [xs] | all_used xs -> returnM (IEThingAll n)
1282 | otherwise -> returnM (IEThingWith n (filter (/= n) ns))
1283 other -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
1286 all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
1287 doc = text "Compute minimal imports from" <+> ppr n
1288 n_mod = nameModule n
1292 %************************************************************************
1296 %************************************************************************
1299 badImportItemErr iface decl_spec ie
1300 = sep [ptext SLIT("Module"), quotes (ppr (is_mod decl_spec)), source_import,
1301 ptext SLIT("does not export"), quotes (ppr ie)]
1303 source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
1306 illegalImportItemErr = ptext SLIT("Illegal import item")
1308 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
1309 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
1312 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
1313 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructors or class methods,"),
1314 ptext SLIT("but it has none") ]
1316 exportItemErr export_item
1317 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
1318 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
1320 typeItemErr name wherestr
1321 = sep [ ptext SLIT("Using 'type' tag on") <+> quotes (ppr name) <+> wherestr,
1322 ptext SLIT("Use -ftype-families to enable this extension") ]
1324 exportClashErr :: GlobalRdrEnv -> Name -> Name -> IE RdrName -> IE RdrName
1326 exportClashErr global_env name1 name2 ie1 ie2
1327 = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
1328 , ppr_export ie1' name1'
1329 , ppr_export ie2' name2' ]
1331 occ = nameOccName name1
1332 ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+>
1333 quotes (ppr name) <+> pprNameProvenance (get_gre name))
1335 -- get_gre finds a GRE for the Name, so that we can show its provenance
1337 = case lookupGRE_Name global_env name of
1339 [] -> pprPanic "exportClashErr" (ppr name)
1340 get_loc name = nameSrcLoc $ gre_name $ get_gre name
1341 (name1', ie1', name2', ie2') = if get_loc name1 < get_loc name2
1342 then (name1, ie1, name2, ie2)
1343 else (name2, ie2, name1, ie1)
1345 addDupDeclErr :: Name -> Name -> TcRn ()
1346 addDupDeclErr name_a name_b
1347 = addErrAt (srcLocSpan loc2) $
1348 vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
1349 ptext SLIT("Declared at:") <+> vcat [ppr (nameSrcLoc name1), ppr loc2]]
1351 loc2 = nameSrcLoc name2
1352 (name1,name2) | nameSrcLoc name_a > nameSrcLoc name_b = (name_b,name_a)
1353 | otherwise = (name_a,name_b)
1354 -- Report the error at the later location
1356 dupExportWarn occ_name ie1 ie2
1357 = hsep [quotes (ppr occ_name),
1358 ptext SLIT("is exported by"), quotes (ppr ie1),
1359 ptext SLIT("and"), quotes (ppr ie2)]
1362 = hsep [ptext SLIT("Duplicate"),
1363 quotes (ptext SLIT("Module") <+> ppr mod),
1364 ptext SLIT("in export list")]
1366 moduleNotImported :: ModuleName -> SDoc
1367 moduleNotImported mod
1368 = ptext SLIT("The export item `module") <+> ppr mod <>
1369 ptext SLIT("' is not imported")
1371 nullModuleExport mod
1372 = ptext SLIT("The export item `module") <+> ppr mod <> ptext SLIT("' exports nothing")
1374 moduleDeprec mod txt
1375 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),
1379 = ptext SLIT("Module `Prelude' implicitly imported")