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