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