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