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