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