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