Update Trac ticket URLs to point to GitLab
[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 Data.Map ( Map )
67 import qualified Data.Map as Map
68 import Data.Ord ( comparing )
69 import Data.List ( partition, (\\), find, sortBy )
70 import qualified Data.Set as S
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 #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 (#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 #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 = do -- First, attempt to grab the name of the class from the instance.
737 -- This step could fail if the instance is not headed by a class,
738 -- such as in the following examples:
739 --
740 -- (1) The class is headed by a bang pattern, such as in
741 -- `instance !Show Int` (#3811c)
742 -- (2) The class is headed by a type variable, such as in
743 -- `instance c` (#16385)
744 --
745 -- If looking up the class name fails, then mb_cls_nm will
746 -- be Nothing.
747 mb_cls_nm <- runMaybeT $ do
748 -- See (1) above
749 L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty
750 -- See (2) above
751 MaybeT $ setSrcSpan loc $ lookupGlobalOccRn_maybe cls_rdr
752 -- Assuming the previous step succeeded, process any associated data
753 -- family instances. If the previous step failed, bail out.
754 case mb_cls_nm of
755 Nothing -> pure ([], [])
756 Just cls_nm -> do
757 (avails, fldss)
758 <- mapAndUnzipM (new_loc_di overload_ok (Just cls_nm)) adts
759 pure (avails, concat fldss)
760 new_assoc _ (L _ (ClsInstD _ (XClsInstDecl _))) = panic "new_assoc"
761 new_assoc _ (L _ (XInstDecl _)) = panic "new_assoc"
762
763 new_di :: Bool -> Maybe Name -> DataFamInstDecl GhcPs
764 -> RnM (AvailInfo, [(Name, [FieldLabel])])
765 new_di overload_ok mb_cls dfid@(DataFamInstDecl { dfid_eqn =
766 HsIB { hsib_body = ti_decl }})
767 = do { main_name <- lookupFamInstName mb_cls (feqn_tycon ti_decl)
768 ; let (bndrs, flds) = hsDataFamInstBinders dfid
769 ; sub_names <- mapM newTopSrcBinder bndrs
770 ; flds' <- mapM (newRecordSelector overload_ok sub_names) flds
771 ; let avail = AvailTC (unLoc main_name) sub_names flds'
772 -- main_name is not bound here!
773 fld_env = mk_fld_env (feqn_rhs ti_decl) sub_names flds'
774 ; return (avail, fld_env) }
775 new_di _ _ (DataFamInstDecl (XHsImplicitBndrs _)) = panic "new_di"
776
777 new_loc_di :: Bool -> Maybe Name -> LDataFamInstDecl GhcPs
778 -> RnM (AvailInfo, [(Name, [FieldLabel])])
779 new_loc_di overload_ok mb_cls (L _ d) = new_di overload_ok mb_cls d
780 getLocalNonValBinders _ (XHsGroup _) = panic "getLocalNonValBinders"
781
782 newRecordSelector :: Bool -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel
783 newRecordSelector _ [] _ = error "newRecordSelector: datatype has no constructors!"
784 newRecordSelector _ _ (L _ (XFieldOcc _)) = panic "newRecordSelector"
785 newRecordSelector overload_ok (dc:_) (L loc (FieldOcc _ (L _ fld)))
786 = do { selName <- newTopSrcBinder $ L loc $ field
787 ; return $ qualFieldLbl { flSelector = selName } }
788 where
789 fieldOccName = occNameFS $ rdrNameOcc fld
790 qualFieldLbl = mkFieldLabelOccs fieldOccName (nameOccName dc) overload_ok
791 field | isExact fld = fld
792 -- use an Exact RdrName as is to preserve the bindings
793 -- of an already renamer-resolved field and its use
794 -- sites. This is needed to correctly support record
795 -- selectors in Template Haskell. See Note [Binders in
796 -- Template Haskell] in Convert.hs and Note [Looking up
797 -- Exact RdrNames] in RnEnv.hs.
798 | otherwise = mkRdrUnqual (flSelector qualFieldLbl)
799
800 {-
801 Note [Looking up family names in family instances]
802 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
803 Consider
804
805 module M where
806 type family T a :: *
807 type instance M.T Int = Bool
808
809 We might think that we can simply use 'lookupOccRn' when processing the type
810 instance to look up 'M.T'. Alas, we can't! The type family declaration is in
811 the *same* HsGroup as the type instance declaration. Hence, as we are
812 currently collecting the binders declared in that HsGroup, these binders will
813 not have been added to the global environment yet.
814
815 Solution is simple: process the type family declarations first, extend
816 the environment, and then process the type instances.
817
818
819 ************************************************************************
820 * *
821 \subsection{Filtering imports}
822 * *
823 ************************************************************************
824
825 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
826 available, and filters it through the import spec (if any).
827
828 Note [Dealing with imports]
829 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
830 For import M( ies ), we take the mi_exports of M, and make
831 imp_occ_env :: OccEnv (Name, AvailInfo, Maybe Name)
832 One entry for each Name that M exports; the AvailInfo is the
833 AvailInfo exported from M that exports that Name.
834
835 The situation is made more complicated by associated types. E.g.
836 module M where
837 class C a where { data T a }
838 instance C Int where { data T Int = T1 | T2 }
839 instance C Bool where { data T Int = T3 }
840 Then M's export_avails are (recall the AvailTC invariant from Avails.hs)
841 C(C,T), T(T,T1,T2,T3)
842 Notice that T appears *twice*, once as a child and once as a parent. From
843 this list we construct a raw list including
844 T -> (T, T( T1, T2, T3 ), Nothing)
845 T -> (C, C( C, T ), Nothing)
846 and we combine these (in function 'combine' in 'imp_occ_env' in
847 'filterImports') to get
848 T -> (T, T(T,T1,T2,T3), Just C)
849
850 So the overall imp_occ_env is
851 C -> (C, C(C,T), Nothing)
852 T -> (T, T(T,T1,T2,T3), Just C)
853 T1 -> (T1, T(T,T1,T2,T3), Nothing) -- similarly T2,T3
854
855 If we say
856 import M( T(T1,T2) )
857 then we get *two* Avails: C(T), T(T1,T2)
858
859 Note that the imp_occ_env will have entries for data constructors too,
860 although we never look up data constructors.
861 -}
862
863 filterImports
864 :: ModIface
865 -> ImpDeclSpec -- The span for the entire import decl
866 -> Maybe (Bool, Located [LIE GhcPs]) -- Import spec; True => hiding
867 -> RnM (Maybe (Bool, Located [LIE GhcRn]), -- Import spec w/ Names
868 [GlobalRdrElt]) -- Same again, but in GRE form
869 filterImports iface decl_spec Nothing
870 = return (Nothing, gresFromAvails (Just imp_spec) (mi_exports iface))
871 where
872 imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }
873
874
875 filterImports iface decl_spec (Just (want_hiding, L l import_items))
876 = do -- check for errors, convert RdrNames to Names
877 items1 <- mapM lookup_lie import_items
878
879 let items2 :: [(LIE GhcRn, AvailInfo)]
880 items2 = concat items1
881 -- NB the AvailInfo may have duplicates, and several items
882 -- for the same parent; e.g N(x) and N(y)
883
884 names = availsToNameSetWithSelectors (map snd items2)
885 keep n = not (n `elemNameSet` names)
886 pruned_avails = filterAvails keep all_avails
887 hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }
888
889 gres | want_hiding = gresFromAvails (Just hiding_spec) pruned_avails
890 | otherwise = concatMap (gresFromIE decl_spec) items2
891
892 return (Just (want_hiding, L l (map fst items2)), gres)
893 where
894 all_avails = mi_exports iface
895
896 -- See Note [Dealing with imports]
897 imp_occ_env :: OccEnv (Name, -- the name
898 AvailInfo, -- the export item providing the name
899 Maybe Name) -- the parent of associated types
900 imp_occ_env = mkOccEnv_C combine [ (occ, (n, a, Nothing))
901 | a <- all_avails
902 , (n, occ) <- availNamesWithOccs a]
903 where
904 -- See Note [Dealing with imports]
905 -- 'combine' is only called for associated data types which appear
906 -- twice in the all_avails. In the example, we combine
907 -- T(T,T1,T2,T3) and C(C,T) to give (T, T(T,T1,T2,T3), Just C)
908 -- NB: the AvailTC can have fields as well as data constructors (#12127)
909 combine (name1, a1@(AvailTC p1 _ _), mp1)
910 (name2, a2@(AvailTC p2 _ _), mp2)
911 = ASSERT2( name1 == name2 && isNothing mp1 && isNothing mp2
912 , ppr name1 <+> ppr name2 <+> ppr mp1 <+> ppr mp2 )
913 if p1 == name1 then (name1, a1, Just p2)
914 else (name1, a2, Just p1)
915 combine x y = pprPanic "filterImports/combine" (ppr x $$ ppr y)
916
917 lookup_name :: IE GhcPs -> RdrName -> IELookupM (Name, AvailInfo, Maybe Name)
918 lookup_name ie rdr
919 | isQual rdr = failLookupWith (QualImportError rdr)
920 | Just succ <- mb_success = return succ
921 | otherwise = failLookupWith (BadImport ie)
922 where
923 mb_success = lookupOccEnv imp_occ_env (rdrNameOcc rdr)
924
925 lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, AvailInfo)]
926 lookup_lie (L loc ieRdr)
927 = do (stuff, warns) <- setSrcSpan loc $
928 liftM (fromMaybe ([],[])) $
929 run_lookup (lookup_ie ieRdr)
930 mapM_ emit_warning warns
931 return [ (L loc ie, avail) | (ie,avail) <- stuff ]
932 where
933 -- Warn when importing T(..) if T was exported abstractly
934 emit_warning (DodgyImport n) = whenWOptM Opt_WarnDodgyImports $
935 addWarn (Reason Opt_WarnDodgyImports) (dodgyImportWarn n)
936 emit_warning MissingImportList = whenWOptM Opt_WarnMissingImportList $
937 addWarn (Reason Opt_WarnMissingImportList) (missingImportListItem ieRdr)
938 emit_warning (BadImportW ie) = whenWOptM Opt_WarnDodgyImports $
939 addWarn (Reason Opt_WarnDodgyImports) (lookup_err_msg (BadImport ie))
940
941 run_lookup :: IELookupM a -> TcRn (Maybe a)
942 run_lookup m = case m of
943 Failed err -> addErr (lookup_err_msg err) >> return Nothing
944 Succeeded a -> return (Just a)
945
946 lookup_err_msg err = case err of
947 BadImport ie -> badImportItemErr iface decl_spec ie all_avails
948 IllegalImport -> illegalImportItemErr
949 QualImportError rdr -> qualImportItemErr rdr
950
951 -- For each import item, we convert its RdrNames to Names,
952 -- and at the same time construct an AvailInfo corresponding
953 -- to what is actually imported by this item.
954 -- Returns Nothing on error.
955 -- We return a list here, because in the case of an import
956 -- item like C, if we are hiding, then C refers to *both* a
957 -- type/class and a data constructor. Moreover, when we import
958 -- data constructors of an associated family, we need separate
959 -- AvailInfos for the data constructors and the family (as they have
960 -- different parents). See Note [Dealing with imports]
961 lookup_ie :: IE GhcPs
962 -> IELookupM ([(IE GhcRn, AvailInfo)], [IELookupWarning])
963 lookup_ie ie = handle_bad_import $ do
964 case ie of
965 IEVar _ (L l n) -> do
966 (name, avail, _) <- lookup_name ie $ ieWrappedName n
967 return ([(IEVar noExt (L l (replaceWrappedName n name)),
968 trimAvail avail name)], [])
969
970 IEThingAll _ (L l tc) -> do
971 (name, avail, mb_parent) <- lookup_name ie $ ieWrappedName tc
972 let warns = case avail of
973 Avail {} -- e.g. f(..)
974 -> [DodgyImport $ ieWrappedName tc]
975
976 AvailTC _ subs fs
977 | null (drop 1 subs) && null fs -- e.g. T(..) where T is a synonym
978 -> [DodgyImport $ ieWrappedName tc]
979
980 | not (is_qual decl_spec) -- e.g. import M( T(..) )
981 -> [MissingImportList]
982
983 | otherwise
984 -> []
985
986 renamed_ie = IEThingAll noExt (L l (replaceWrappedName tc name))
987 sub_avails = case avail of
988 Avail {} -> []
989 AvailTC name2 subs fs -> [(renamed_ie, AvailTC name2 (subs \\ [name]) fs)]
990 case mb_parent of
991 Nothing -> return ([(renamed_ie, avail)], warns)
992 -- non-associated ty/cls
993 Just parent -> return ((renamed_ie, AvailTC parent [name] []) : sub_avails, warns)
994 -- associated type
995
996 IEThingAbs _ (L l tc')
997 | want_hiding -- hiding ( C )
998 -- Here the 'C' can be a data constructor
999 -- *or* a type/class, or even both
1000 -> let tc = ieWrappedName tc'
1001 tc_name = lookup_name ie tc
1002 dc_name = lookup_name ie (setRdrNameSpace tc srcDataName)
1003 in
1004 case catIELookupM [ tc_name, dc_name ] of
1005 [] -> failLookupWith (BadImport ie)
1006 names -> return ([mkIEThingAbs tc' l name | name <- names], [])
1007 | otherwise
1008 -> do nameAvail <- lookup_name ie (ieWrappedName tc')
1009 return ([mkIEThingAbs tc' l nameAvail]
1010 , [])
1011
1012 IEThingWith xt ltc@(L l rdr_tc) wc rdr_ns rdr_fs ->
1013 ASSERT2(null rdr_fs, ppr rdr_fs) do
1014 (name, avail, mb_parent)
1015 <- lookup_name (IEThingAbs noExt ltc) (ieWrappedName rdr_tc)
1016
1017 let (ns,subflds) = case avail of
1018 AvailTC _ ns' subflds' -> (ns',subflds')
1019 Avail _ -> panic "filterImports"
1020
1021 -- Look up the children in the sub-names of the parent
1022 let subnames = case ns of -- The tc is first in ns,
1023 [] -> [] -- if it is there at all
1024 -- See the AvailTC Invariant in Avail.hs
1025 (n1:ns1) | n1 == name -> ns1
1026 | otherwise -> ns
1027 case lookupChildren (map Left subnames ++ map Right subflds) rdr_ns of
1028
1029 Failed rdrs -> failLookupWith (BadImport (IEThingWith xt ltc wc rdrs []))
1030 -- We are trying to import T( a,b,c,d ), and failed
1031 -- to find 'b' and 'd'. So we make up an import item
1032 -- to report as failing, namely T( b, d ).
1033 -- c.f. #15412
1034
1035 Succeeded (childnames, childflds) ->
1036 case mb_parent of
1037 -- non-associated ty/cls
1038 Nothing
1039 -> return ([(IEThingWith noExt (L l name') wc childnames'
1040 childflds,
1041 AvailTC name (name:map unLoc childnames) (map unLoc childflds))],
1042 [])
1043 where name' = replaceWrappedName rdr_tc name
1044 childnames' = map to_ie_post_rn childnames
1045 -- childnames' = postrn_ies childnames
1046 -- associated ty
1047 Just parent
1048 -> return ([(IEThingWith noExt (L l name') wc childnames'
1049 childflds,
1050 AvailTC name (map unLoc childnames) (map unLoc childflds)),
1051 (IEThingWith noExt (L l name') wc childnames'
1052 childflds,
1053 AvailTC parent [name] [])],
1054 [])
1055 where name' = replaceWrappedName rdr_tc name
1056 childnames' = map to_ie_post_rn childnames
1057
1058 _other -> failLookupWith IllegalImport
1059 -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed
1060 -- all errors.
1061
1062 where
1063 mkIEThingAbs tc l (n, av, Nothing )
1064 = (IEThingAbs noExt (L l (replaceWrappedName tc n)), trimAvail av n)
1065 mkIEThingAbs tc l (n, _, Just parent)
1066 = (IEThingAbs noExt (L l (replaceWrappedName tc n))
1067 , AvailTC parent [n] [])
1068
1069 handle_bad_import m = catchIELookup m $ \err -> case err of
1070 BadImport ie | want_hiding -> return ([], [BadImportW ie])
1071 _ -> failLookupWith err
1072
1073 type IELookupM = MaybeErr IELookupError
1074
1075 data IELookupWarning
1076 = BadImportW (IE GhcPs)
1077 | MissingImportList
1078 | DodgyImport RdrName
1079 -- NB. use the RdrName for reporting a "dodgy" import
1080
1081 data IELookupError
1082 = QualImportError RdrName
1083 | BadImport (IE GhcPs)
1084 | IllegalImport
1085
1086 failLookupWith :: IELookupError -> IELookupM a
1087 failLookupWith err = Failed err
1088
1089 catchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a
1090 catchIELookup m h = case m of
1091 Succeeded r -> return r
1092 Failed err -> h err
1093
1094 catIELookupM :: [IELookupM a] -> [a]
1095 catIELookupM ms = [ a | Succeeded a <- ms ]
1096
1097 {-
1098 ************************************************************************
1099 * *
1100 \subsection{Import/Export Utils}
1101 * *
1102 ************************************************************************
1103 -}
1104
1105 -- | Given an import\/export spec, construct the appropriate 'GlobalRdrElt's.
1106 gresFromIE :: ImpDeclSpec -> (LIE GhcRn, AvailInfo) -> [GlobalRdrElt]
1107 gresFromIE decl_spec (L loc ie, avail)
1108 = gresFromAvail prov_fn avail
1109 where
1110 is_explicit = case ie of
1111 IEThingAll _ name -> \n -> n == lieWrappedName name
1112 _ -> \_ -> True
1113 prov_fn name
1114 = Just (ImpSpec { is_decl = decl_spec, is_item = item_spec })
1115 where
1116 item_spec = ImpSome { is_explicit = is_explicit name, is_iloc = loc }
1117
1118
1119 {-
1120 Note [Children for duplicate record fields]
1121 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1122 Consider the module
1123
1124 {-# LANGUAGE DuplicateRecordFields #-}
1125 module M (F(foo, MkFInt, MkFBool)) where
1126 data family F a
1127 data instance F Int = MkFInt { foo :: Int }
1128 data instance F Bool = MkFBool { foo :: Bool }
1129
1130 The `foo` in the export list refers to *both* selectors! For this
1131 reason, lookupChildren builds an environment that maps the FastString
1132 to a list of items, rather than a single item.
1133 -}
1134
1135 mkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]
1136 mkChildEnv gres = foldr add emptyNameEnv gres
1137 where
1138 add gre env = case gre_par gre of
1139 FldParent p _ -> extendNameEnv_Acc (:) singleton env p gre
1140 ParentIs p -> extendNameEnv_Acc (:) singleton env p gre
1141 NoParent -> env
1142
1143 findChildren :: NameEnv [a] -> Name -> [a]
1144 findChildren env n = lookupNameEnv env n `orElse` []
1145
1146 lookupChildren :: [Either Name FieldLabel] -> [LIEWrappedName RdrName]
1147 -> MaybeErr [LIEWrappedName RdrName] -- The ones for which the lookup failed
1148 ([Located Name], [Located FieldLabel])
1149 -- (lookupChildren all_kids rdr_items) maps each rdr_item to its
1150 -- corresponding Name all_kids, if the former exists
1151 -- The matching is done by FastString, not OccName, so that
1152 -- Cls( meth, AssocTy )
1153 -- will correctly find AssocTy among the all_kids of Cls, even though
1154 -- the RdrName for AssocTy may have a (bogus) DataName namespace
1155 -- (Really the rdr_items should be FastStrings in the first place.)
1156 lookupChildren all_kids rdr_items
1157 | null fails
1158 = Succeeded (fmap concat (partitionEithers oks))
1159 -- This 'fmap concat' trickily applies concat to the /second/ component
1160 -- of the pair, whose type is ([Located Name], [[Located FieldLabel]])
1161 | otherwise
1162 = Failed fails
1163 where
1164 mb_xs = map doOne rdr_items
1165 fails = [ bad_rdr | Failed bad_rdr <- mb_xs ]
1166 oks = [ ok | Succeeded ok <- mb_xs ]
1167 oks :: [Either (Located Name) [Located FieldLabel]]
1168
1169 doOne item@(L l r)
1170 = case (lookupFsEnv kid_env . occNameFS . rdrNameOcc . ieWrappedName) r of
1171 Just [Left n] -> Succeeded (Left (L l n))
1172 Just rs | all isRight rs -> Succeeded (Right (map (L l) (rights rs)))
1173 _ -> Failed item
1174
1175 -- See Note [Children for duplicate record fields]
1176 kid_env = extendFsEnvList_C (++) emptyFsEnv
1177 [(either (occNameFS . nameOccName) flLabel x, [x]) | x <- all_kids]
1178
1179
1180
1181 -------------------------------
1182
1183 {-
1184 *********************************************************
1185 * *
1186 \subsection{Unused names}
1187 * *
1188 *********************************************************
1189 -}
1190
1191 reportUnusedNames :: Maybe (Located [LIE GhcPs]) -- Export list
1192 -> TcGblEnv -> RnM ()
1193 reportUnusedNames _export_decls gbl_env
1194 = do { traceRn "RUN" (ppr (tcg_dus gbl_env))
1195 ; warnUnusedImportDecls gbl_env
1196 ; warnUnusedTopBinds unused_locals
1197 ; warnMissingSignatures gbl_env }
1198 where
1199 used_names :: NameSet
1200 used_names = findUses (tcg_dus gbl_env) emptyNameSet
1201 -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
1202 -- Hence findUses
1203
1204 -- Collect the defined names from the in-scope environment
1205 defined_names :: [GlobalRdrElt]
1206 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
1207
1208 -- Note that defined_and_used, defined_but_not_used
1209 -- are both [GRE]; that's why we need defined_and_used
1210 -- rather than just used_names
1211 _defined_and_used, defined_but_not_used :: [GlobalRdrElt]
1212 (_defined_and_used, defined_but_not_used)
1213 = partition (gre_is_used used_names) defined_names
1214
1215 kids_env = mkChildEnv defined_names
1216 -- This is done in mkExports too; duplicated work
1217
1218 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
1219 gre_is_used used_names (GRE {gre_name = name})
1220 = name `elemNameSet` used_names
1221 || any (\ gre -> gre_name gre `elemNameSet` used_names) (findChildren kids_env name)
1222 -- A use of C implies a use of T,
1223 -- if C was brought into scope by T(..) or T(C)
1224
1225 -- Filter out the ones that are
1226 -- (a) defined in this module, and
1227 -- (b) not defined by a 'deriving' clause
1228 -- The latter have an Internal Name, so we can filter them out easily
1229 unused_locals :: [GlobalRdrElt]
1230 unused_locals = filter is_unused_local defined_but_not_used
1231 is_unused_local :: GlobalRdrElt -> Bool
1232 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
1233
1234 {- *********************************************************************
1235 * *
1236 Missing signatures
1237 * *
1238 ********************************************************************* -}
1239
1240 -- | Warn the user about top level binders that lack type signatures.
1241 -- Called /after/ type inference, so that we can report the
1242 -- inferred type of the function
1243 warnMissingSignatures :: TcGblEnv -> RnM ()
1244 warnMissingSignatures gbl_env
1245 = do { let exports = availsToNameSet (tcg_exports gbl_env)
1246 sig_ns = tcg_sigs gbl_env
1247 -- We use sig_ns to exclude top-level bindings that are generated by GHC
1248 binds = collectHsBindsBinders $ tcg_binds gbl_env
1249 pat_syns = tcg_patsyns gbl_env
1250
1251 -- Warn about missing signatures
1252 -- Do this only when we have a type to offer
1253 ; warn_missing_sigs <- woptM Opt_WarnMissingSignatures
1254 ; warn_only_exported <- woptM Opt_WarnMissingExportedSignatures
1255 ; warn_pat_syns <- woptM Opt_WarnMissingPatternSynonymSignatures
1256
1257 ; let add_sig_warns
1258 | warn_only_exported = add_warns Opt_WarnMissingExportedSignatures
1259 | warn_missing_sigs = add_warns Opt_WarnMissingSignatures
1260 | warn_pat_syns = add_warns Opt_WarnMissingPatternSynonymSignatures
1261 | otherwise = return ()
1262
1263 add_warns flag
1264 = when warn_pat_syns
1265 (mapM_ add_pat_syn_warn pat_syns) >>
1266 when (warn_missing_sigs || warn_only_exported)
1267 (mapM_ add_bind_warn binds)
1268 where
1269 add_pat_syn_warn p
1270 = add_warn name $
1271 hang (text "Pattern synonym with no type signature:")
1272 2 (text "pattern" <+> pprPrefixName name <+> dcolon <+> pp_ty)
1273 where
1274 name = patSynName p
1275 pp_ty = pprPatSynType p
1276
1277 add_bind_warn :: Id -> IOEnv (Env TcGblEnv TcLclEnv) ()
1278 add_bind_warn id
1279 = do { env <- tcInitTidyEnv -- Why not use emptyTidyEnv?
1280 ; let name = idName id
1281 (_, ty) = tidyOpenType env (idType id)
1282 ty_msg = pprSigmaType ty
1283 ; add_warn name $
1284 hang (text "Top-level binding with no type signature:")
1285 2 (pprPrefixName name <+> dcolon <+> ty_msg) }
1286
1287 add_warn name msg
1288 = when (name `elemNameSet` sig_ns && export_check name)
1289 (addWarnAt (Reason flag) (getSrcSpan name) msg)
1290
1291 export_check name
1292 = not warn_only_exported || name `elemNameSet` exports
1293
1294 ; add_sig_warns }
1295
1296
1297 {-
1298 *********************************************************
1299 * *
1300 \subsection{Unused imports}
1301 * *
1302 *********************************************************
1303
1304 This code finds which import declarations are unused. The
1305 specification and implementation notes are here:
1306 http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/UnusedImports
1307
1308 See also Note [Choosing the best import declaration] in RdrName
1309 -}
1310
1311 type ImportDeclUsage
1312 = ( LImportDecl GhcRn -- The import declaration
1313 , [GlobalRdrElt] -- What *is* used (normalised)
1314 , [Name] ) -- What is imported but *not* used
1315
1316 warnUnusedImportDecls :: TcGblEnv -> RnM ()
1317 warnUnusedImportDecls gbl_env
1318 = do { uses <- readMutVar (tcg_used_gres gbl_env)
1319 ; let user_imports = filterOut
1320 (ideclImplicit . unLoc)
1321 (tcg_rn_imports gbl_env)
1322 -- This whole function deals only with *user* imports
1323 -- both for warning about unnecessary ones, and for
1324 -- deciding the minimal ones
1325 rdr_env = tcg_rdr_env gbl_env
1326 fld_env = mkFieldEnv rdr_env
1327
1328 ; let usage :: [ImportDeclUsage]
1329 usage = findImportUsage user_imports uses
1330
1331 ; traceRn "warnUnusedImportDecls" $
1332 (vcat [ text "Uses:" <+> ppr uses
1333 , text "Import usage" <+> ppr usage])
1334
1335 ; whenWOptM Opt_WarnUnusedImports $
1336 mapM_ (warnUnusedImport Opt_WarnUnusedImports fld_env) usage
1337
1338 ; whenGOptM Opt_D_dump_minimal_imports $
1339 printMinimalImports usage }
1340
1341 findImportUsage :: [LImportDecl GhcRn]
1342 -> [GlobalRdrElt]
1343 -> [ImportDeclUsage]
1344
1345 findImportUsage imports used_gres
1346 = map unused_decl imports
1347 where
1348 import_usage :: ImportMap
1349 import_usage = mkImportMap used_gres
1350
1351 unused_decl decl@(L loc (ImportDecl { ideclHiding = imps }))
1352 = (decl, used_gres, nameSetElemsStable unused_imps)
1353 where
1354 used_gres = Map.lookup (srcSpanEnd loc) import_usage
1355 -- srcSpanEnd: see Note [The ImportMap]
1356 `orElse` []
1357
1358 used_names = mkNameSet (map gre_name used_gres)
1359 used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)
1360
1361 unused_imps -- Not trivial; see eg #7454
1362 = case imps of
1363 Just (False, L _ imp_ies) ->
1364 foldr (add_unused . unLoc) emptyNameSet imp_ies
1365 _other -> emptyNameSet -- No explicit import list => no unused-name list
1366
1367 add_unused :: IE GhcRn -> NameSet -> NameSet
1368 add_unused (IEVar _ n) acc = add_unused_name (lieWrappedName n) acc
1369 add_unused (IEThingAbs _ n) acc = add_unused_name (lieWrappedName n) acc
1370 add_unused (IEThingAll _ n) acc = add_unused_all (lieWrappedName n) acc
1371 add_unused (IEThingWith _ p wc ns fs) acc =
1372 add_wc_all (add_unused_with pn xs acc)
1373 where pn = lieWrappedName p
1374 xs = map lieWrappedName ns ++ map (flSelector . unLoc) fs
1375 add_wc_all = case wc of
1376 NoIEWildcard -> id
1377 IEWildcard _ -> add_unused_all pn
1378 add_unused _ acc = acc
1379
1380 add_unused_name n acc
1381 | n `elemNameSet` used_names = acc
1382 | otherwise = acc `extendNameSet` n
1383 add_unused_all n acc
1384 | n `elemNameSet` used_names = acc
1385 | n `elemNameSet` used_parents = acc
1386 | otherwise = acc `extendNameSet` n
1387 add_unused_with p ns acc
1388 | all (`elemNameSet` acc1) ns = add_unused_name p acc1
1389 | otherwise = acc1
1390 where
1391 acc1 = foldr add_unused_name acc ns
1392 -- If you use 'signum' from Num, then the user may well have
1393 -- imported Num(signum). We don't want to complain that
1394 -- Num is not itself mentioned. Hence the two cases in add_unused_with.
1395 unused_decl (L _ (XImportDecl _)) = panic "unused_decl"
1396
1397
1398 {- Note [The ImportMap]
1399 ~~~~~~~~~~~~~~~~~~~~~~~
1400 The ImportMap is a short-lived intermediate data structure records, for
1401 each import declaration, what stuff brought into scope by that
1402 declaration is actually used in the module.
1403
1404 The SrcLoc is the location of the END of a particular 'import'
1405 declaration. Why *END*? Because we don't want to get confused
1406 by the implicit Prelude import. Consider (#7476) the module
1407 import Foo( foo )
1408 main = print foo
1409 There is an implicit 'import Prelude(print)', and it gets a SrcSpan
1410 of line 1:1 (just the point, not a span). If we use the *START* of
1411 the SrcSpan to identify the import decl, we'll confuse the implicit
1412 import Prelude with the explicit 'import Foo'. So we use the END.
1413 It's just a cheap hack; we could equally well use the Span too.
1414
1415 The [GlobalRdrElt] are the things imported from that decl.
1416 -}
1417
1418 type ImportMap = Map SrcLoc [GlobalRdrElt] -- See [The ImportMap]
1419 -- If loc :-> gres, then
1420 -- 'loc' = the end loc of the bestImport of each GRE in 'gres'
1421
1422 mkImportMap :: [GlobalRdrElt] -> ImportMap
1423 -- For each of a list of used GREs, find all the import decls that brought
1424 -- it into scope; choose one of them (bestImport), and record
1425 -- the RdrName in that import decl's entry in the ImportMap
1426 mkImportMap gres
1427 = foldr add_one Map.empty gres
1428 where
1429 add_one gre@(GRE { gre_imp = imp_specs }) imp_map
1430 = Map.insertWith add decl_loc [gre] imp_map
1431 where
1432 best_imp_spec = bestImport imp_specs
1433 decl_loc = srcSpanEnd (is_dloc (is_decl best_imp_spec))
1434 -- For srcSpanEnd see Note [The ImportMap]
1435 add _ gres = gre : gres
1436
1437 warnUnusedImport :: WarningFlag -> NameEnv (FieldLabelString, Name)
1438 -> ImportDeclUsage -> RnM ()
1439 warnUnusedImport flag fld_env (L loc decl, used, unused)
1440
1441 -- Do not warn for 'import M()'
1442 | Just (False,L _ []) <- ideclHiding decl
1443 = return ()
1444
1445 -- Note [Do not warn about Prelude hiding]
1446 | Just (True, L _ hides) <- ideclHiding decl
1447 , not (null hides)
1448 , pRELUDE_NAME == unLoc (ideclName decl)
1449 = return ()
1450
1451 -- Nothing used; drop entire declaration
1452 | null used
1453 = addWarnAt (Reason flag) loc msg1
1454
1455 -- Everything imported is used; nop
1456 | null unused
1457 = return ()
1458
1459 -- Some imports are unused
1460 | otherwise
1461 = addWarnAt (Reason flag) loc msg2
1462
1463 where
1464 msg1 = vcat [ pp_herald <+> quotes pp_mod <+> is_redundant
1465 , nest 2 (text "except perhaps to import instances from"
1466 <+> quotes pp_mod)
1467 , text "To import instances alone, use:"
1468 <+> text "import" <+> pp_mod <> parens Outputable.empty ]
1469 msg2 = sep [ pp_herald <+> quotes sort_unused
1470 , text "from module" <+> quotes pp_mod <+> is_redundant]
1471 pp_herald = text "The" <+> pp_qual <+> text "import of"
1472 pp_qual
1473 | ideclQualified decl = text "qualified"
1474 | otherwise = Outputable.empty
1475 pp_mod = ppr (unLoc (ideclName decl))
1476 is_redundant = text "is redundant"
1477
1478 -- In warning message, pretty-print identifiers unqualified unconditionally
1479 -- to improve the consistent for ambiguous/unambiguous identifiers.
1480 -- See trac#14881.
1481 ppr_possible_field n = case lookupNameEnv fld_env n of
1482 Just (fld, p) -> pprNameUnqualified p <> parens (ppr fld)
1483 Nothing -> pprNameUnqualified n
1484
1485 -- Print unused names in a deterministic (lexicographic) order
1486 sort_unused :: SDoc
1487 sort_unused = pprWithCommas ppr_possible_field $
1488 sortBy (comparing nameOccName) unused
1489
1490 {-
1491 Note [Do not warn about Prelude hiding]
1492 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1493 We do not warn about
1494 import Prelude hiding( x, y )
1495 because even if nothing else from Prelude is used, it may be essential to hide
1496 x,y to avoid name-shadowing warnings. Example (#9061)
1497 import Prelude hiding( log )
1498 f x = log where log = ()
1499
1500
1501
1502 Note [Printing minimal imports]
1503 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1504 To print the minimal imports we walk over the user-supplied import
1505 decls, and simply trim their import lists. NB that
1506
1507 * We do *not* change the 'qualified' or 'as' parts!
1508
1509 * We do not disard a decl altogether; we might need instances
1510 from it. Instead we just trim to an empty import list
1511 -}
1512
1513 getMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]
1514 getMinimalImports = mapM mk_minimal
1515 where
1516 mk_minimal (L l decl, used_gres, unused)
1517 | null unused
1518 , Just (False, _) <- ideclHiding decl
1519 = return (L l decl)
1520 | otherwise
1521 = do { let ImportDecl { ideclName = L _ mod_name
1522 , ideclSource = is_boot
1523 , ideclPkgQual = mb_pkg } = decl
1524 ; iface <- loadSrcInterface doc mod_name is_boot (fmap sl_fs mb_pkg)
1525 ; let used_avails = gresToAvailInfo used_gres
1526 lies = map (L l) (concatMap (to_ie iface) used_avails)
1527 ; return (L l (decl { ideclHiding = Just (False, L l lies) })) }
1528 where
1529 doc = text "Compute minimal imports for" <+> ppr decl
1530
1531 to_ie :: ModIface -> AvailInfo -> [IE GhcRn]
1532 -- The main trick here is that if we're importing all the constructors
1533 -- we want to say "T(..)", but if we're importing only a subset we want
1534 -- to say "T(A,B,C)". So we have to find out what the module exports.
1535 to_ie _ (Avail n)
1536 = [IEVar noExt (to_ie_post_rn $ noLoc n)]
1537 to_ie _ (AvailTC n [m] [])
1538 | n==m = [IEThingAbs noExt (to_ie_post_rn $ noLoc n)]
1539 to_ie iface (AvailTC n ns fs)
1540 = case [(xs,gs) | AvailTC x xs gs <- mi_exports iface
1541 , x == n
1542 , x `elem` xs -- Note [Partial export]
1543 ] of
1544 [xs] | all_used xs -> [IEThingAll noExt (to_ie_post_rn $ noLoc n)]
1545 | otherwise ->
1546 [IEThingWith noExt (to_ie_post_rn $ noLoc n) NoIEWildcard
1547 (map (to_ie_post_rn . noLoc) (filter (/= n) ns))
1548 (map noLoc fs)]
1549 -- Note [Overloaded field import]
1550 _other | all_non_overloaded fs
1551 -> map (IEVar noExt . to_ie_post_rn_var . noLoc) $ ns
1552 ++ map flSelector fs
1553 | otherwise ->
1554 [IEThingWith noExt (to_ie_post_rn $ noLoc n) NoIEWildcard
1555 (map (to_ie_post_rn . noLoc) (filter (/= n) ns))
1556 (map noLoc fs)]
1557 where
1558
1559 fld_lbls = map flLabel fs
1560
1561 all_used (avail_occs, avail_flds)
1562 = all (`elem` ns) avail_occs
1563 && all (`elem` fld_lbls) (map flLabel avail_flds)
1564
1565 all_non_overloaded = all (not . flIsOverloaded)
1566
1567 printMinimalImports :: [ImportDeclUsage] -> RnM ()
1568 -- See Note [Printing minimal imports]
1569 printMinimalImports imports_w_usage
1570 = do { imports' <- getMinimalImports imports_w_usage
1571 ; this_mod <- getModule
1572 ; dflags <- getDynFlags
1573 ; liftIO $
1574 do { h <- openFile (mkFilename dflags this_mod) WriteMode
1575 ; printForUser dflags h neverQualify (vcat (map ppr imports')) }
1576 -- The neverQualify is important. We are printing Names
1577 -- but they are in the context of an 'import' decl, and
1578 -- we never qualify things inside there
1579 -- E.g. import Blag( f, b )
1580 -- not import Blag( Blag.f, Blag.g )!
1581 }
1582 where
1583 mkFilename dflags this_mod
1584 | Just d <- dumpDir dflags = d </> basefn
1585 | otherwise = basefn
1586 where
1587 basefn = moduleNameString (moduleName this_mod) ++ ".imports"
1588
1589
1590 to_ie_post_rn_var :: (HasOccName name) => Located name -> LIEWrappedName name
1591 to_ie_post_rn_var (L l n)
1592 | isDataOcc $ occName n = L l (IEPattern (L l n))
1593 | otherwise = L l (IEName (L l n))
1594
1595
1596 to_ie_post_rn :: (HasOccName name) => Located name -> LIEWrappedName name
1597 to_ie_post_rn (L l n)
1598 | isTcOcc occ && isSymOcc occ = L l (IEType (L l n))
1599 | otherwise = L l (IEName (L l n))
1600 where occ = occName n
1601
1602 {-
1603 Note [Partial export]
1604 ~~~~~~~~~~~~~~~~~~~~~
1605 Suppose we have
1606
1607 module A( op ) where
1608 class C a where
1609 op :: a -> a
1610
1611 module B where
1612 import A
1613 f = ..op...
1614
1615 Then the minimal import for module B is
1616 import A( op )
1617 not
1618 import A( C( op ) )
1619 which we would usually generate if C was exported from B. Hence
1620 the (x `elem` xs) test when deciding what to generate.
1621
1622
1623 Note [Overloaded field import]
1624 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1625 On the other hand, if we have
1626
1627 {-# LANGUAGE DuplicateRecordFields #-}
1628 module A where
1629 data T = MkT { foo :: Int }
1630
1631 module B where
1632 import A
1633 f = ...foo...
1634
1635 then the minimal import for module B must be
1636 import A ( T(foo) )
1637 because when DuplicateRecordFields is enabled, field selectors are
1638 not in scope without their enclosing datatype.
1639
1640
1641 ************************************************************************
1642 * *
1643 \subsection{Errors}
1644 * *
1645 ************************************************************************
1646 -}
1647
1648 qualImportItemErr :: RdrName -> SDoc
1649 qualImportItemErr rdr
1650 = hang (text "Illegal qualified name in import item:")
1651 2 (ppr rdr)
1652
1653 badImportItemErrStd :: ModIface -> ImpDeclSpec -> IE GhcPs -> SDoc
1654 badImportItemErrStd iface decl_spec ie
1655 = sep [text "Module", quotes (ppr (is_mod decl_spec)), source_import,
1656 text "does not export", quotes (ppr ie)]
1657 where
1658 source_import | mi_boot iface = text "(hi-boot interface)"
1659 | otherwise = Outputable.empty
1660
1661 badImportItemErrDataCon :: OccName -> ModIface -> ImpDeclSpec -> IE GhcPs
1662 -> SDoc
1663 badImportItemErrDataCon dataType_occ iface decl_spec ie
1664 = vcat [ text "In module"
1665 <+> quotes (ppr (is_mod decl_spec))
1666 <+> source_import <> colon
1667 , nest 2 $ quotes datacon
1668 <+> text "is a data constructor of"
1669 <+> quotes dataType
1670 , text "To import it use"
1671 , nest 2 $ text "import"
1672 <+> ppr (is_mod decl_spec)
1673 <> parens_sp (dataType <> parens_sp datacon)
1674 , text "or"
1675 , nest 2 $ text "import"
1676 <+> ppr (is_mod decl_spec)
1677 <> parens_sp (dataType <> text "(..)")
1678 ]
1679 where
1680 datacon_occ = rdrNameOcc $ ieName ie
1681 datacon = parenSymOcc datacon_occ (ppr datacon_occ)
1682 dataType = parenSymOcc dataType_occ (ppr dataType_occ)
1683 source_import | mi_boot iface = text "(hi-boot interface)"
1684 | otherwise = Outputable.empty
1685 parens_sp d = parens (space <> d <> space) -- T( f,g )
1686
1687 badImportItemErr :: ModIface -> ImpDeclSpec -> IE GhcPs -> [AvailInfo] -> SDoc
1688 badImportItemErr iface decl_spec ie avails
1689 = case find checkIfDataCon avails of
1690 Just con -> badImportItemErrDataCon (availOccName con) iface decl_spec ie
1691 Nothing -> badImportItemErrStd iface decl_spec ie
1692 where
1693 checkIfDataCon (AvailTC _ ns _) =
1694 case find (\n -> importedFS == nameOccNameFS n) ns of
1695 Just n -> isDataConName n
1696 Nothing -> False
1697 checkIfDataCon _ = False
1698 availOccName = nameOccName . availName
1699 nameOccNameFS = occNameFS . nameOccName
1700 importedFS = occNameFS . rdrNameOcc $ ieName ie
1701
1702 illegalImportItemErr :: SDoc
1703 illegalImportItemErr = text "Illegal import item"
1704
1705 dodgyImportWarn :: RdrName -> SDoc
1706 dodgyImportWarn item
1707 = dodgyMsg (text "import") item (dodgyMsgInsert item :: IE GhcPs)
1708
1709 dodgyMsg :: (Outputable a, Outputable b) => SDoc -> a -> b -> SDoc
1710 dodgyMsg kind tc ie
1711 = sep [ text "The" <+> kind <+> ptext (sLit "item")
1712 -- <+> quotes (ppr (IEThingAll (noLoc (IEName $ noLoc tc))))
1713 <+> quotes (ppr ie)
1714 <+> text "suggests that",
1715 quotes (ppr tc) <+> text "has (in-scope) constructors or class methods,",
1716 text "but it has none" ]
1717
1718 dodgyMsgInsert :: forall p . IdP (GhcPass p) -> IE (GhcPass p)
1719 dodgyMsgInsert tc = IEThingAll noExt ii
1720 where
1721 ii :: LIEWrappedName (IdP (GhcPass p))
1722 ii = noLoc (IEName $ noLoc tc)
1723
1724
1725 addDupDeclErr :: [GlobalRdrElt] -> TcRn ()
1726 addDupDeclErr [] = panic "addDupDeclErr: empty list"
1727 addDupDeclErr gres@(gre : _)
1728 = addErrAt (getSrcSpan (last sorted_names)) $
1729 -- Report the error at the later location
1730 vcat [text "Multiple declarations of" <+>
1731 quotes (ppr (nameOccName name)),
1732 -- NB. print the OccName, not the Name, because the
1733 -- latter might not be in scope in the RdrEnv and so will
1734 -- be printed qualified.
1735 text "Declared at:" <+>
1736 vcat (map (ppr . nameSrcLoc) sorted_names)]
1737 where
1738 name = gre_name gre
1739 sorted_names = sortWith nameSrcLoc (map gre_name gres)
1740
1741
1742
1743 missingImportListWarn :: ModuleName -> SDoc
1744 missingImportListWarn mod
1745 = text "The module" <+> quotes (ppr mod) <+> ptext (sLit "does not have an explicit import list")
1746
1747 missingImportListItem :: IE GhcPs -> SDoc
1748 missingImportListItem ie
1749 = text "The import item" <+> quotes (ppr ie) <+> ptext (sLit "does not have an explicit import list")
1750
1751 moduleWarn :: ModuleName -> WarningTxt -> SDoc
1752 moduleWarn mod (WarningTxt _ txt)
1753 = sep [ text "Module" <+> quotes (ppr mod) <> ptext (sLit ":"),
1754 nest 2 (vcat (map (ppr . sl_fs . unLoc) txt)) ]
1755 moduleWarn mod (DeprecatedTxt _ txt)
1756 = sep [ text "Module" <+> quotes (ppr mod)
1757 <+> text "is deprecated:",
1758 nest 2 (vcat (map (ppr . sl_fs . unLoc) txt)) ]
1759
1760 packageImportErr :: SDoc
1761 packageImportErr
1762 = text "Package-qualified imports are not enabled; use PackageImports"
1763
1764 -- This data decl will parse OK
1765 -- data T = a Int
1766 -- treating "a" as the constructor.
1767 -- It is really hard to make the parser spot this malformation.
1768 -- So the renamer has to check that the constructor is legal
1769 --
1770 -- We can get an operator as the constructor, even in the prefix form:
1771 -- data T = :% Int Int
1772 -- from interface files, which always print in prefix form
1773
1774 checkConName :: RdrName -> TcRn ()
1775 checkConName name = checkErr (isRdrDataCon name) (badDataCon name)
1776
1777 badDataCon :: RdrName -> SDoc
1778 badDataCon name
1779 = hsep [text "Illegal data constructor name", quotes (ppr name)]