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