145d6fca7d1e04b14cbb5f48e3a19178fa5f5408
[ghc.git] / compiler / rename / RnNames.hs
1 {-
2 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3
4 \section[RnNames]{Extracting imported and top-level names in scope}
5 -}
6
7 {-# LANGUAGE CPP, NondecreasingIndentation #-}
8
9 module RnNames (
10 rnImports, getLocalNonValBinders,
11 rnExports, extendGlobalRdrEnvRn,
12 gresFromAvails,
13 calculateAvails,
14 reportUnusedNames,
15 checkConName
16 ) where
17
18 #include "HsVersions.h"
19
20 import DynFlags
21 import HsSyn
22 import TcEnv ( isBrackStage )
23 import RnEnv
24 import RnHsDoc ( rnHsDoc )
25 import LoadIface ( loadSrcInterface )
26 import TcRnMonad
27 import PrelNames
28 import Module
29 import Name
30 import NameEnv
31 import NameSet
32 import Avail
33 import HscTypes
34 import RdrName
35 import Outputable
36 import Maybes
37 import SrcLoc
38 import BasicTypes ( TopLevelFlag(..) )
39 import ErrUtils
40 import Util
41 import FastString
42 import ListSetOps
43
44 import Control.Monad
45 import Data.Map ( Map )
46 import qualified Data.Map as Map
47 import Data.List ( partition, (\\), find )
48 import qualified Data.Set as Set
49 import System.FilePath ((</>))
50 import System.IO
51
52 {-
53 ************************************************************************
54 * *
55 \subsection{rnImports}
56 * *
57 ************************************************************************
58
59 Note [Tracking Trust Transitively]
60 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
61 When we import a package as well as checking that the direct imports are safe
62 according to the rules outlined in the Note [HscMain . Safe Haskell Trust Check]
63 we must also check that these rules hold transitively for all dependent modules
64 and packages. Doing this without caching any trust information would be very
65 slow as we would need to touch all packages and interface files a module depends
66 on. To avoid this we make use of the property that if a modules Safe Haskell
67 mode changes, this triggers a recompilation from that module in the dependcy
68 graph. So we can just worry mostly about direct imports.
69
70 There is one trust property that can change for a package though without
71 recompliation being triggered: package trust. So we must check that all
72 packages a module tranitively depends on to be trusted are still trusted when
73 we are compiling this module (as due to recompilation avoidance some modules
74 below may not be considered trusted any more without recompilation being
75 triggered).
76
77 We handle this by augmenting the existing transitive list of packages a module M
78 depends on with a bool for each package that says if it must be trusted when the
79 module M is being checked for trust. This list of trust required packages for a
80 single import is gathered in the rnImportDecl function and stored in an
81 ImportAvails data structure. The union of these trust required packages for all
82 imports is done by the rnImports function using the combine function which calls
83 the plusImportAvails function that is a union operation for the ImportAvails
84 type. This gives us in an ImportAvails structure all packages required to be
85 trusted for the module we are currently compiling. Checking that these packages
86 are still trusted (and that direct imports are trusted) is done in
87 HscMain.checkSafeImports.
88
89 See the note below, [Trust Own Package] for a corner case in this method and
90 how its handled.
91
92
93 Note [Trust Own Package]
94 ~~~~~~~~~~~~~~~~~~~~~~~~
95 There is a corner case of package trust checking that the usual transitive check
96 doesn't cover. (For how the usual check operates see the Note [Tracking Trust
97 Transitively] below). The case is when you import a -XSafe module M and M
98 imports a -XTrustworthy module N. If N resides in a different package than M,
99 then the usual check works as M will record a package dependency on N's package
100 and mark it as required to be trusted. If N resides in the same package as M
101 though, then importing M should require its own package be trusted due to N
102 (since M is -XSafe so doesn't create this requirement by itself). The usual
103 check fails as a module doesn't record a package dependency of its own package.
104 So instead we now have a bool field in a modules interface file that simply
105 states if the module requires its own package to be trusted. This field avoids
106 us having to load all interface files that the module depends on to see if one
107 is trustworthy.
108
109
110 Note [Trust Transitive Property]
111 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
112 So there is an interesting design question in regards to transitive trust
113 checking. Say I have a module B compiled with -XSafe. B is dependent on a bunch
114 of modules and packages, some packages it requires to be trusted as its using
115 -XTrustworthy modules from them. Now if I have a module A that doesn't use safe
116 haskell at all and simply imports B, should A inherit all the the trust
117 requirements from B? Should A now also require that a package p is trusted since
118 B required it?
119
120 We currently say no but saying yes also makes sense. The difference is, if a
121 module M that doesn't use Safe Haskell imports a module N that does, should all
122 the trusted package requirements be dropped since M didn't declare that it cares
123 about Safe Haskell (so -XSafe is more strongly associated with the module doing
124 the importing) or should it be done still since the author of the module N that
125 uses Safe Haskell said they cared (so -XSafe is more strongly associated with
126 the module that was compiled that used it).
127
128 Going with yes is a simpler semantics we think and harder for the user to stuff
129 up but it does mean that Safe Haskell will affect users who don't care about
130 Safe Haskell as they might grab a package from Cabal which uses safe haskell (say
131 network) and that packages imports -XTrustworthy modules from another package
132 (say bytestring), so requires that package is trusted. The user may now get
133 compilation errors in code that doesn't do anything with Safe Haskell simply
134 because they are using the network package. They will have to call 'ghc-pkg
135 trust network' to get everything working. Due to this invasive nature of going
136 with yes we have gone with no for now.
137 -}
138
139 -- | Process Import Decls
140 -- Do the non SOURCE ones first, so that we get a helpful warning for SOURCE
141 -- ones that are unnecessary
142 rnImports :: [LImportDecl RdrName]
143 -> RnM ([LImportDecl Name], GlobalRdrEnv, ImportAvails, AnyHpcUsage)
144 rnImports imports = do
145 this_mod <- getModule
146 let (source, ordinary) = partition is_source_import imports
147 is_source_import d = ideclSource (unLoc d)
148 stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary
149 stuff2 <- mapAndReportM (rnImportDecl this_mod) source
150 -- Safe Haskell: See Note [Tracking Trust Transitively]
151 let (decls, rdr_env, imp_avails, hpc_usage) = combine (stuff1 ++ stuff2)
152 return (decls, rdr_env, imp_avails, hpc_usage)
153
154 where
155 combine :: [(LImportDecl Name, GlobalRdrEnv, ImportAvails, AnyHpcUsage)]
156 -> ([LImportDecl Name], GlobalRdrEnv, ImportAvails, AnyHpcUsage)
157 combine = foldr plus ([], emptyGlobalRdrEnv, emptyImportAvails, False)
158
159 plus (decl, gbl_env1, imp_avails1,hpc_usage1)
160 (decls, gbl_env2, imp_avails2,hpc_usage2)
161 = ( decl:decls,
162 gbl_env1 `plusGlobalRdrEnv` gbl_env2,
163 imp_avails1 `plusImportAvails` imp_avails2,
164 hpc_usage1 || hpc_usage2 )
165
166 rnImportDecl :: Module -> LImportDecl RdrName
167 -> RnM (LImportDecl Name, GlobalRdrEnv, ImportAvails, AnyHpcUsage)
168 rnImportDecl this_mod
169 (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name, ideclPkgQual = mb_pkg
170 , ideclSource = want_boot, ideclSafe = mod_safe
171 , ideclQualified = qual_only, ideclImplicit = implicit
172 , ideclAs = as_mod, ideclHiding = imp_details }))
173 = setSrcSpan loc $ do
174
175 when (isJust mb_pkg) $ do
176 pkg_imports <- xoptM Opt_PackageImports
177 when (not pkg_imports) $ addErr packageImportErr
178
179 -- If there's an error in loadInterface, (e.g. interface
180 -- file not found) we get lots of spurious errors from 'filterImports'
181 let imp_mod_name = unLoc loc_imp_mod_name
182 doc = ppr imp_mod_name <+> ptext (sLit "is directly imported")
183
184 -- Check for self-import, which confuses the typechecker (Trac #9032)
185 -- ghc --make rejects self-import cycles already, but batch-mode may not
186 -- at least not until TcIface.tcHiBootIface, which is too late to avoid
187 -- typechecker crashes. ToDo: what about indirect self-import?
188 -- But 'import {-# SOURCE #-} M' is ok, even if a bit odd
189 when (not want_boot && imp_mod_name == moduleName this_mod)
190 (addErr (ptext (sLit "A module cannot import itself:") <+> ppr imp_mod_name))
191
192 -- Check for a missing import list (Opt_WarnMissingImportList also
193 -- checks for T(..) items but that is done in checkDodgyImport below)
194 case imp_details of
195 Just (False, _) -> return () -- Explicit import list
196 _ | implicit -> return () -- Do not bleat for implicit imports
197 | qual_only -> return ()
198 | otherwise -> whenWOptM Opt_WarnMissingImportList $
199 addWarn (missingImportListWarn imp_mod_name)
200
201 ifaces <- loadSrcInterface doc imp_mod_name want_boot mb_pkg
202
203 -- Compiler sanity check: if the import didn't say
204 -- {-# SOURCE #-} we should not get a hi-boot file
205 WARN( not want_boot && any mi_boot ifaces, ppr imp_mod_name ) do
206
207 -- Another sanity check: we should not get multiple interfaces
208 -- if we're looking for an hi-boot file
209 WARN( want_boot && length ifaces /= 1, ppr imp_mod_name ) do
210
211 -- Issue a user warning for a redundant {- SOURCE -} import
212 -- NB that we arrange to read all the ordinary imports before
213 -- any of the {- SOURCE -} imports.
214 --
215 -- in --make and GHCi, the compilation manager checks for this,
216 -- and indeed we shouldn't do it here because the existence of
217 -- the non-boot module depends on the compilation order, which
218 -- is not deterministic. The hs-boot test can show this up.
219 dflags <- getDynFlags
220 warnIf (want_boot && any (not.mi_boot) ifaces && isOneShot (ghcMode dflags))
221 (warnRedundantSourceImport imp_mod_name)
222 when (mod_safe && not (safeImportsOn dflags)) $
223 addErr (ptext (sLit "safe import can't be used as Safe Haskell isn't on!")
224 $+$ ptext (sLit $ "please enable Safe Haskell through either "
225 ++ "Safe, Trustworthy or Unsafe"))
226
227 let
228 qual_mod_name = as_mod `orElse` imp_mod_name
229 imp_spec = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,
230 is_dloc = loc, is_as = qual_mod_name }
231
232 -- filter the imports according to the import declaration
233 (new_imp_details, gres) <- filterImports ifaces imp_spec imp_details
234
235 let gbl_env = mkGlobalRdrEnv (filterOut from_this_mod gres)
236 from_this_mod gre = nameModule (gre_name gre) == this_mod
237
238 -- True <=> import M ()
239 import_all = case imp_details of
240 Just (is_hiding, L _ ls) -> not is_hiding && null ls
241 _ -> False
242
243 -- should the import be safe?
244 mod_safe' = mod_safe
245 || (not implicit && safeDirectImpsReq dflags)
246 || (implicit && safeImplicitImpsReq dflags)
247
248 let imports
249 = foldr plusImportAvails emptyImportAvails (map
250 (\iface ->
251 (calculateAvails dflags iface mod_safe' want_boot) {
252 imp_mods = unitModuleEnv (mi_module iface)
253 [(qual_mod_name, import_all, loc, mod_safe')] })
254 ifaces)
255
256 -- Complain if we import a deprecated module
257 whenWOptM Opt_WarnWarningsDeprecations (
258 forM_ ifaces $ \iface ->
259 case mi_warns iface of
260 WarnAll txt -> addWarn $ moduleWarn imp_mod_name txt
261 _ -> return ()
262 )
263
264 let new_imp_decl = L loc (decl { ideclSafe = mod_safe'
265 , ideclHiding = new_imp_details })
266
267 return (new_imp_decl, gbl_env, imports, any mi_hpc ifaces)
268
269 -- | Calculate the 'ImportAvails' induced by an import of a particular
270 -- interface, but without 'imp_mods'.
271 calculateAvails :: DynFlags
272 -> ModIface
273 -> IsSafeImport
274 -> IsBootInterface
275 -> ImportAvails
276 calculateAvails dflags iface mod_safe' want_boot =
277 let imp_mod = mi_module iface
278 orph_iface = mi_orphan iface
279 has_finsts = mi_finsts iface
280 deps = mi_deps iface
281 trust = getSafeMode $ mi_trust iface
282 trust_pkg = mi_trust_pkg iface
283
284 -- If the module exports anything defined in this module, just
285 -- ignore it. Reason: otherwise it looks as if there are two
286 -- local definition sites for the thing, and an error gets
287 -- reported. Easiest thing is just to filter them out up
288 -- front. This situation only arises if a module imports
289 -- itself, or another module that imported it. (Necessarily,
290 -- this invoves a loop.)
291 --
292 -- We do this *after* filterImports, so that if you say
293 -- module A where
294 -- import B( AType )
295 -- type AType = ...
296 --
297 -- module B( AType ) where
298 -- import {-# SOURCE #-} A( AType )
299 --
300 -- then you won't get a 'B does not export AType' message.
301
302
303 -- Compute new transitive dependencies
304
305 orphans | orph_iface = ASSERT( not (imp_mod `elem` dep_orphs deps) )
306 imp_mod : dep_orphs deps
307 | otherwise = dep_orphs deps
308
309 finsts | has_finsts = ASSERT( not (imp_mod `elem` dep_finsts deps) )
310 imp_mod : dep_finsts deps
311 | otherwise = dep_finsts deps
312
313 pkg = modulePackageKey (mi_module iface)
314
315 -- Does this import mean we now require our own pkg
316 -- to be trusted? See Note [Trust Own Package]
317 ptrust = trust == Sf_Trustworthy || trust_pkg
318
319 (dependent_mods, dependent_pkgs, pkg_trust_req)
320 | pkg == thisPackage dflags =
321 -- Imported module is from the home package
322 -- Take its dependent modules and add imp_mod itself
323 -- Take its dependent packages unchanged
324 --
325 -- NB: (dep_mods deps) might include a hi-boot file
326 -- for the module being compiled, CM. Do *not* filter
327 -- this out (as we used to), because when we've
328 -- finished dealing with the direct imports we want to
329 -- know if any of them depended on CM.hi-boot, in
330 -- which case we should do the hi-boot consistency
331 -- check. See LoadIface.loadHiBootInterface
332 ((moduleName imp_mod,want_boot):dep_mods deps,dep_pkgs deps,ptrust)
333
334 | otherwise =
335 -- Imported module is from another package
336 -- Dump the dependent modules
337 -- Add the package imp_mod comes from to the dependent packages
338 ASSERT2( not (pkg `elem` (map fst $ dep_pkgs deps))
339 , ppr pkg <+> ppr (dep_pkgs deps) )
340 ([], (pkg, False) : dep_pkgs deps, False)
341
342 in ImportAvails {
343 imp_mods = emptyModuleEnv, -- this gets filled in later
344 imp_orphs = orphans,
345 imp_finsts = finsts,
346 imp_dep_mods = mkModDeps dependent_mods,
347 imp_dep_pkgs = map fst $ dependent_pkgs,
348 -- Add in the imported modules trusted package
349 -- requirements. ONLY do this though if we import the
350 -- module as a safe import.
351 -- See Note [Tracking Trust Transitively]
352 -- and Note [Trust Transitive Property]
353 imp_trust_pkgs = if mod_safe'
354 then map fst $ filter snd dependent_pkgs
355 else [],
356 -- Do we require our own pkg to be trusted?
357 -- See Note [Trust Own Package]
358 imp_trust_own_pkg = pkg_trust_req
359 }
360
361
362 warnRedundantSourceImport :: ModuleName -> SDoc
363 warnRedundantSourceImport mod_name
364 = ptext (sLit "Unnecessary {-# SOURCE #-} in the import of module")
365 <+> quotes (ppr mod_name)
366
367 {-
368 ************************************************************************
369 * *
370 \subsection{importsFromLocalDecls}
371 * *
372 ************************************************************************
373
374 From the top-level declarations of this module produce
375 * the lexical environment
376 * the ImportAvails
377 created by its bindings.
378
379 Note [Top-level Names in Template Haskell decl quotes]
380 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
381 See also: Note [Interactively-bound Ids in GHCi] in HscTypes
382
383 Consider a Template Haskell declaration quotation like this:
384 module M where
385 f x = h [d| f = 3 |]
386 When renaming the declarations inside [d| ...|], we treat the
387 top level binders specially in two ways
388
389 1. We give them an Internal name, not (as usual) an External one.
390 Otherwise the NameCache gets confused by a second allocation of
391 M.f. (We used to invent a fake module ThFake to avoid this, but
392 that had other problems, notably in getting the correct answer for
393 nameIsLocalOrFrom in lookupFixity. So we now leave tcg_module
394 unaffected.)
395
396 2. We make them *shadow* the outer bindings. If we don't do that,
397 we'll get a complaint when extending the GlobalRdrEnv, saying that
398 there are two bindings for 'f'. There are several tricky points:
399
400 * This shadowing applies even if the binding for 'f' is in a
401 where-clause, and hence is in the *local* RdrEnv not the *global*
402 RdrEnv.
403
404 * The *qualified* name M.f from the enclosing module must certainly
405 still be available. So we don't nuke it entirely; we just make
406 it seem like qualified import.
407
408 * We only shadow *External* names (which come from the main module)
409 Do not shadow *Inernal* names because in the bracket
410 [d| class C a where f :: a
411 f = 4 |]
412 rnSrcDecls will first call extendGlobalRdrEnvRn with C[f] from the
413 class decl, and *separately* extend the envt with the value binding.
414
415 3. We find out whether we are inside a [d| ... |] by testing the TH
416 stage. This is a slight hack, because the stage field was really
417 meant for the type checker, and here we are not interested in the
418 fields of Brack, hence the error thunks in thRnBrack.
419 -}
420
421 extendGlobalRdrEnvRn :: [AvailInfo]
422 -> MiniFixityEnv
423 -> RnM (TcGblEnv, TcLclEnv)
424 -- Updates both the GlobalRdrEnv and the FixityEnv
425 -- We return a new TcLclEnv only because we might have to
426 -- delete some bindings from it;
427 -- see Note [Top-level Names in Template Haskell decl quotes]
428
429 extendGlobalRdrEnvRn avails new_fixities
430 = do { (gbl_env, lcl_env) <- getEnvs
431 ; stage <- getStage
432 ; isGHCi <- getIsGHCi
433 ; let rdr_env = tcg_rdr_env gbl_env
434 fix_env = tcg_fix_env gbl_env
435 th_bndrs = tcl_th_bndrs lcl_env
436 th_lvl = thLevel stage
437
438 -- Delete new_occs from global and local envs
439 -- If we are in a TemplateHaskell decl bracket,
440 -- we are going to shadow them
441 -- See Note [Top-level Names in Template Haskell decl quotes]
442 inBracket = isBrackStage stage
443 lcl_env_TH = lcl_env { tcl_rdr = delLocalRdrEnvList (tcl_rdr lcl_env) new_occs }
444
445 lcl_env2 | inBracket = lcl_env_TH
446 | otherwise = lcl_env
447
448 rdr_env2 = extendGlobalRdrEnv (isGHCi && not inBracket) rdr_env avails
449 -- Shadowing only applies for GHCi decls outside brackets
450 -- e.g. (Trac #4127a)
451 -- ghci> runQ [d| class C a where f :: a
452 -- f = True
453 -- instance C Int where f = 2 |]
454 -- We don't want the f=True to shadow the f class-op
455
456 lcl_env3 = lcl_env2 { tcl_th_bndrs = extendNameEnvList th_bndrs
457 [ (n, (TopLevel, th_lvl))
458 | n <- new_names ] }
459 fix_env' = foldl extend_fix_env fix_env new_names
460 dups = findLocalDupsRdrEnv rdr_env2 new_names
461
462 gbl_env' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env' }
463
464 ; traceRn (text "extendGlobalRdrEnvRn 1" <+> (ppr avails $$ (ppr dups)))
465 ; mapM_ (addDupDeclErr . map gre_name) dups
466
467 ; traceRn (text "extendGlobalRdrEnvRn 2" <+> (pprGlobalRdrEnv True rdr_env2))
468 ; return (gbl_env', lcl_env3) }
469 where
470 new_names = concatMap availNames avails
471 new_occs = map nameOccName new_names
472
473 -- If there is a fixity decl for the gre, add it to the fixity env
474 extend_fix_env fix_env name
475 | Just (L _ fi) <- lookupFsEnv new_fixities (occNameFS occ)
476 = extendNameEnv fix_env name (FixItem occ fi)
477 | otherwise
478 = fix_env
479 where
480 occ = nameOccName name
481
482 {-
483 @getLocalDeclBinders@ returns the names for an @HsDecl@. It's
484 used for source code.
485
486 *** See "THE NAMING STORY" in HsDecls ****
487 -}
488
489 getLocalNonValBinders :: MiniFixityEnv -> HsGroup RdrName
490 -> RnM ((TcGblEnv, TcLclEnv), NameSet)
491 -- Get all the top-level binders bound the group *except*
492 -- for value bindings, which are treated separately
493 -- Specifically we return AvailInfo for
494 -- type decls (incl constructors and record selectors)
495 -- class decls (including class ops)
496 -- associated types
497 -- foreign imports
498 -- (in hs-boot files) value signatures
499
500 getLocalNonValBinders fixity_env
501 (HsGroup { hs_valds = val_binds,
502 hs_tyclds = tycl_decls,
503 hs_instds = inst_decls,
504 hs_fords = foreign_decls })
505 = do { -- Process all type/class decls *except* family instances
506 ; tc_avails <- mapM new_tc (tyClGroupConcat tycl_decls)
507 ; traceRn (text "getLocalNonValBinders 1" <+> ppr tc_avails)
508 ; envs <- extendGlobalRdrEnvRn tc_avails fixity_env
509 ; setEnvs envs $ do {
510 -- Bring these things into scope first
511 -- See Note [Looking up family names in family instances]
512
513 -- Process all family instances
514 -- to bring new data constructors into scope
515 ; nti_avails <- concatMapM new_assoc inst_decls
516
517 -- Finish off with value binders:
518 -- foreign decls for an ordinary module
519 -- type sigs in case of a hs-boot file only
520 ; is_boot <- tcIsHsBootOrSig
521 ; let val_bndrs | is_boot = hs_boot_sig_bndrs
522 | otherwise = for_hs_bndrs
523 ; val_avails <- mapM new_simple val_bndrs
524
525 ; let avails = nti_avails ++ val_avails
526 new_bndrs = availsToNameSet avails `unionNameSet`
527 availsToNameSet tc_avails
528 ; traceRn (text "getLocalNonValBinders 2" <+> ppr avails)
529 ; envs <- extendGlobalRdrEnvRn avails fixity_env
530 ; return (envs, new_bndrs) } }
531 where
532 for_hs_bndrs :: [Located RdrName]
533 for_hs_bndrs = [ L decl_loc (unLoc nm)
534 | L decl_loc (ForeignImport nm _ _ _) <- foreign_decls]
535
536 -- In a hs-boot file, the value binders come from the
537 -- *signatures*, and there should be no foreign binders
538 hs_boot_sig_bndrs = [ L decl_loc (unLoc n)
539 | L decl_loc (TypeSig ns _ _) <- val_sigs, n <- ns]
540 ValBindsIn _ val_sigs = val_binds
541
542 -- the SrcSpan attached to the input should be the span of the
543 -- declaration, not just the name
544 new_simple :: Located RdrName -> RnM AvailInfo
545 new_simple rdr_name = do{ nm <- newTopSrcBinder rdr_name
546 ; return (Avail nm) }
547
548 new_tc tc_decl -- NOT for type/data instances
549 = do { let bndrs = hsLTyClDeclBinders tc_decl
550 ; names@(main_name : _) <- mapM newTopSrcBinder bndrs
551 ; return (AvailTC main_name names) }
552
553 new_assoc :: LInstDecl RdrName -> RnM [AvailInfo]
554 new_assoc (L _ (TyFamInstD {})) = return []
555 -- type instances don't bind new names
556
557 new_assoc (L _ (DataFamInstD { dfid_inst = d }))
558 = do { avail <- new_di Nothing d
559 ; return [avail] }
560 new_assoc (L _ (ClsInstD { cid_inst = ClsInstDecl
561 { cid_poly_ty = inst_ty
562 , cid_datafam_insts = adts } }))
563 | Just (_, _, L loc cls_rdr, _) <- splitLHsInstDeclTy_maybe inst_ty
564 = do { cls_nm <- setSrcSpan loc $ lookupGlobalOccRn cls_rdr
565 ; mapM (new_di (Just cls_nm) . unLoc) adts }
566 | otherwise
567 = return [] -- Do not crash on ill-formed instances
568 -- Eg instance !Show Int Trac #3811c
569
570 new_di :: Maybe Name -> DataFamInstDecl RdrName -> RnM AvailInfo
571 new_di mb_cls ti_decl
572 = do { main_name <- lookupFamInstName mb_cls (dfid_tycon ti_decl)
573 ; sub_names <- mapM newTopSrcBinder (hsDataFamInstBinders ti_decl)
574 ; return (AvailTC (unLoc main_name) sub_names) }
575 -- main_name is not bound here!
576
577 {-
578 Note [Looking up family names in family instances]
579 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
580 Consider
581
582 module M where
583 type family T a :: *
584 type instance M.T Int = Bool
585
586 We might think that we can simply use 'lookupOccRn' when processing the type
587 instance to look up 'M.T'. Alas, we can't! The type family declaration is in
588 the *same* HsGroup as the type instance declaration. Hence, as we are
589 currently collecting the binders declared in that HsGroup, these binders will
590 not have been added to the global environment yet.
591
592 Solution is simple: process the type family declarations first, extend
593 the environment, and then process the type instances.
594
595
596 ************************************************************************
597 * *
598 \subsection{Filtering imports}
599 * *
600 ************************************************************************
601
602 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
603 available, and filters it through the import spec (if any).
604
605 Note [Dealing with imports]
606 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
607 For import M( ies ), we take the mi_exports of M, and make
608 imp_occ_env :: OccEnv (Name, AvailInfo, Maybe Name)
609 One entry for each Name that M exports; the AvailInfo describes just
610 that Name.
611
612 The situation is made more complicated by associated types. E.g.
613 module M where
614 class C a where { data T a }
615 instance C Int where { data T Int = T1 | T2 }
616 instance C Bool where { data T Int = T3 }
617 Then M's export_avails are (recall the AvailTC invariant from Avails.hs)
618 C(C,T), T(T,T1,T2,T3)
619 Notice that T appears *twice*, once as a child and once as a parent.
620 From this we construct the imp_occ_env
621 C -> (C, C(C,T), Nothing
622 T -> (T, T(T,T1,T2,T3), Just C)
623 T1 -> (T1, T(T1,T2,T3), Nothing) -- similarly T2,T3
624
625 Note that the imp_occ_env will have entries for data constructors too,
626 although we never look up data constructors.
627 -}
628
629 filterImports
630 :: [ModIface]
631 -> ImpDeclSpec -- The span for the entire import decl
632 -> Maybe (Bool, Located [LIE RdrName]) -- Import spec; True => hiding
633 -> RnM (Maybe (Bool, Located [LIE Name]), -- Import spec w/ Names
634 [GlobalRdrElt]) -- Same again, but in GRE form
635 filterImports iface decl_spec Nothing
636 = return (Nothing, gresFromAvails prov (concatMap mi_exports iface))
637 where
638 prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
639
640
641 filterImports ifaces decl_spec (Just (want_hiding, L l import_items))
642 = do -- check for errors, convert RdrNames to Names
643 items1 <- mapM lookup_lie import_items
644
645 let items2 :: [(LIE Name, AvailInfo)]
646 items2 = concat items1
647 -- NB the AvailInfo may have duplicates, and several items
648 -- for the same parent; e.g N(x) and N(y)
649
650 names = availsToNameSet (map snd items2)
651 keep n = not (n `elemNameSet` names)
652 pruned_avails = filterAvails keep all_avails
653 hiding_prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
654
655 gres | want_hiding = gresFromAvails hiding_prov pruned_avails
656 | otherwise = concatMap (gresFromIE decl_spec) items2
657
658 return (Just (want_hiding, L l (map fst items2)), gres)
659 where
660 all_avails = concatMap mi_exports ifaces
661
662 -- See Note [Dealing with imports]
663 imp_occ_env :: OccEnv (Name, -- the name
664 AvailInfo, -- the export item providing the name
665 Maybe Name) -- the parent of associated types
666 imp_occ_env = mkOccEnv_C combine [ (nameOccName n, (n, a, Nothing))
667 | a <- all_avails, n <- availNames a]
668 where
669 -- See example in Note [Dealing with imports]
670 -- 'combine' is only called for associated types which appear twice
671 -- in the all_avails. In the example, we combine
672 -- T(T,T1,T2,T3) and C(C,T) to give (T, T(T,T1,T2,T3), Just C)
673 combine (name1, a1@(AvailTC p1 _), mp1)
674 (name2, a2@(AvailTC p2 _), mp2)
675 = ASSERT( name1 == name2 && isNothing mp1 && isNothing mp2 )
676 if p1 == name1 then (name1, a1, Just p2)
677 else (name1, a2, Just p1)
678 combine x y = pprPanic "filterImports/combine" (ppr x $$ ppr y)
679
680 lookup_name :: RdrName -> IELookupM (Name, AvailInfo, Maybe Name)
681 lookup_name rdr | isQual rdr = failLookupWith (QualImportError rdr)
682 | Just succ <- mb_success = return succ
683 | otherwise = failLookupWith BadImport
684 where
685 mb_success = lookupOccEnv imp_occ_env (rdrNameOcc rdr)
686
687 lookup_lie :: LIE RdrName -> TcRn [(LIE Name, AvailInfo)]
688 lookup_lie (L loc ieRdr)
689 = do (stuff, warns) <- setSrcSpan loc $
690 liftM (fromMaybe ([],[])) $
691 run_lookup (lookup_ie ieRdr)
692 mapM_ emit_warning warns
693 return [ (L loc ie, avail) | (ie,avail) <- stuff ]
694 where
695 -- Warn when importing T(..) if T was exported abstractly
696 emit_warning (DodgyImport n) = whenWOptM Opt_WarnDodgyImports $
697 addWarn (dodgyImportWarn n)
698 emit_warning MissingImportList = whenWOptM Opt_WarnMissingImportList $
699 addWarn (missingImportListItem ieRdr)
700 emit_warning BadImportW = whenWOptM Opt_WarnDodgyImports $
701 addWarn (lookup_err_msg BadImport)
702
703 run_lookup :: IELookupM a -> TcRn (Maybe a)
704 run_lookup m = case m of
705 Failed err -> addErr (lookup_err_msg err) >> return Nothing
706 Succeeded a -> return (Just a)
707
708 lookup_err_msg err = case err of
709 BadImport -> badImportItemErr (any mi_boot ifaces) decl_spec
710 ieRdr all_avails
711 IllegalImport -> illegalImportItemErr
712 QualImportError rdr -> qualImportItemErr rdr
713
714 -- For each import item, we convert its RdrNames to Names,
715 -- and at the same time construct an AvailInfo corresponding
716 -- to what is actually imported by this item.
717 -- Returns Nothing on error.
718 -- We return a list here, because in the case of an import
719 -- item like C, if we are hiding, then C refers to *both* a
720 -- type/class and a data constructor. Moreover, when we import
721 -- data constructors of an associated family, we need separate
722 -- AvailInfos for the data constructors and the family (as they have
723 -- different parents). See Note [Dealing with imports]
724 lookup_ie :: IE RdrName -> IELookupM ([(IE Name, AvailInfo)], [IELookupWarning])
725 lookup_ie ie = handle_bad_import $ do
726 case ie of
727 IEVar (L l n) -> do
728 (name, avail, _) <- lookup_name n
729 return ([(IEVar (L l name), trimAvail avail name)], [])
730
731 IEThingAll (L l tc) -> do
732 (name, avail@(AvailTC name2 subs), mb_parent) <- lookup_name tc
733 let warns | null (drop 1 subs) = [DodgyImport tc]
734 | not (is_qual decl_spec) = [MissingImportList]
735 | otherwise = []
736 case mb_parent of
737 -- non-associated ty/cls
738 Nothing -> return ([(IEThingAll (L l name), avail)], warns)
739 -- associated ty
740 Just parent -> return ([(IEThingAll (L l name),
741 AvailTC name2 (subs \\ [name])),
742 (IEThingAll (L l name),
743 AvailTC parent [name])],
744 warns)
745
746 IEThingAbs tc
747 | want_hiding -- hiding ( C )
748 -- Here the 'C' can be a data constructor
749 -- *or* a type/class, or even both
750 -> let tc_name = lookup_name tc
751 dc_name = lookup_name (setRdrNameSpace tc srcDataName)
752 in
753 case catIELookupM [ tc_name, dc_name ] of
754 [] -> failLookupWith BadImport
755 names -> return ([mkIEThingAbs name | name <- names], [])
756 | otherwise
757 -> do nameAvail <- lookup_name tc
758 return ([mkIEThingAbs nameAvail], [])
759
760 IEThingWith (L l rdr_tc) rdr_ns -> do
761 (name, AvailTC _ ns, mb_parent) <- lookup_name rdr_tc
762
763 -- Look up the children in the sub-names of the parent
764 let subnames = case ns of -- The tc is first in ns,
765 [] -> [] -- if it is there at all
766 -- See the AvailTC Invariant in Avail.hs
767 (n1:ns1) | n1 == name -> ns1
768 | otherwise -> ns
769 mb_children = lookupChildren subnames rdr_ns
770
771 children <- if any isNothing mb_children
772 then failLookupWith BadImport
773 else return (catMaybes mb_children)
774
775 case mb_parent of
776 -- non-associated ty/cls
777 Nothing -> return ([(IEThingWith (L l name) children,
778 AvailTC name (name:map unLoc children))],
779 [])
780 -- associated ty
781 Just parent -> return ([(IEThingWith (L l name) children,
782 AvailTC name (map unLoc children)),
783 (IEThingWith (L l name) children,
784 AvailTC parent [name])],
785 [])
786
787 _other -> failLookupWith IllegalImport
788 -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed
789 -- all errors.
790
791 where
792 mkIEThingAbs (n, av, Nothing ) = (IEThingAbs n, trimAvail av n)
793 mkIEThingAbs (n, _, Just parent) = (IEThingAbs n, AvailTC parent [n])
794
795 handle_bad_import m = catchIELookup m $ \err -> case err of
796 BadImport | want_hiding -> return ([], [BadImportW])
797 _ -> failLookupWith err
798
799 type IELookupM = MaybeErr IELookupError
800
801 data IELookupWarning
802 = BadImportW
803 | MissingImportList
804 | DodgyImport RdrName
805 -- NB. use the RdrName for reporting a "dodgy" import
806
807 data IELookupError
808 = QualImportError RdrName
809 | BadImport
810 | IllegalImport
811
812 failLookupWith :: IELookupError -> IELookupM a
813 failLookupWith err = Failed err
814
815 catchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a
816 catchIELookup m h = case m of
817 Succeeded r -> return r
818 Failed err -> h err
819
820 catIELookupM :: [IELookupM a] -> [a]
821 catIELookupM ms = [ a | Succeeded a <- ms ]
822
823 {-
824 ************************************************************************
825 * *
826 \subsection{Import/Export Utils}
827 * *
828 ************************************************************************
829 -}
830
831 greExportAvail :: GlobalRdrElt -> AvailInfo
832 greExportAvail gre
833 = case gre_par gre of
834 ParentIs p -> AvailTC p [me]
835 NoParent | isTyConName me -> AvailTC me [me]
836 | otherwise -> Avail me
837 where
838 me = gre_name gre
839
840 plusAvail :: AvailInfo -> AvailInfo -> AvailInfo
841 plusAvail a1 a2
842 | debugIsOn && availName a1 /= availName a2
843 = pprPanic "RnEnv.plusAvail names differ" (hsep [ppr a1,ppr a2])
844 plusAvail a1@(Avail {}) (Avail {}) = a1
845 plusAvail (AvailTC _ []) a2@(AvailTC {}) = a2
846 plusAvail a1@(AvailTC {}) (AvailTC _ []) = a1
847 plusAvail (AvailTC n1 (s1:ss1)) (AvailTC n2 (s2:ss2))
848 = case (n1==s1, n2==s2) of -- Maintain invariant the parent is first
849 (True,True) -> AvailTC n1 (s1 : (ss1 `unionLists` ss2))
850 (True,False) -> AvailTC n1 (s1 : (ss1 `unionLists` (s2:ss2)))
851 (False,True) -> AvailTC n1 (s2 : ((s1:ss1) `unionLists` ss2))
852 (False,False) -> AvailTC n1 ((s1:ss1) `unionLists` (s2:ss2))
853 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
854
855 trimAvail :: AvailInfo -> Name -> AvailInfo
856 trimAvail (Avail n) _ = Avail n
857 trimAvail (AvailTC n ns) m = ASSERT( m `elem` ns) AvailTC n [m]
858
859 -- | filters 'AvailInfo's by the given predicate
860 filterAvails :: (Name -> Bool) -> [AvailInfo] -> [AvailInfo]
861 filterAvails keep avails = foldr (filterAvail keep) [] avails
862
863 -- | filters an 'AvailInfo' by the given predicate
864 filterAvail :: (Name -> Bool) -> AvailInfo -> [AvailInfo] -> [AvailInfo]
865 filterAvail keep ie rest =
866 case ie of
867 Avail n | keep n -> ie : rest
868 | otherwise -> rest
869 AvailTC tc ns ->
870 let left = filter keep ns in
871 if null left then rest else AvailTC tc left : rest
872
873 -- | Given an import\/export spec, construct the appropriate 'GlobalRdrElt's.
874 gresFromIE :: ImpDeclSpec -> (LIE Name, AvailInfo) -> [GlobalRdrElt]
875 gresFromIE decl_spec (L loc ie, avail)
876 = gresFromAvail prov_fn avail
877 where
878 is_explicit = case ie of
879 IEThingAll (L _ name) -> \n -> n == name
880 _ -> \_ -> True
881 prov_fn name = Imported [imp_spec]
882 where
883 imp_spec = ImpSpec { is_decl = decl_spec, is_item = item_spec }
884 item_spec = ImpSome { is_explicit = is_explicit name, is_iloc = loc }
885
886 mkChildEnv :: [GlobalRdrElt] -> NameEnv [Name]
887 mkChildEnv gres = foldr add emptyNameEnv gres
888 where
889 add (GRE { gre_name = n, gre_par = ParentIs p }) env = extendNameEnv_Acc (:) singleton env p n
890 add _ env = env
891
892 findChildren :: NameEnv [Name] -> Name -> [Name]
893 findChildren env n = lookupNameEnv env n `orElse` []
894
895 lookupChildren :: [Name] -> [Located RdrName] -> [Maybe (Located Name)]
896 -- (lookupChildren all_kids rdr_items) maps each rdr_item to its
897 -- corresponding Name all_kids, if the former exists
898 -- The matching is done by FastString, not OccName, so that
899 -- Cls( meth, AssocTy )
900 -- will correctly find AssocTy among the all_kids of Cls, even though
901 -- the RdrName for AssocTy may have a (bogus) DataName namespace
902 -- (Really the rdr_items should be FastStrings in the first place.)
903 lookupChildren all_kids rdr_items
904 -- = map (lookupFsEnv kid_env . occNameFS . rdrNameOcc) rdr_items
905 = map doOne rdr_items
906 where
907 doOne (L l r) = case (lookupFsEnv kid_env . occNameFS . rdrNameOcc) r of
908 Just n -> Just (L l n)
909 Nothing -> Nothing
910
911 kid_env = mkFsEnv [(occNameFS (nameOccName n), n) | n <- all_kids]
912
913 -- | Combines 'AvailInfo's from the same family
914 -- 'avails' may have several items with the same availName
915 -- E.g import Ix( Ix(..), index )
916 -- will give Ix(Ix,index,range) and Ix(index)
917 -- We want to combine these; addAvail does that
918 nubAvails :: [AvailInfo] -> [AvailInfo]
919 nubAvails avails = nameEnvElts (foldl add emptyNameEnv avails)
920 where
921 add env avail = extendNameEnv_C plusAvail env (availName avail) avail
922
923 {-
924 ************************************************************************
925 * *
926 \subsection{Export list processing}
927 * *
928 ************************************************************************
929
930 Processing the export list.
931
932 You might think that we should record things that appear in the export
933 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
934 wrong. We do check (here) that they are in scope, but there is no
935 need to slurp in their actual declaration (which is what
936 @addOccurrenceName@ forces).
937
938 Indeed, doing so would big trouble when compiling @PrelBase@, because
939 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
940 @ConcBase.StateAndSynchVar#@, and so on...
941
942 Note [Exports of data families]
943 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
944 Suppose you see (Trac #5306)
945 module M where
946 import X( F )
947 data instance F Int = FInt
948 What does M export? AvailTC F [FInt]
949 or AvailTC F [F,FInt]?
950 The former is strictly right because F isn't defined in this module.
951 But then you can never do an explicit import of M, thus
952 import M( F( FInt ) )
953 because F isn't exported by M. Nor can you import FInt alone from here
954 import M( FInt )
955 because we don't have syntax to support that. (It looks like an import of
956 the type FInt.)
957
958 At one point I implemented a compromise:
959 * When constructing exports with no export list, or with module M(
960 module M ), we add the parent to the exports as well.
961 * But not when you see module M( f ), even if f is a
962 class method with a parent.
963 * Nor when you see module M( module N ), with N /= M.
964
965 But the compromise seemed too much of a hack, so we backed it out.
966 You just have to use an explicit export list:
967 module M( F(..) ) where ...
968 -}
969
970 type ExportAccum -- The type of the accumulating parameter of
971 -- the main worker function in rnExports
972 = ([LIE Name], -- Export items with Names
973 ExportOccMap, -- Tracks exported occurrence names
974 [AvailInfo]) -- The accumulated exported stuff
975 -- Not nub'd!
976
977 emptyExportAccum :: ExportAccum
978 emptyExportAccum = ([], emptyOccEnv, [])
979
980 type ExportOccMap = OccEnv (Name, IE RdrName)
981 -- Tracks what a particular exported OccName
982 -- in an export list refers to, and which item
983 -- it came from. It's illegal to export two distinct things
984 -- that have the same occurrence name
985
986 rnExports :: Bool -- False => no 'module M(..) where' header at all
987 -> Maybe (Located [LIE RdrName]) -- Nothing => no explicit export list
988 -> TcGblEnv
989 -> RnM TcGblEnv
990
991 -- Complains if two distinct exports have same OccName
992 -- Warns about identical exports.
993 -- Complains about exports items not in scope
994
995 rnExports explicit_mod exports
996 tcg_env@(TcGblEnv { tcg_mod = this_mod,
997 tcg_rdr_env = rdr_env,
998 tcg_imports = imports })
999 = unsetWOptM Opt_WarnWarningsDeprecations $
1000 -- Do not report deprecations arising from the export
1001 -- list, to avoid bleating about re-exporting a deprecated
1002 -- thing (especially via 'module Foo' export item)
1003 do {
1004 -- If the module header is omitted altogether, then behave
1005 -- as if the user had written "module Main(main) where..."
1006 -- EXCEPT in interactive mode, when we behave as if he had
1007 -- written "module Main where ..."
1008 -- Reason: don't want to complain about 'main' not in scope
1009 -- in interactive mode
1010 ; dflags <- getDynFlags
1011 ; let real_exports
1012 | explicit_mod = exports
1013 | ghcLink dflags == LinkInMemory = Nothing
1014 | otherwise
1015 = Just (noLoc [noLoc (IEVar (noLoc main_RDR_Unqual))])
1016 -- ToDo: the 'noLoc' here is unhelpful if 'main'
1017 -- turns out to be out of scope
1018
1019 ; (rn_exports, avails) <- exports_from_avail real_exports rdr_env imports this_mod
1020 ; let final_avails = nubAvails avails -- Combine families
1021
1022 ; traceRn (text "rnExports: Exports:" <+> ppr final_avails)
1023
1024 ; return (tcg_env { tcg_exports = final_avails,
1025 tcg_rn_exports = case tcg_rn_exports tcg_env of
1026 Nothing -> Nothing
1027 Just _ -> rn_exports,
1028 tcg_dus = tcg_dus tcg_env `plusDU`
1029 usesOnly (availsToNameSet final_avails) }) }
1030
1031 exports_from_avail :: Maybe (Located [LIE RdrName])
1032 -- Nothing => no explicit export list
1033 -> GlobalRdrEnv
1034 -> ImportAvails
1035 -> Module
1036 -> RnM (Maybe [LIE Name], [AvailInfo])
1037
1038 exports_from_avail Nothing rdr_env _imports _this_mod
1039 = -- The same as (module M) where M is the current module name,
1040 -- so that's how we handle it.
1041 let
1042 avails = [ greExportAvail gre
1043 | gre <- globalRdrEnvElts rdr_env
1044 , isLocalGRE gre ]
1045 in
1046 return (Nothing, avails)
1047
1048 exports_from_avail (Just (L _ rdr_items)) rdr_env imports this_mod
1049 = do (ie_names, _, exports) <- foldlM do_litem emptyExportAccum rdr_items
1050 return (Just ie_names, exports)
1051 where
1052 do_litem :: ExportAccum -> LIE RdrName -> RnM ExportAccum
1053 do_litem acc lie = setSrcSpan (getLoc lie) (exports_from_item acc lie)
1054
1055 kids_env :: NameEnv [Name] -- Maps a parent to its in-scope children
1056 kids_env = mkChildEnv (globalRdrEnvElts rdr_env)
1057
1058 imported_modules = [ qual_name
1059 | xs <- moduleEnvElts $ imp_mods imports,
1060 (qual_name, _, _, _) <- xs ]
1061
1062 exports_from_item :: ExportAccum -> LIE RdrName -> RnM ExportAccum
1063 exports_from_item acc@(ie_names, occs, exports)
1064 (L loc (IEModuleContents (L lm mod)))
1065 | let earlier_mods = [ mod
1066 | (L _ (IEModuleContents (L _ mod))) <- ie_names ]
1067 , mod `elem` earlier_mods -- Duplicate export of M
1068 = do { warn_dup_exports <- woptM Opt_WarnDuplicateExports ;
1069 warnIf warn_dup_exports (dupModuleExport mod) ;
1070 return acc }
1071
1072 | otherwise
1073 = do { implicit_prelude <- xoptM Opt_ImplicitPrelude
1074 ; warnDodgyExports <- woptM Opt_WarnDodgyExports
1075 ; let { exportValid = (mod `elem` imported_modules)
1076 || (moduleName this_mod == mod)
1077 ; gres = filter (isModuleExported implicit_prelude mod)
1078 (globalRdrEnvElts rdr_env)
1079 ; new_exports = map greExportAvail gres
1080 ; names = map gre_name gres }
1081
1082 ; checkErr exportValid (moduleNotImported mod)
1083 ; warnIf (warnDodgyExports && exportValid && null names)
1084 (nullModuleExport mod)
1085
1086 ; addUsedRdrNames (concat [ [mkRdrQual mod occ, mkRdrUnqual occ]
1087 | occ <- map nameOccName names ])
1088 -- The qualified and unqualified version of all of
1089 -- these names are, in effect, used by this export
1090
1091 ; occs' <- check_occs (IEModuleContents (noLoc mod)) occs names
1092 -- This check_occs not only finds conflicts
1093 -- between this item and others, but also
1094 -- internally within this item. That is, if
1095 -- 'M.x' is in scope in several ways, we'll have
1096 -- several members of mod_avails with the same
1097 -- OccName.
1098 ; traceRn (vcat [ text "export mod" <+> ppr mod
1099 , ppr new_exports ])
1100 ; return (L loc (IEModuleContents (L lm mod)) : ie_names,
1101 occs', new_exports ++ exports) }
1102
1103 exports_from_item acc@(lie_names, occs, exports) (L loc ie)
1104 | isDoc ie
1105 = do new_ie <- lookup_doc_ie ie
1106 return (L loc new_ie : lie_names, occs, exports)
1107
1108 | otherwise
1109 = do (new_ie, avail) <- lookup_ie ie
1110 if isUnboundName (ieName new_ie)
1111 then return acc -- Avoid error cascade
1112 else do
1113
1114 occs' <- check_occs ie occs (availNames avail)
1115
1116 return (L loc new_ie : lie_names, occs', avail : exports)
1117
1118 -------------
1119 lookup_ie :: IE RdrName -> RnM (IE Name, AvailInfo)
1120 lookup_ie (IEVar (L l rdr))
1121 = do gre <- lookupGreRn rdr
1122 return (IEVar (L l (gre_name gre)), greExportAvail gre)
1123
1124 lookup_ie (IEThingAbs rdr)
1125 = do gre <- lookupGreRn rdr
1126 let name = gre_name gre
1127 avail = greExportAvail gre
1128 return (IEThingAbs name, avail)
1129
1130 lookup_ie ie@(IEThingAll (L l rdr))
1131 = do name <- lookupGlobalOccRn rdr
1132 let kids = findChildren kids_env name
1133 addUsedKids rdr kids
1134 warnDodgyExports <- woptM Opt_WarnDodgyExports
1135 when (null kids) $
1136 if isTyConName name
1137 then when warnDodgyExports $ addWarn (dodgyExportWarn name)
1138 else -- This occurs when you export T(..), but
1139 -- only import T abstractly, or T is a synonym.
1140 addErr (exportItemErr ie)
1141
1142 return (IEThingAll (L l name), AvailTC name (name:kids))
1143
1144 lookup_ie ie@(IEThingWith (L l rdr) sub_rdrs)
1145 = do name <- lookupGlobalOccRn rdr
1146 if isUnboundName name
1147 then return (IEThingWith (L l name) [], AvailTC name [name])
1148 else do
1149 let mb_names = lookupChildren (findChildren kids_env name) sub_rdrs
1150 if any isNothing mb_names
1151 then do addErr (exportItemErr ie)
1152 return (IEThingWith (L l name) [], AvailTC name [name])
1153 else do let names = catMaybes mb_names
1154 addUsedKids rdr (map unLoc names)
1155 return (IEThingWith (L l name) names
1156 , AvailTC name (name:map unLoc names))
1157
1158 lookup_ie _ = panic "lookup_ie" -- Other cases covered earlier
1159
1160 -------------
1161 lookup_doc_ie :: IE RdrName -> RnM (IE Name)
1162 lookup_doc_ie (IEGroup lev doc) = do rn_doc <- rnHsDoc doc
1163 return (IEGroup lev rn_doc)
1164 lookup_doc_ie (IEDoc doc) = do rn_doc <- rnHsDoc doc
1165 return (IEDoc rn_doc)
1166 lookup_doc_ie (IEDocNamed str) = return (IEDocNamed str)
1167 lookup_doc_ie _ = panic "lookup_doc_ie" -- Other cases covered earlier
1168
1169 -- In an export item M.T(A,B,C), we want to treat the uses of
1170 -- A,B,C as if they were M.A, M.B, M.C
1171 addUsedKids parent_rdr kid_names
1172 = addUsedRdrNames $ map (mk_kid_rdr . nameOccName) kid_names
1173 where
1174 mk_kid_rdr = case isQual_maybe parent_rdr of
1175 Nothing -> mkRdrUnqual
1176 Just (modName, _) -> mkRdrQual modName
1177
1178 isDoc :: IE RdrName -> Bool
1179 isDoc (IEDoc _) = True
1180 isDoc (IEDocNamed _) = True
1181 isDoc (IEGroup _ _) = True
1182 isDoc _ = False
1183
1184 -------------------------------
1185 isModuleExported :: Bool -> ModuleName -> GlobalRdrElt -> Bool
1186 -- True if the thing is in scope *both* unqualified, *and* with qualifier M
1187 isModuleExported implicit_prelude mod (GRE { gre_name = name, gre_prov = prov })
1188 | implicit_prelude && isBuiltInSyntax name = False
1189 -- Optimisation: filter out names for built-in syntax
1190 -- They just clutter up the environment (esp tuples), and the parser
1191 -- will generate Exact RdrNames for them, so the cluttered
1192 -- envt is no use. To avoid doing this filter all the time,
1193 -- we use -XNoImplicitPrelude as a clue that the filter is
1194 -- worth while. Really, it's only useful for GHC.Base and GHC.Tuple.
1195 --
1196 -- It's worth doing because it makes the environment smaller for
1197 -- every module that imports the Prelude
1198 | otherwise
1199 = case prov of
1200 LocalDef | Just name_mod <- nameModule_maybe name
1201 -> moduleName name_mod == mod
1202 | otherwise -> False
1203 Imported is -> any unQualSpecOK is && any (qualSpecOK mod) is
1204
1205 -------------------------------
1206 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
1207 check_occs ie occs names -- 'names' are the entities specifed by 'ie'
1208 = foldlM check occs names
1209 where
1210 check occs name
1211 = case lookupOccEnv occs name_occ of
1212 Nothing -> return (extendOccEnv occs name_occ (name, ie))
1213
1214 Just (name', ie')
1215 | name == name' -- Duplicate export
1216 -- But we don't want to warn if the same thing is exported
1217 -- by two different module exports. See ticket #4478.
1218 -> do unless (dupExport_ok name ie ie') $ do
1219 warn_dup_exports <- woptM Opt_WarnDuplicateExports
1220 warnIf warn_dup_exports (dupExportWarn name_occ ie ie')
1221 return occs
1222
1223 | otherwise -- Same occ name but different names: an error
1224 -> do { global_env <- getGlobalRdrEnv ;
1225 addErr (exportClashErr global_env name' name ie' ie) ;
1226 return occs }
1227 where
1228 name_occ = nameOccName name
1229
1230
1231 dupExport_ok :: Name -> IE RdrName -> IE RdrName -> Bool
1232 -- The Name is exported by both IEs. Is that ok?
1233 -- "No" iff the name is mentioned explicitly in both IEs
1234 -- or one of the IEs mentions the name *alone*
1235 -- "Yes" otherwise
1236 --
1237 -- Examples of "no": module M( f, f )
1238 -- module M( fmap, Functor(..) )
1239 -- module M( module Data.List, head )
1240 --
1241 -- Example of "yes"
1242 -- module M( module A, module B ) where
1243 -- import A( f )
1244 -- import B( f )
1245 --
1246 -- Example of "yes" (Trac #2436)
1247 -- module M( C(..), T(..) ) where
1248 -- class C a where { data T a }
1249 -- instace C Int where { data T Int = TInt }
1250 --
1251 -- Example of "yes" (Trac #2436)
1252 -- module Foo ( T ) where
1253 -- data family T a
1254 -- module Bar ( T(..), module Foo ) where
1255 -- import Foo
1256 -- data instance T Int = TInt
1257
1258 dupExport_ok n ie1 ie2
1259 = not ( single ie1 || single ie2
1260 || (explicit_in ie1 && explicit_in ie2) )
1261 where
1262 explicit_in (IEModuleContents _) = False -- module M
1263 explicit_in (IEThingAll r) = nameOccName n == rdrNameOcc (unLoc r) -- T(..)
1264 explicit_in _ = True
1265
1266 single (IEVar {}) = True
1267 single (IEThingAbs {}) = True
1268 single _ = False
1269
1270 {-
1271 *********************************************************
1272 * *
1273 \subsection{Unused names}
1274 * *
1275 *********************************************************
1276 -}
1277
1278 reportUnusedNames :: Maybe (Located [LIE RdrName]) -- Export list
1279 -> TcGblEnv -> RnM ()
1280 reportUnusedNames _export_decls gbl_env
1281 = do { traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env)))
1282 ; warnUnusedImportDecls gbl_env
1283 ; warnUnusedTopBinds unused_locals }
1284 where
1285 used_names :: NameSet
1286 used_names = findUses (tcg_dus gbl_env) emptyNameSet
1287 -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
1288 -- Hence findUses
1289
1290 -- Collect the defined names from the in-scope environment
1291 defined_names :: [GlobalRdrElt]
1292 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
1293
1294 -- Note that defined_and_used, defined_but_not_used
1295 -- are both [GRE]; that's why we need defined_and_used
1296 -- rather than just used_names
1297 _defined_and_used, defined_but_not_used :: [GlobalRdrElt]
1298 (_defined_and_used, defined_but_not_used)
1299 = partition (gre_is_used used_names) defined_names
1300
1301 kids_env = mkChildEnv defined_names
1302 -- This is done in mkExports too; duplicated work
1303
1304 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
1305 gre_is_used used_names (GRE {gre_name = name})
1306 = name `elemNameSet` used_names
1307 || any (`elemNameSet` used_names) (findChildren kids_env name)
1308 -- A use of C implies a use of T,
1309 -- if C was brought into scope by T(..) or T(C)
1310
1311 -- Filter out the ones that are
1312 -- (a) defined in this module, and
1313 -- (b) not defined by a 'deriving' clause
1314 -- The latter have an Internal Name, so we can filter them out easily
1315 unused_locals :: [GlobalRdrElt]
1316 unused_locals = filter is_unused_local defined_but_not_used
1317 is_unused_local :: GlobalRdrElt -> Bool
1318 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
1319
1320 {-
1321 *********************************************************
1322 * *
1323 \subsection{Unused imports}
1324 * *
1325 *********************************************************
1326
1327 This code finds which import declarations are unused. The
1328 specification and implementation notes are here:
1329 http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/UnusedImports
1330 -}
1331
1332 type ImportDeclUsage
1333 = ( LImportDecl Name -- The import declaration
1334 , [AvailInfo] -- What *is* used (normalised)
1335 , [Name] ) -- What is imported but *not* used
1336
1337 warnUnusedImportDecls :: TcGblEnv -> RnM ()
1338 warnUnusedImportDecls gbl_env
1339 = do { uses <- readMutVar (tcg_used_rdrnames gbl_env)
1340 ; let user_imports = filterOut (ideclImplicit . unLoc) (tcg_rn_imports gbl_env)
1341 -- This whole function deals only with *user* imports
1342 -- both for warning about unnecessary ones, and for
1343 -- deciding the minimal ones
1344 rdr_env = tcg_rdr_env gbl_env
1345
1346 ; let usage :: [ImportDeclUsage]
1347 usage = findImportUsage user_imports rdr_env (Set.elems uses)
1348
1349 ; traceRn (vcat [ ptext (sLit "Uses:") <+> ppr (Set.elems uses)
1350 , ptext (sLit "Import usage") <+> ppr usage])
1351 ; whenWOptM Opt_WarnUnusedImports $
1352 mapM_ warnUnusedImport usage
1353
1354 ; whenGOptM Opt_D_dump_minimal_imports $
1355 printMinimalImports usage }
1356
1357 {-
1358 Note [The ImportMap]
1359 ~~~~~~~~~~~~~~~~~~~~
1360 The ImportMap is a short-lived intermediate data struture records, for
1361 each import declaration, what stuff brought into scope by that
1362 declaration is actually used in the module.
1363
1364 The SrcLoc is the location of the END of a particular 'import'
1365 declaration. Why *END*? Because we don't want to get confused
1366 by the implicit Prelude import. Consider (Trac #7476) the module
1367 import Foo( foo )
1368 main = print foo
1369 There is an implicit 'import Prelude(print)', and it gets a SrcSpan
1370 of line 1:1 (just the point, not a span). If we use the *START* of
1371 the SrcSpan to identify the import decl, we'll confuse the implicit
1372 import Prelude with the explicit 'import Foo'. So we use the END.
1373 It's just a cheap hack; we could equally well use the Span too.
1374
1375 The AvailInfos are the things imported from that decl (just a list,
1376 not normalised).
1377 -}
1378
1379 type ImportMap = Map SrcLoc [AvailInfo] -- See [The ImportMap]
1380
1381 findImportUsage :: [LImportDecl Name]
1382 -> GlobalRdrEnv
1383 -> [RdrName]
1384 -> [ImportDeclUsage]
1385
1386 findImportUsage imports rdr_env rdrs
1387 = map unused_decl imports
1388 where
1389 import_usage :: ImportMap
1390 import_usage = foldr (extendImportMap rdr_env) Map.empty rdrs
1391
1392 unused_decl decl@(L loc (ImportDecl { ideclHiding = imps }))
1393 = (decl, nubAvails used_avails, nameSetElems unused_imps)
1394 where
1395 used_avails = Map.lookup (srcSpanEnd loc) import_usage `orElse` []
1396 -- srcSpanEnd: see Note [The ImportMap]
1397 used_names = availsToNameSet used_avails
1398 used_parents = mkNameSet [n | AvailTC n _ <- used_avails]
1399
1400 unused_imps -- Not trivial; see eg Trac #7454
1401 = case imps of
1402 Just (False, L _ imp_ies) ->
1403 foldr (add_unused . unLoc) emptyNameSet imp_ies
1404 _other -> emptyNameSet -- No explicit import list => no unused-name list
1405
1406 add_unused :: IE Name -> NameSet -> NameSet
1407 add_unused (IEVar (L _ n)) acc = add_unused_name n acc
1408 add_unused (IEThingAbs n) acc = add_unused_name n acc
1409 add_unused (IEThingAll (L _ n)) acc = add_unused_all n acc
1410 add_unused (IEThingWith (L _ p) ns) acc
1411 = add_unused_with p (map unLoc ns) acc
1412 add_unused _ acc = acc
1413
1414 add_unused_name n acc
1415 | n `elemNameSet` used_names = acc
1416 | otherwise = acc `extendNameSet` n
1417 add_unused_all n acc
1418 | n `elemNameSet` used_names = acc
1419 | n `elemNameSet` used_parents = acc
1420 | otherwise = acc `extendNameSet` n
1421 add_unused_with p ns acc
1422 | all (`elemNameSet` acc1) ns = add_unused_name p acc1
1423 | otherwise = acc1
1424 where
1425 acc1 = foldr add_unused_name acc ns
1426 -- If you use 'signum' from Num, then the user may well have
1427 -- imported Num(signum). We don't want to complain that
1428 -- Num is not itself mentioned. Hence the two cases in add_unused_with.
1429
1430
1431 extendImportMap :: GlobalRdrEnv -> RdrName -> ImportMap -> ImportMap
1432 -- For a used RdrName, find all the import decls that brought
1433 -- it into scope; choose one of them (bestImport), and record
1434 -- the RdrName in that import decl's entry in the ImportMap
1435 extendImportMap rdr_env rdr imp_map
1436 | [gre] <- lookupGRE_RdrName rdr rdr_env
1437 , Imported imps <- gre_prov gre
1438 = add_imp gre (bestImport imps) imp_map
1439 | otherwise
1440 = imp_map
1441 where
1442 add_imp :: GlobalRdrElt -> ImportSpec -> ImportMap -> ImportMap
1443 add_imp gre (ImpSpec { is_decl = imp_decl_spec }) imp_map
1444 = Map.insertWith add decl_loc [avail] imp_map
1445 where
1446 add _ avails = avail : avails -- add is really just a specialised (++)
1447 decl_loc = srcSpanEnd (is_dloc imp_decl_spec)
1448 -- For srcSpanEnd see Note [The ImportMap]
1449 avail = greExportAvail gre
1450
1451 bestImport :: [ImportSpec] -> ImportSpec
1452 bestImport iss
1453 = case partition isImpAll iss of
1454 ([], imp_somes) -> textuallyFirst imp_somes
1455 (imp_alls, _) -> textuallyFirst imp_alls
1456
1457 textuallyFirst :: [ImportSpec] -> ImportSpec
1458 textuallyFirst iss = case sortWith (is_dloc . is_decl) iss of
1459 [] -> pprPanic "textuallyFirst" (ppr iss)
1460 (is:_) -> is
1461
1462 isImpAll :: ImportSpec -> Bool
1463 isImpAll (ImpSpec { is_item = ImpAll }) = True
1464 isImpAll _other = False
1465
1466 warnUnusedImport :: ImportDeclUsage -> RnM ()
1467 warnUnusedImport (L loc decl, used, unused)
1468 | Just (False,L _ []) <- ideclHiding decl
1469 = return () -- Do not warn for 'import M()'
1470
1471 | Just (True, L _ hides) <- ideclHiding decl
1472 , not (null hides)
1473 , pRELUDE_NAME == unLoc (ideclName decl)
1474 = return () -- Note [Do not warn about Prelude hiding]
1475 | null used = addWarnAt loc msg1 -- Nothing used; drop entire decl
1476 | null unused = return () -- Everything imported is used; nop
1477 | otherwise = addWarnAt loc msg2 -- Some imports are unused
1478 where
1479 msg1 = vcat [pp_herald <+> quotes pp_mod <+> pp_not_used,
1480 nest 2 (ptext (sLit "except perhaps to import instances from")
1481 <+> quotes pp_mod),
1482 ptext (sLit "To import instances alone, use:")
1483 <+> ptext (sLit "import") <+> pp_mod <> parens Outputable.empty ]
1484 msg2 = sep [pp_herald <+> quotes (pprWithCommas ppr unused),
1485 text "from module" <+> quotes pp_mod <+> pp_not_used]
1486 pp_herald = text "The" <+> pp_qual <+> text "import of"
1487 pp_qual
1488 | ideclQualified decl = text "qualified"
1489 | otherwise = Outputable.empty
1490 pp_mod = ppr (unLoc (ideclName decl))
1491 pp_not_used = text "is redundant"
1492
1493 {-
1494 Note [Do not warn about Prelude hiding]
1495 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1496 We do not warn about
1497 import Prelude hiding( x, y )
1498 because even if nothing else from Prelude is used, it may be essential to hide
1499 x,y to avoid name-shadowing warnings. Example (Trac #9061)
1500 import Prelude hiding( log )
1501 f x = log where log = ()
1502
1503
1504
1505 Note [Printing minimal imports]
1506 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1507 To print the minimal imports we walk over the user-supplied import
1508 decls, and simply trim their import lists. NB that
1509
1510 * We do *not* change the 'qualified' or 'as' parts!
1511
1512 * We do not disard a decl altogether; we might need instances
1513 from it. Instead we just trim to an empty import list
1514 -}
1515
1516 printMinimalImports :: [ImportDeclUsage] -> RnM ()
1517 -- See Note [Printing minimal imports]
1518 printMinimalImports imports_w_usage
1519 = do { imports' <- mapM mk_minimal imports_w_usage
1520 ; this_mod <- getModule
1521 ; dflags <- getDynFlags
1522 ; liftIO $
1523 do { h <- openFile (mkFilename dflags this_mod) WriteMode
1524 ; printForUser dflags h neverQualify (vcat (map ppr imports')) }
1525 -- The neverQualify is important. We are printing Names
1526 -- but they are in the context of an 'import' decl, and
1527 -- we never qualify things inside there
1528 -- E.g. import Blag( f, b )
1529 -- not import Blag( Blag.f, Blag.g )!
1530 }
1531 where
1532 mkFilename dflags this_mod
1533 | Just d <- dumpDir dflags = d </> basefn
1534 | otherwise = basefn
1535 where
1536 basefn = moduleNameString (moduleName this_mod) ++ ".imports"
1537
1538 mk_minimal (L l decl, used, unused)
1539 | null unused
1540 , Just (False, _) <- ideclHiding decl
1541 = return (L l decl)
1542 | otherwise
1543 = do { let ImportDecl { ideclName = L _ mod_name
1544 , ideclSource = is_boot
1545 , ideclPkgQual = mb_pkg } = decl
1546 ; ifaces <- loadSrcInterface doc mod_name is_boot mb_pkg
1547 ; let lies = map (L l) (concatMap (to_ie ifaces) used)
1548 ; return (L l (decl { ideclHiding = Just (False, L l lies) })) }
1549 where
1550 doc = text "Compute minimal imports for" <+> ppr decl
1551
1552 to_ie :: [ModIface] -> AvailInfo -> [IE Name]
1553 -- The main trick here is that if we're importing all the constructors
1554 -- we want to say "T(..)", but if we're importing only a subset we want
1555 -- to say "T(A,B,C)". So we have to find out what the module exports.
1556 to_ie _ (Avail n)
1557 = [IEVar (noLoc n)]
1558 to_ie _ (AvailTC n [m])
1559 | n==m = [IEThingAbs n]
1560 to_ie ifaces (AvailTC n ns)
1561 = case [xs | iface <- ifaces
1562 , AvailTC x xs <- mi_exports iface
1563 , x == n
1564 , x `elem` xs -- Note [Partial export]
1565 ] of
1566 [xs] | all_used xs -> [IEThingAll (noLoc n)]
1567 | otherwise -> [IEThingWith (noLoc n)
1568 (map noLoc (filter (/= n) ns))]
1569 _other -> map (IEVar . noLoc) ns
1570 where
1571 all_used avail_occs = all (`elem` ns) avail_occs
1572
1573 {-
1574 Note [Partial export]
1575 ~~~~~~~~~~~~~~~~~~~~~
1576 Suppose we have
1577
1578 module A( op ) where
1579 class C a where
1580 op :: a -> a
1581
1582 module B where
1583 import A
1584 f = ..op...
1585
1586 Then the minimal import for module B is
1587 import A( op )
1588 not
1589 import A( C( op ) )
1590 which we would usually generate if C was exported from B. Hence
1591 the (x `elem` xs) test when deciding what to generate.
1592
1593
1594 ************************************************************************
1595 * *
1596 \subsection{Errors}
1597 * *
1598 ************************************************************************
1599 -}
1600
1601 qualImportItemErr :: RdrName -> SDoc
1602 qualImportItemErr rdr
1603 = hang (ptext (sLit "Illegal qualified name in import item:"))
1604 2 (ppr rdr)
1605
1606 badImportItemErrStd :: IsBootInterface -> ImpDeclSpec -> IE RdrName -> SDoc
1607 badImportItemErrStd is_boot decl_spec ie
1608 = sep [ptext (sLit "Module"), quotes (ppr (is_mod decl_spec)), source_import,
1609 ptext (sLit "does not export"), quotes (ppr ie)]
1610 where
1611 source_import | is_boot = ptext (sLit "(hi-boot interface)")
1612 | otherwise = Outputable.empty
1613
1614 badImportItemErrDataCon :: OccName
1615 -> IsBootInterface
1616 -> ImpDeclSpec
1617 -> IE RdrName
1618 -> SDoc
1619 badImportItemErrDataCon dataType is_boot decl_spec ie
1620 = vcat [ ptext (sLit "In module")
1621 <+> quotes (ppr (is_mod decl_spec))
1622 <+> source_import <> colon
1623 , nest 2 $ quotes datacon
1624 <+> ptext (sLit "is a data constructor of")
1625 <+> quotes (ppr dataType)
1626 , ptext (sLit "To import it use")
1627 , nest 2 $ quotes (ptext (sLit "import"))
1628 <+> ppr (is_mod decl_spec)
1629 <> parens_sp (ppr dataType <> parens_sp datacon)
1630 , ptext (sLit "or")
1631 , nest 2 $ quotes (ptext (sLit "import"))
1632 <+> ppr (is_mod decl_spec)
1633 <> parens_sp (ppr dataType <> ptext (sLit "(..)"))
1634 ]
1635 where
1636 datacon_occ = rdrNameOcc $ ieName ie
1637 datacon = parenSymOcc datacon_occ (ppr datacon_occ)
1638 source_import | is_boot = ptext (sLit "(hi-boot interface)")
1639 | otherwise = Outputable.empty
1640 parens_sp d = parens (space <> d <> space) -- T( f,g )
1641
1642 badImportItemErr :: IsBootInterface
1643 -> ImpDeclSpec
1644 -> IE RdrName
1645 -> [AvailInfo]
1646 -> SDoc
1647 badImportItemErr is_boot decl_spec ie avails
1648 = case find checkIfDataCon avails of
1649 Just con -> badImportItemErrDataCon (availOccName con) is_boot decl_spec ie
1650 Nothing -> badImportItemErrStd is_boot decl_spec ie
1651 where
1652 checkIfDataCon (AvailTC _ ns) =
1653 case find (\n -> importedFS == nameOccNameFS n) ns of
1654 Just n -> isDataConName n
1655 Nothing -> False
1656 checkIfDataCon _ = False
1657 availOccName = nameOccName . availName
1658 nameOccNameFS = occNameFS . nameOccName
1659 importedFS = occNameFS . rdrNameOcc $ ieName ie
1660
1661 illegalImportItemErr :: SDoc
1662 illegalImportItemErr = ptext (sLit "Illegal import item")
1663
1664 dodgyImportWarn :: RdrName -> SDoc
1665 dodgyImportWarn item = dodgyMsg (ptext (sLit "import")) item
1666 dodgyExportWarn :: Name -> SDoc
1667 dodgyExportWarn item = dodgyMsg (ptext (sLit "export")) item
1668
1669 dodgyMsg :: (OutputableBndr n, HasOccName n) => SDoc -> n -> SDoc
1670 dodgyMsg kind tc
1671 = sep [ ptext (sLit "The") <+> kind <+> ptext (sLit "item")
1672 <+> quotes (ppr (IEThingAll (noLoc tc)))
1673 <+> ptext (sLit "suggests that"),
1674 quotes (ppr tc) <+> ptext (sLit "has (in-scope) constructors or class methods,"),
1675 ptext (sLit "but it has none") ]
1676
1677 exportItemErr :: IE RdrName -> SDoc
1678 exportItemErr export_item
1679 = sep [ ptext (sLit "The export item") <+> quotes (ppr export_item),
1680 ptext (sLit "attempts to export constructors or class methods that are not visible here") ]
1681
1682 exportClashErr :: GlobalRdrEnv -> Name -> Name -> IE RdrName -> IE RdrName
1683 -> MsgDoc
1684 exportClashErr global_env name1 name2 ie1 ie2
1685 = vcat [ ptext (sLit "Conflicting exports for") <+> quotes (ppr occ) <> colon
1686 , ppr_export ie1' name1'
1687 , ppr_export ie2' name2' ]
1688 where
1689 occ = nameOccName name1
1690 ppr_export ie name = nest 3 (hang (quotes (ppr ie) <+> ptext (sLit "exports") <+>
1691 quotes (ppr name))
1692 2 (pprNameProvenance (get_gre name)))
1693
1694 -- get_gre finds a GRE for the Name, so that we can show its provenance
1695 get_gre name
1696 = case lookupGRE_Name global_env name of
1697 (gre:_) -> gre
1698 [] -> pprPanic "exportClashErr" (ppr name)
1699 get_loc name = greSrcSpan (get_gre name)
1700 (name1', ie1', name2', ie2') = if get_loc name1 < get_loc name2
1701 then (name1, ie1, name2, ie2)
1702 else (name2, ie2, name1, ie1)
1703
1704 -- the SrcSpan that pprNameProvenance prints out depends on whether
1705 -- the Name is defined locally or not: for a local definition the
1706 -- definition site is used, otherwise the location of the import
1707 -- declaration. We want to sort the export locations in
1708 -- exportClashErr by this SrcSpan, we need to extract it:
1709 greSrcSpan :: GlobalRdrElt -> SrcSpan
1710 greSrcSpan gre
1711 | Imported (is:_) <- gre_prov gre = is_dloc (is_decl is)
1712 | otherwise = name_span
1713 where
1714 name_span = nameSrcSpan (gre_name gre)
1715
1716 addDupDeclErr :: [Name] -> TcRn ()
1717 addDupDeclErr []
1718 = panic "addDupDeclErr: empty list"
1719 addDupDeclErr names@(name : _)
1720 = addErrAt (getSrcSpan (last sorted_names)) $
1721 -- Report the error at the later location
1722 vcat [ptext (sLit "Multiple declarations of") <+>
1723 quotes (ppr (nameOccName name)),
1724 -- NB. print the OccName, not the Name, because the
1725 -- latter might not be in scope in the RdrEnv and so will
1726 -- be printed qualified.
1727 ptext (sLit "Declared at:") <+>
1728 vcat (map (ppr . nameSrcLoc) sorted_names)]
1729 where
1730 sorted_names = sortWith nameSrcLoc names
1731
1732 dupExportWarn :: OccName -> IE RdrName -> IE RdrName -> SDoc
1733 dupExportWarn occ_name ie1 ie2
1734 = hsep [quotes (ppr occ_name),
1735 ptext (sLit "is exported by"), quotes (ppr ie1),
1736 ptext (sLit "and"), quotes (ppr ie2)]
1737
1738 dupModuleExport :: ModuleName -> SDoc
1739 dupModuleExport mod
1740 = hsep [ptext (sLit "Duplicate"),
1741 quotes (ptext (sLit "Module") <+> ppr mod),
1742 ptext (sLit "in export list")]
1743
1744 moduleNotImported :: ModuleName -> SDoc
1745 moduleNotImported mod
1746 = ptext (sLit "The export item `module") <+> ppr mod <>
1747 ptext (sLit "' is not imported")
1748
1749 nullModuleExport :: ModuleName -> SDoc
1750 nullModuleExport mod
1751 = ptext (sLit "The export item `module") <+> ppr mod <> ptext (sLit "' exports nothing")
1752
1753 missingImportListWarn :: ModuleName -> SDoc
1754 missingImportListWarn mod
1755 = ptext (sLit "The module") <+> quotes (ppr mod) <+> ptext (sLit "does not have an explicit import list")
1756
1757 missingImportListItem :: IE RdrName -> SDoc
1758 missingImportListItem ie
1759 = ptext (sLit "The import item") <+> quotes (ppr ie) <+> ptext (sLit "does not have an explicit import list")
1760
1761 moduleWarn :: ModuleName -> WarningTxt -> SDoc
1762 moduleWarn mod (WarningTxt txt)
1763 = sep [ ptext (sLit "Module") <+> quotes (ppr mod) <> ptext (sLit ":"),
1764 nest 2 (vcat (map ppr txt)) ]
1765 moduleWarn mod (DeprecatedTxt txt)
1766 = sep [ ptext (sLit "Module") <+> quotes (ppr mod)
1767 <+> ptext (sLit "is deprecated:"),
1768 nest 2 (vcat (map ppr txt)) ]
1769
1770 packageImportErr :: SDoc
1771 packageImportErr
1772 = ptext (sLit "Package-qualified imports are not enabled; use PackageImports")
1773
1774 -- This data decl will parse OK
1775 -- data T = a Int
1776 -- treating "a" as the constructor.
1777 -- It is really hard to make the parser spot this malformation.
1778 -- So the renamer has to check that the constructor is legal
1779 --
1780 -- We can get an operator as the constructor, even in the prefix form:
1781 -- data T = :% Int Int
1782 -- from interface files, which always print in prefix form
1783
1784 checkConName :: RdrName -> TcRn ()
1785 checkConName name = checkErr (isRdrDataCon name) (badDataCon name)
1786
1787 badDataCon :: RdrName -> SDoc
1788 badDataCon name
1789 = hsep [ptext (sLit "Illegal data constructor name"), quotes (ppr name)]